1 install JDK (java developer kit)
install eclipse from eclipse.org choose the java developers install option
check your java version : https://www.youtube.com/watch?v=UokTaTwckDw
also C:\Users\Lenovo\eclipse-workspace
the eclipse folder created by the installer is where your project files get stored
2 when eclipse fires up choose new java project or from file, new, java, java project.
right click the project name in the solution explorer, new, to add packages to contain your classes or to
create a class. when you choose a class make sure to camel case its name and without spaces. also, check
static main void to define it as the main class.
package naming convention : com.companyName.projectName
2.2 to change class name :
right click class on the solution explorer, refactor, rename
2.3 comment in out selected code lines : ctrl + /
3 hello world code :
ctrl + f11 to run code
4 making the intelliJ intellisense more sensitive : tool strip, window, preferences , java, editor, content assistent,
auto activation trigger, add abcdefghijklmnopqrstuvwxwz and in upper case and @_ to .
5 var declaration :
int x = 5;
double d1 = 2.5;
int y = (Int)d1; // explicit conversion
byte b1 = 12;
int b2 = b1; // implicit conversion
6 operators
xor operator 5>4 ^ 4==4 //false
7 randomizer :
math.random(); // returns double 0 to 1
8 get user input :
import java.util.Scanner; // at start of code
Scanner s1 = new Scanner(System.in); // after typing this intelliJ should add the import code anyways
int x = s1.nextInt(); // .next(); to input a string
9 shortcut if conditional :
string m1 = (3>1 ? "it is true":"it is false");
10 string jutsus :
compare :
str1.equals(str4);
string old style declare :
str5 = new String("moti rulz");
str.toLowerCase();// you know what it returns
string megazord :
prints :
hi king moti welcome 5
see string format java list for more data types (%s %d)
11 system.nanoTime();
12 loop beef ups:
break; // exits loop while its running
continue; // exit next lines of code in the loop and continue loops execusion
13 arrays :
int[] arr1 = {2,3,4}; // initialize array
System.out.println(Arrays.toString(arr1)); // print array
or
int arr2[]= {1,2,45};
System.out.println(Arrays.toString(arr2)); // full array print for 1D arrays
refer to organ in the array :
// array[x];
int[] arr1 = {2,3,4}; // initialize array
System.out.println(arr1[0]); // prints 2
or
int[] arr1 = {2,3,4}; // initialize array
arr1 = new int[2]; // recreate array you can also : int[] a1 = new int[size integer]
System.out.println(arr1[1]); // prints 0
int[][] g = new int[2][5]; // 2D array
g[1][3] = 5; // access organ
System.out.println(g[0].length); // get inner array size
shallow copy : ar2 = ar1; // changes to either array effect other array
deep copy array :
array2 = Arrays.copyOf(array1,array1.length);
sort array :
Arrays.sort(arr); // sorts arr, no need to return value it is sent by reference (shallow copy)
14 IDE jutsus :
intelliJ : when you type the editor will offer to auto complete code lines, choose code line and enter.
14.2 enable step into and variable watch debug option : click stripe to the left of the code line numbers to
insert a break point, click spider on tool strip next to run code button. right click close to close.
15 methodes :
16 string jutsus :
String sX = "hello";
char c1 = sX.charAt(2); // refer to string as array
char[] arr = sX.toCharArray(); // also refer to string as array
17 create and use object classes, examplified with the deck class that uses the card class
when adding those classes do not check the public static void main option which you check for the Main class:
card class :
[/code]
package gambit;
public class Card {
String type, color;
int level;
public void printCard() {
switch (level) {
case 1:System.out.println("Ace of " + type);break;
case 11:System.out.println("prince of " + type);break;
case 12:System.out.println("queen of " + type);break;
case 13:System.out.println("king of " + type);break;
default:System.out.println(color + " " + type + " level " + level);break;
}
}
}
[/code]
deck class :
Main class :
18 reseting the solution explorer window :
from the tool strip : window,show view, package explorer
19 class with constructor getter and setter (morse code example)
using getters and setters to access private(an acess modifier) class organs helps prevent code injections
type shift + alt + s to auto generate a constructor, getters and or setters, accourding to your
customization.
Code:
main :
Code:
20 exit the debug view :
debug, java browsing, next to the debug spider picture at the top right of the screen, there is a little square that says java
when you mouse hover it.
21 using a class from a different package :
import packageName;
import import packageName.*; // import all files
import packageName.className;
22 const variable :
final double PI = 3.141;
declaring a methode as final makes it unoverridable.
23 enum : declare a group of string const to access via intelliJ :
rightClick package name, enum :
Main :
24 classes and inheritance :
base class (super class):
sub class (with an example for overidding toString methode):
Main class :
25 singleton is a object that can be created only x amount of times, usually once.
used for objects like server connection and rare game objects.
singleton class :
Code:
summoning the singleton object :
Code:
26 polymorphism is the creation of a controller, the base class, that is used to
utilize the methodes of its various Derived sub classes (objects).
polymorphism, exampled via the shape class, and its overridden surface area methode,
in the Main class.
shape super class :
Code:
square sub class of shape
Code:
rectangle sub class of square
Code:
triangle sub class of shape
Code:
circle class extends (sub class of) shape super class:
Code:
main class plays around with the classes using polymorphism to refer to all objects as a shape
and using the override methods of the sub classes even though they were declared as the super class :
Code:
27 get original declared class name (sub class even if it was polymorphism declared into a base class object):
objectName.getClass().toString();
28 the object super class : all objects inherit from it.
class java.lang.objects. to override a super class methode from the derived class, type the methode name
and it will auto comlete. tyoe to, to auto complete the toString override.
the object class also have the object.finalize() methode to end a variable you finished using, though java does this
automatically.
get object class name :
c1.getClass().toString().substring(6); // c1 = object name.
protected methode : clone(), returns object
boolean : equals()
int : hashCode() // returns hash code value for the object.
30 brute force counter :
31 generic lv1 :
main :
lv2 :
a generic class :
main :
32 abstract class :
an abs class doesn't have to have a constructor.
Code:
public abstract class AbsShape {
public abstract int Area();
}
2nd class :
Code:
Code:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbsShape ribua = new Square(5);
System.out.println("area: " + ribua.Area());
}
}
example 2 :
an abstract class doesn't have to have a constructor.
Code:
derived class :
Code:
public class DerivedClass extends BaseClass{
@Override
public void AbstractMethode() {this.x++;this.y++;}
}
main :
Code:
public class Main {
public static void main(String[] args) {
BaseClass patamon = new DerivedClass();
patamon.AbstractMethode();
System.out.println(patamon.getX() + " " + patamon.getY());
}
}
output : 101 151
33 interface :
an interface is like an item an object class can be equiped with.
interface contains methode signatures that has to be implemented in your object class.
right click the project folder in the package explorer window, interface.
Code:
public interface MyCalc {
public int Add(int x, int y);
public int subtract(int x, int y);
public int Multiple(int x, int y);
public int div(int x, int y);
}
2nd interface :
Code:
public interface MyCalc2 {
public int Multiple(int x, int y);
public int sum(int ... sigma);
}
create a class and add implements MyCalc,MyCalc2.
next click the error line under the class name and click add unimplemented methods.
finnally fill in the methodes body.
to get :
Code:
and creat some main class to test MainClass
34 java class with learnability :
written by moti barski
main :
Code:
car class :
Code:
algorithm class :
Code:
fixer bot class :
Code:
about the output :
Suzukitruefalsefalsefalse truetruetruetrue@3 x =
car + car state of parts @ part number to repair, amount of repairs = amount of x
35 generics level1 :
main :
install eclipse from eclipse.org choose the java developers install option
check your java version : https://www.youtube.com/watch?v=UokTaTwckDw
also C:\Users\Lenovo\eclipse-workspace
the eclipse folder created by the installer is where your project files get stored
2 when eclipse fires up choose new java project or from file, new, java, java project.
right click the project name in the solution explorer, new, to add packages to contain your classes or to
create a class. when you choose a class make sure to camel case its name and without spaces. also, check
static main void to define it as the main class.
package naming convention : com.companyName.projectName
2.2 to change class name :
right click class on the solution explorer, refactor, rename
2.3 comment in out selected code lines : ctrl + /
3 hello world code :
Code:
package PL;
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
}
}
ctrl + f11 to run code
4 making the intelliJ intellisense more sensitive : tool strip, window, preferences , java, editor, content assistent,
auto activation trigger, add abcdefghijklmnopqrstuvwxwz and in upper case and @_ to .
5 var declaration :
int x = 5;
double d1 = 2.5;
int y = (Int)d1; // explicit conversion
byte b1 = 12;
int b2 = b1; // implicit conversion
6 operators
xor operator 5>4 ^ 4==4 //false
7 randomizer :
math.random(); // returns double 0 to 1
8 get user input :
import java.util.Scanner; // at start of code
Scanner s1 = new Scanner(System.in); // after typing this intelliJ should add the import code anyways
int x = s1.nextInt(); // .next(); to input a string
9 shortcut if conditional :
string m1 = (3>1 ? "it is true":"it is false");
10 string jutsus :
compare :
str1.equals(str4);
string old style declare :
str5 = new String("moti rulz");
str.toLowerCase();// you know what it returns
string megazord :
Code:
package PL;
import java.util.Scanner;
import static java.lang.System.out;
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = String.format("hi %s %s welcome %d", "king","moti",5);
System.out.println(s1);
}
}
prints :
hi king moti welcome 5
see string format java list for more data types (%s %d)
11 system.nanoTime();
12 loop beef ups:
break; // exits loop while its running
continue; // exit next lines of code in the loop and continue loops execusion
13 arrays :
int[] arr1 = {2,3,4}; // initialize array
System.out.println(Arrays.toString(arr1)); // print array
or
int arr2[]= {1,2,45};
System.out.println(Arrays.toString(arr2)); // full array print for 1D arrays
refer to organ in the array :
// array[x];
int[] arr1 = {2,3,4}; // initialize array
System.out.println(arr1[0]); // prints 2
or
int[] arr1 = {2,3,4}; // initialize array
arr1 = new int[2]; // recreate array you can also : int[] a1 = new int[size integer]
System.out.println(arr1[1]); // prints 0
int[][] g = new int[2][5]; // 2D array
g[1][3] = 5; // access organ
System.out.println(g[0].length); // get inner array size
shallow copy : ar2 = ar1; // changes to either array effect other array
deep copy array :
array2 = Arrays.copyOf(array1,array1.length);
sort array :
Arrays.sort(arr); // sorts arr, no need to return value it is sent by reference (shallow copy)
14 IDE jutsus :
intelliJ : when you type the editor will offer to auto complete code lines, choose code line and enter.
14.2 enable step into and variable watch debug option : click stripe to the left of the code line numbers to
insert a break point, click spider on tool strip next to run code button. right click close to close.
15 methodes :
Code:
package t3;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class ttGood {
static String var1 = "hadouken";
public static void main(String[] args) {
// TODO Auto-generated method stub
printMe(); // STATIC FUNCTION CAN ONLY USE static functions
printMe("moti");
hadouken();
hadouken(); // prints : hadouken!!
System.out.println(futsujutsu(3,4)); // prints 7
int[] a2 = {1,2,3,4};
System.out.println(sumArray(a2)); //prints 10
System.out.println(sumArray2(a2));
System.out.println(sumArray2(1,2,3,4,5)); // prints 15
}
public static void printMe() {System.out.println(("rulz"));} // sub returns nothing
public static void printMe(String name) {{System.out.println((name + " rulz"));}}
public static void hadouken() {
var1+="!";
System.out.println((var1));}
public static int futsujutsu(int x,int y) {return x+y;} // shared function
public static int sumArray(int[] a1) {
int sum=0; // for each loop called for int in java :
for (int h:a1) {
sum+=h;
}
return sum;
} // shared function
public static int sumArray2(int...nums) // treat array of variables as an object = var args
{
int sum=0; // for each loop called for int in java :
for (int h:nums) {
sum+=h;
}
return sum;
} // shared function
public static int[] dec(int[] a3) // array returning function
{
int[] newArray = Arrays.copyOf(a3, a3.length);
for (int i = 0; i < newArray.length; i++) {
newArray[i]+=1;
}
return newArray;
}
}
16 string jutsus :
String sX = "hello";
char c1 = sX.charAt(2); // refer to string as array
char[] arr = sX.toCharArray(); // also refer to string as array
17 create and use object classes, examplified with the deck class that uses the card class
when adding those classes do not check the public static void main option which you check for the Main class:
card class :
[/code]
package gambit;
public class Card {
String type, color;
int level;
public void printCard() {
switch (level) {
case 1:System.out.println("Ace of " + type);break;
case 11:System.out.println("prince of " + type);break;
case 12:System.out.println("queen of " + type);break;
case 13:System.out.println("king of " + type);break;
default:System.out.println(color + " " + type + " level " + level);break;
}
}
}
[/code]
deck class :
Code:
package gambit;
public class Deck {
Card[] cards = new Card[52];
public void initDeck() {
for (int i = 0; i < 13; i++) {
cards[i] = new Card();
cards[i].type = "clubs";
cards[i].color = "black";
cards[i].level = i+1;
}
for (int i = 13; i < 26; i++) {
cards[i] = new Card();
cards[i].type = "hearts";
cards[i].color = "red";
cards[i].level = i-12;
}
for (int i = 26; i < 39; i++) {
cards[i] = new Card();
cards[i].type = "spades";
cards[i].color = "black";
cards[i].level = i-25;
}
for (int i = 39; i < 52; i++) {
cards[i] = new Card();
cards[i].type = "diamonds";
cards[i].color = "red";
cards[i].level = i-38;
}
}
public void printDeck() {
for (int i = 0; i < 52; i++) {
cards[i].printCard();
}
}
}
Main class :
Code:
package gambit;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Deck d1 = new Deck();
d1.initDeck();
d1.printDeck();
}
}
18 reseting the solution explorer window :
from the tool strip : window,show view, package explorer
19 class with constructor getter and setter (morse code example)
using getters and setters to access private(an acess modifier) class organs helps prevent code injections
type shift + alt + s to auto generate a constructor, getters and or setters, accourding to your
customization.
Code:
Code:
package morseCodePackage;
public class morseCode {
private String user; // click on var and type alt + shift + s then select generate getters setters
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
private static String lastMsg;
public morseCode(String user) {this.user = user;} // I'm a constructor, use this. if the param names are
// the same as the classes
public String toMorse(String msg) {lastMsg = code(msg);return this.user + " " + this.lastMsg;}
public String toHuman(String msg) {return this.user + " " + decoder(msg);}
public static String code(String msg) {
char[] arr = msg.toCharArray();
String result ="";
for (int i = 0; i < arr.length; i++) {
result += charToMorse(arr[i]);
}
return result;
}
private static String charToMorse(char x) {
String result="";
switch (x) {
case 'a': result = "*-";break;
case 'b': result = "-***";break;
case 'c': result = "-*-*";break;
case 'd': result = "-**";break;
case 'e': result = "*";break;
case 'f': result = "**-*";break;
case 'g': result = "--*";break;
case 'h': result = "****";break;
case 'i': result = "**";break;
case 'j': result = "*---";break;
case 'k': result = "-*-";break;
case 'l': result = "*-**";break;
case 'm': result = "--";break;
case 'n': result = "-*";break;
case 'o': result = "---";break;
case 'p': result = "*--*";break;
case 'q': result = "--*-";break;
case 'r': result = "*-*";break;
case 's': result = "***";break;
case 't': result = "-";break;
case 'u': result = "**-";break;
case 'v': result = "***-";break;
case 'w': result = "*--";break;
case 'x': result = "-**-";break;
case 'y': result = "-*--";break;
case 'z': result = "--**";break;
case '0': result = "-----";break;
case '1': result = "*----";break;
case '2': result = "**---";break;
case '3': result = "***--";break;
case '4': result = "****-";break;
case '5': result = "*****";break;
case '6': result = "-****";break;
case '7': result = "--***";break;
case '8': result = "---**";break;
case '9': result = "----*";break;
case '.': result = "*-*-*-";break;
case ',': result = "--**--";break;
case '?': result = "**--**";break;
case ' ': result = "/";break;
default:
break;
}
return result + "/";
}
public static String decoder(String msg) {
String morseChr ="";
String result = "";
char[] arr = msg.toCharArray();
for (int i = 0; i < arr.length; i++) {
if(arr[i]!='/') {morseChr += arr[i];}
else {result += morseCharToChar(morseChr);morseChr="";}
}
result = result.replaceAll(" ", " ");
return result;
}
private static char morseCharToChar(String x) {
char result='@';
switch (x) {
case "*-": result = 'a';break;
case "-***": result = 'b';break;
case "-*-*": result = 'c';break;
case "-**": result = 'd';break;
case "*": result = 'e';break;
case "**-*": result ='f' ;break;
case "--*": result = 'g';break;
case "****": result = 'h';break;
case "**": result = 'i';break;
case "*---": result = 'j';break;
case "-*-": result = 'k';break;
case "*-**": result = 'l';break;
case "--": result = 'm';break;
case "-*": result = 'n';break;
case "---": result = 'o';break;
case "*--*": result = 'p';break;
case "--*-": result = 'q';break;
case "*-*": result = 'r';break;
case "***": result = 's';break;
case "-": result = 't';break;
case "**-": result = 'u';break;
case "***-": result = 'v';break;
case "*--": result = 'w';break;
case "-**-": result = 'x';break;
case "-*--": result = 'y';break;
case "--**": result = 'z';break;
case "-----": result = '0';break;
case "*----": result = '1';break;
case "**---": result = '2';break;
case "***--": result = '3';break;
case "****-": result = '4';break;
case "*****": result = '5';break;
case "-****": result = '6';break;
case "--***": result = '7';break;
case "---**": result = '8';break;
case "----*": result = '9';break;
case "*-*-*-": result = '.';break;
case "--**--": result =',' ;break;
case "**--**": result = '?';break;
case "/": result = ' ';break;
default:
break;
}
if(result == '@') {result = ' ';}
return result;
}
public static void describeME() {System.out.println("I'm a class that can code and decode morse code");}
}
main :
Code:
Code:
package morseCodePackage;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(morseCode.code("hadouken"));
System.out.println(morseCode.code("over 9000"));
String n1 = morseCode.code("hadouken");
System.out.println(morseCode.decoder(n1));
morseCode mc1 = new morseCode("moti");
System.out.println(mc1.toMorse("souryuken"));
System.out.println(mc1.toHuman("****/*-/-**/---/**-/-*-/*/-*/"));
morseCode.describeME();
}
}
20 exit the debug view :
debug, java browsing, next to the debug spider picture at the top right of the screen, there is a little square that says java
when you mouse hover it.
21 using a class from a different package :
import packageName;
import import packageName.*; // import all files
import packageName.className;
22 const variable :
final double PI = 3.141;
declaring a methode as final makes it unoverridable.
23 enum : declare a group of string const to access via intelliJ :
rightClick package name, enum :
Code:
package pokemon;
public enum Day {
SUN,MON,TUE,WED,THU,FRI,SAT
}
Main :
Code:
public class Main {
public static void dayOfWeek(Day d) {
switch(d) {
case SUN:System.out.println("sunday");break;
}
}
public static void main(String[] args) {
dayOfWeek(Day.SUN);
Day[] d1 = Day.values(); // create a days array
System.out.println(Arrays.toString(d1));
System.out.println(Day.FRI.ordinal());
System.out.println(d1[Day.SUN.ordinal()+3]);
}
}
24 classes and inheritance :
base class (super class):
Code:
package pokemon;
public class PokEgg {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PokEgg(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}
}
sub class (with an example for overidding toString methode):
Code:
package pokemon;
import java.awt.Window.Type;
import java.util.function.ToDoubleBiFunction;
public class Pokemon extends PokEgg {
private String cry;
private int level;
public String getCry() {
return cry;
}
public void setCry(String cry) {
this.cry = cry;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public Pokemon(String name, String cry, int level) {
// TODO Auto-generated constructor stub
super(name);
this.cry = cry;
this.level = level;
}
/**
* type slash astrics astrics to enable documentation
*/
public String toString() {return super.getName() + "\n level : " + this.level +
" says: "
+ "" + this.cry;
}
}
Main class :
Code:
package pokemon;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Pokemon pickachu = new Pokemon("lars","pickach yu", 5);
System.out.println(pickachu.toString());
}
}
25 singleton is a object that can be created only x amount of times, usually once.
used for objects like server connection and rare game objects.
singleton class :
Code:
Code:
package singleton;
public class Singleton {
private static Singleton singleton; // array this to get x number of singletons enabled
private Singleton() {
System.out.println("new singleton instace has been created");
}
public static Singleton newInstance() {
if(singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
summoning the singleton object :
Code:
Code:
package singleton;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton sing1 = Singleton.newInstance(); // can only create 1, all others point to the same object
}
}
26 polymorphism is the creation of a controller, the base class, that is used to
utilize the methodes of its various Derived sub classes (objects).
polymorphism, exampled via the shape class, and its overridden surface area methode,
in the Main class.
shape super class :
Code:
Code:
package com.shapes.objects;
public class Shape {
public Shape() {
// TODO Auto-generated constructor stub
}
public double surfaceArea() {
return 0;
}
}
square sub class of shape
Code:
Code:
package com.shapes.objects;
public class Square extends Shape {
private double height;
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Square(double height) {
this.height = height;
}
public double surfaceArea() {
return height*height;
}
}
rectangle sub class of square
Code:
Code:
package com.shapes.objects;
public class Rectangle extends Square{
private double width;
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public Rectangle(double height, double width) {
super(height);
this.width = width;
}
@Override
public double surfaceArea() {
return super.getHeight()*width;
}
}
triangle sub class of shape
Code:
Code:
package com.shapes.objects;
public class Triangle extends Shape {
private double height;
private double width;
public Triangle(double height, double width) {
super();
this.height = height;
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
@Override
public double surfaceArea() {
return (height*width)/2;
}
}
circle class extends (sub class of) shape super class:
Code:
Code:
package com.shapes.objects;
public class Circle extends Shape {
private double Radius;
public double getRadius() {
return Radius;
}
public void setRadius(double radius) {
Radius = radius;
}
public Circle(double radius) {
super();
Radius = radius;
}
public double surfaceArea() {
return Radius*Radius*3.1415;
}
}
main class plays around with the classes using polymorphism to refer to all objects as a shape
and using the override methods of the sub classes even though they were declared as the super class :
Code:
Code:
package com.shapes.objects;
import java.util.Scanner;
import org.w3c.dom.css.Rect;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape sh1 = new Shape();
System.out.println(sh1.surfaceArea());
Rectangle rec1 = new Rectangle(10, 5);
System.out.println(rec1.surfaceArea());
Shape sh2 = rec1;
System.out.println(sh2.surfaceArea());
Shape[] shapeArray = new Shape[5];
for (int i = 0; i < shapeArray.length; i++) {
System.out.println("enter shape");
Scanner scanner2 = new Scanner(System.in);
String x2 = scanner2.next();
shapeArray[i] = getShape(x2);
System.out.println(shapeArray[i].surfaceArea());
}
}
public static Shape getShape(String form) {
Shape result = null;
Scanner scanner11 = new Scanner(System.in);
switch (form) {
case "square":
System.out.println("enter square side size");
double x1 = scanner11.nextDouble();
return new Square(x1);
case "circle":
System.out.println("enter circle radius");
double Radius1 = scanner11.nextDouble();
return new Circle(Radius1);
case "rectangle":
System.out.println("enter rectangle height");
double height = scanner11.nextDouble();
System.out.println("enter rectangle width");
double width = scanner11.nextDouble();
return new Rectangle(height, width);
case "triangle":
System.out.println("enter triangle height");
double Theight = scanner11.nextDouble();
System.out.println("enter triangle width");
double Twidth = scanner11.nextDouble();
return new Triangle(Theight, Twidth);
default:
break;
}
return result;
}
}
27 get original declared class name (sub class even if it was polymorphism declared into a base class object):
objectName.getClass().toString();
28 the object super class : all objects inherit from it.
class java.lang.objects. to override a super class methode from the derived class, type the methode name
and it will auto comlete. tyoe to, to auto complete the toString override.
the object class also have the object.finalize() methode to end a variable you finished using, though java does this
automatically.
get object class name :
c1.getClass().toString().substring(6); // c1 = object name.
protected methode : clone(), returns object
boolean : equals()
int : hashCode() // returns hash code value for the object.
30 brute force counter :
Code:
String arr[] = {"0","a","b","c"};
String result = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
for (int j2 = 0; j2 < arr.length; j2++) {
result += arr[i] + arr[j] + arr[j2] + " \n";
}
}
}
System.out.println(result);
31 generic lv1 :
Code:
package gener;
public class myGeneric {
public static <T> void Print(T[] input) {
for (T t: input){
System.out.println(t);
}
}
}
main :
Code:
package gener;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String arr[] = {"0","a","b","c"};
myGeneric.Print(arr);
}
}
lv2 :
a generic class :
Code:
package gener;
public class myGeneric<T> {
Object[] myType = new Object[0];
public void add(T value) {
Object[] temp = new Object[myType.length+1];
for (int i = 0; i < temp.length - 1; i++) {
temp[i]= (T)myType[i];
}
temp[temp.length -1]= value;
myType = new Object[temp.length];
for (int i = 0; i < temp.length; i++) {
myType[i] = (T)temp[i];
}
}
public void printArray() {
for (int i = 0; i < myType.length; i++) {
System.out.println((T)myType[i]);
}
}
public static <T> void Print(T[] input) {
for (T t: input){
System.out.println(t);
}
}
public T getElement(int index) {return (T)myType[index];}
@Override
public String toString() {
String result ="";
for (int i = 0; i < myType.length; i++) {
result+=(T)myType[i] + " \n";
}
return result;
}
public int indexOf(T element) {
int result = -1;
for (int i = 0; i < myType.length; i++) {
if((T)myType[i]==element) {return i;}
}
return result;
}
}
main :
Code:
package gener;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String arr[] = {"0","a","b","c"};
myGeneric.Print(arr);
myGeneric<String> x = new myGeneric<String>(); // Integer for int
x.add("1");
x.add("2");
x.printArray();
System.out.println(x.getElement(1));
System.out.println("toString: " + x.toString());
System.out.println("index of 1 is :" + x.indexOf("1"));
}
}
32 abstract class :
an abs class doesn't have to have a constructor.
Code:
public abstract class AbsShape {
public abstract int Area();
}
2nd class :
Code:
Code:
import java.util.regex.Matcher;
public class Square extends AbsShape{
private int side;
public int getSide() {
return side;
}
public void setSide(int side) {
this.side = side;
}
public Square(int side) {
super();
this.side = side;
}
@Override
public int Area() {
// TODO Auto-generated method stub
return (int)Math.pow(side, 2); // powe ^
}
}
Code:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbsShape ribua = new Square(5);
System.out.println("area: " + ribua.Area());
}
}
example 2 :
an abstract class doesn't have to have a constructor.
Code:
Code:
public abstract class BaseClass {
protected int x = 100; // visible to this base class and sub classes(that extend it)
protected int y = 150;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public abstract void AbstractMethode();
}
derived class :
Code:
public class DerivedClass extends BaseClass{
@Override
public void AbstractMethode() {this.x++;this.y++;}
}
main :
Code:
public class Main {
public static void main(String[] args) {
BaseClass patamon = new DerivedClass();
patamon.AbstractMethode();
System.out.println(patamon.getX() + " " + patamon.getY());
}
}
output : 101 151
33 interface :
an interface is like an item an object class can be equiped with.
interface contains methode signatures that has to be implemented in your object class.
right click the project folder in the package explorer window, interface.
Code:
public interface MyCalc {
public int Add(int x, int y);
public int subtract(int x, int y);
public int Multiple(int x, int y);
public int div(int x, int y);
}
2nd interface :
Code:
public interface MyCalc2 {
public int Multiple(int x, int y);
public int sum(int ... sigma);
}
create a class and add implements MyCalc,MyCalc2.
next click the error line under the class name and click add unimplemented methods.
finnally fill in the methodes body.
to get :
Code:
Code:
public class MainClass implements MyCalc,MyCalc2 {
@Override
public int sum(int... sigma) {
// TODO Auto-generated method stub
int result = 0;
for (int i = 0; i < sigma.length; i++) {
result += sigma[i];
}
return result;
}
@Override
public int Add(int x, int y) {
// TODO Auto-generated method stub
return x+y;
}
@Override
public int subtract(int x, int y) {
// TODO Auto-generated method stub
return x-y;
}
@Override
public int Multiple(int x, int y) {
// TODO Auto-generated method stub
return x*y;
}
@Override
public int div(int x, int y) {
// TODO Auto-generated method stub
return x/y;
}
}
and creat some main class to test MainClass
34 java class with learnability :
written by moti barski
main :
Code:
Code:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class Main {
public static void main(String[] args) {
boolean[] parts = {true,true,true,false};
Car x = new Suzuki(parts);
FixerBot fb1 = new FixerBot();
fb1.gainExp(x);
fb1.gainExp(new Suzuki(parts));
fb1.gainExp(new Suzuki(parts));
fb1.getRepairProphesy(new Suzuki(parts));
}
}
car class :
Code:
Code:
import java.awt.Point;
import java.util.Arrays;
import java.util.Random;
public class Car {
public boolean parts[] = new boolean[4];
// steer, spoke, tire, wheel
public Car(boolean[] parts) {
super();
this.parts = Arrays.copyOf(parts, parts.length);
effects();
}
private void effects() {
if(!parts[3]) {parts[2]=false;parts[1] = false;}
}
public void fixWithEffects(int part) {
parts[part] = true;
if(part == 3) {parts[2]=true;parts[1] = true;}
}
public int repairSuggestion() {
int counter = 0;
for (int i = 0; i < parts.length; i++) {
if(!parts[i]) {counter++;}
}
int counter2 = 0;
int brokenParts[] = new int[counter];
for (int i = 0; i < parts.length; i++) {
if(!parts[i]) {brokenParts[counter2]=i;counter2++;}
}
Random rn = new Random();
int answer = rn.nextInt(counter);
return brokenParts[answer];
}
public boolean working() {
for (int i = 0; i < parts.length; i++) {
if(!parts[i]) {return false;}
}
return true;
}
public String getState() {
String result = "";
for (int i = 0; i < parts.length; i++) {
result += parts[i] + "";
}
return result;
}
}
Suzuki car class, inherits from car class :
Code:
import java.awt.Point;
import java.sql.Ref;
public class Suzuki extends Car {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Suzuki(boolean[] parts) {
super(parts);
// TODO Auto-generated constructor stub
}
}
algorithm class :
Code:
Code:
import java.awt.Point;
import java.util.Arrays;
public class AlgMatrix {
public String[][] states= new String[10][10];
//public String[][] actions= new String[10][10];
public void defaulter() {
for (int i = 0; i < states.length; i++) {
for (int j = 0; j < states[0].length -1; j++) {
states[i][j] = "";
}
}
for (int i = 0; i < states.length; i++) {
states[i][9] = "xxxxxxxxxxxxxxxxxxxx";
}
}
public Point StateLocate(String str) {
Point tP = new Point(1000, 1000);
int sl = states.length;
String str2="";
for (int i = 0; i < sl; i++) {
for (int j = 0; j < sl-1; j++) {
str2 = states[i][j];
if(str2 != null) {if(str2.contains(str)) {tP.x = i;tP.y= j;break;}}
}
}
return tP;
}
public void sortMe() {
}
}
fixer bot class :
Code:
Code:
import java.awt.Point;
import java.awt.image.ReplicateScaleFilter;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Hashtable;
import org.omg.CORBA.PUBLIC_MEMBER;
public class FixerBot {
public int expBarrier = 100;
public AlgMatrix aMatrix = new AlgMatrix();
Dictionary dic1 = new Hashtable();
private String carKey(Car c1) {
String Key = c1.getClass().toString().substring(6);
for (int i = 0; i < c1.parts.length; i++) {
Key += c1.parts[i] + "";
}
if(dic1.get(Key)==null) {aMatrix.defaulter();dic1.put(Key, aMatrix);}
return Key;
}
public String repairCar(Car c1) {
String Key = carKey(c1);
//if too costly alg, gainExp
//repair action + print
aMatrix = (AlgMatrix)dic1.get(Key);
return Key;
}
public void getRepairProphesy(Car c1) {
String Key = carKey(c1);
aMatrix = (AlgMatrix)dic1.get(Key);
for (int i = 0; i < aMatrix.states.length; i++) {
if(aMatrix.states[0][i]!=null) {System.out.print(aMatrix.states[0][i] +" ");}
}
}
public void gainExp(Car c1) {
if(!(c1.working())) {gainExpInner(c1);}
else {System.out.println("car works");}
}
public void gainExpInner(Car c1) {
String[] sc = new String[10];
sc[0] = carKey(c1);
AlgMatrix ax = (AlgMatrix)dic1.get(sc[0]);
int sCount = 1;
int cost =0;boolean b1;
int nextFix;
boolean b3 = !(c1.working());
boolean b2;
Point tP1 = new Point(1000,1000);// change to 1;
do {
nextFix = c1.repairSuggestion();
c1.fixWithEffects(nextFix);
sc[sCount] = c1.getState() + "@" + nextFix;
sCount++;cost++;this.expBarrier--;
//AlgMatrix ax = (AlgMatrix)dic1.get(sc[0]);
tP1 = new Point(ax.StateLocate(c1.getState()));
b3 = !(c1.working());
b2 = tP1.x < 1000;
} while ((expBarrier == 0 && b2)|| b3);
if(expBarrier == 0 && b2) {
for (int i = tP1.y; i < sc.length; i++) {
sc[i] = ax.states[tP1.x][i];
cost++;
}
}
for (int i = 0; i < sc.length; i++) {
ax.states[sc.length -1][i] = sc[i];
}
String costStr ="";
for (int i = 0; i < cost; i++) {
costStr+="x";
}
ax.states[ax.states.length - 1][ax.states.length - 1] = costStr;
//ax.sortMe();
int min = 0;
int minIndex = 0;
String temp = "";
for (int i = 0; i < ax.states.length; i++) {
min = ax.states[i][ax.states.length-1].length();
minIndex = i;
for (int j = i+1; j < ax.states.length; j++) {
if(ax.states[j][ax.states.length-1].length() < min) {minIndex =j;}
}
for (int j = 0; j < ax.states.length; j++) {
if(i!=minIndex) {
temp = ax.states[i][j];
ax.states[i][j] = ax.states[minIndex][j];
ax.states[minIndex][j] = temp;}
}
}
dic1.put(sc[0], ax);
}
}
about the output :
Suzukitruefalsefalsefalse truetruetruetrue@3 x =
car + car state of parts @ part number to repair, amount of repairs = amount of x
35 generics level1 :
Code:
package gener;
public class myGeneric<T> {
Object[] myType = new Object[0];
public void add(T value) {
Object[] temp = new Object[myType.length+1];
for (int i = 0; i < temp.length - 1; i++) {
temp[i]= (T)myType[i];
}
temp[temp.length -1]= value;
myType = new Object[temp.length];
for (int i = 0; i < temp.length; i++) {
myType[i] = (T)temp[i];
}
}
public void printArray() {
for (int i = 0; i < myType.length; i++) {
System.out.println((T)myType[i]);
}
}
public static <T> void Print(T[] input) {
for (T t: input){
System.out.println(t);
}
}
public T getElement(int index) {return (T)myType[index];}
@Override
public String toString() {
String result ="";
for (int i = 0; i < myType.length; i++) {
result+=(T)myType[i] + " \n";
}
return result;
}
public int indexOf(T element) {
int result = -1;
for (int i = 0; i < myType.length; i++) {
if((T)myType[i]==element) {return i;}
}
return result;
}
}
main :
Code:
package gener;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String arr[] = {"0","a","b","c"};
myGeneric.Print(arr);
myGeneric<String> x = new myGeneric<String>();
x.add("1");
x.add("2");
x.printArray();
System.out.println(x.getElement(1));
System.out.println("toString: " + x.toString());
System.out.println("index of 1 is :" + x.indexOf("1"));
}
}