Demos
Type going from -128 to 127 | byte |
Type going from -32 768 to 32767 | short |
Type going from -2 billions to 2 billions | int |
Type going from -9 million billion to 9 million billion | long |
Type going from 4.9e-324 to 1.8e+038 | double |
Type going from 1.4e-045 to 3.4e+038 | float |
Type of double * short | double |
Type of float * byte | float |
Type of double + float | double |
Type int / short | int |
Declare and initialize table of ints | int my_table[]=new int[mytablesize]; |
Declare a table of doubles and put 1.1 and 1.2 in it | double nums[]={1.1,1.2} |
Declare and initialize a two dimension array of integers | int my_table[][]=new int[mysizex][mysizey] |
Get the maximum number of elements in a table | mytable.length |
in condition: or | || |
in condition: and | && |
in condition: equal | == |
in condition : not equal | != |
difference between & and && | with && if first condition is false, you do not check the next conditions |
if then else + assignment in one line | resultparameter=condition ? valueiftrue : valueiffalse |
if else if | if (condition1){...} else if ( condition2 ){...}else{...} |
use of the switch operator | switch(valuetotest){ case value1: ... break; case value2: case value3: ... break; default: ... } |
do while | do{ ... }while (conditiontocontinue) |
Loop through a table of int | for(int currentvalue : mytable){ use currentvalue ... } You can use currentvalue but cannot change it (read only) |
Loop through a bidimensional array of int | for (int currentable[] : mybimensionaltable){ for ( int currentvalue : currentable ){ use currentvalue } } |
Equivalent of go to | mymark : lineofcode ... continue mymark; |
What happens with b when MyClass a=new MyClass();MyClass b=a;a=null | b is still pointing to new MyClass() |
Assign parameter to class parameter | this.myvariable=myvariable; |
Passing parameter in a fonction : when by value, when by reference | Object passed by reference ( can change the value ), for the rest it is by value ( cannot change the value) |
static variable | Like a global variable. All object from the class are sharing this variable You can increment such a variable in a constructor so that you get a count of the number of objects from this class |
What cannot be done with static variables | cannot use functions or variables other than static. Cannot use this nor super |
final variable | Cannot change its value once initialized. Usually used for constants |
Put as parameter a undefined number of variables of type int. Then use all these parameters | myfunction(int ... myparams ){... for (int currentvalue : myparams){...}} |
Class B is child of class A | class B extends A{.... |
Intialize class B child of class A, taken int parameter a from A and adding int parameter b | B(int a,int b) { super(a); this.b=b; } super is the constructor of class A and must be called first |
Force the implementation of a method on child classes | abstract class classname{ abstract returntype mandatoryfunction(listofparameters); .. } |
Restriction with abstract | cannot declare abstract constructors nor abstract methods |
Inside abstract class, what the class has a non-abstract method | The method is defined in the parent class but the method is called using the object instantiated with the child class |
Declare object which type is the parent class, instantiate two child class having a function with the same name, assign object corresponding to the parent class and use first the function from the first child, then the function from the second child | ParentClass pc; ChildClassA cca=new ChildClassA(param2); ChildClassB ccb=new ChildClassB(param3); pc=cca; pc.sibblingmethod(); pc=ccb; pc.sibblingmethod(); sibblingmethod is declared as an abstract method in the parent class and is defined in two different ways in each child class |
Declare method so that child classes cannot override it | final mytype mymethodname(myparams) |
Where can you access what is private | In the same class |
Where can you access what is not marked as private nor public nor protected | In the same package |
Where can you access what is protected | Everywhere except in another package, another class ( can be child class from another package) |
use the name of class from another package | otherpackagename.classname |
How to write an interface | interface InterfaceName{ methodtype methodname(parameters); ... } |
Class A is child of B and implementing interface C | class A extends B implements C |
If A implements interface B, what will cause a compilation error. Exception | if A does not have all methods declared in B (Except if A is an abstract class), or if one or more methods in A does not match the parameters of the method in B. |
Class A and B implement interface C, have object use first method from A, then method from B | C myCObject; A myAObject=new A(parameters); B mybObject=new B(parameters); myCObject=myAObject; myCObject.myCommonMethod; myCObject=myBObject; myCObject.myCommonMethod; |
Interface and abstract class | If a class is declared as abstract and implements an interface, it does not need to implement all methods declared in the interface. Its child class will then implement the missing methods |
Constants and interfaces | You can declare constants in an interface. All classes implementing this interface will have access to these values |
What happends if a class implements an interface that is child of another interface | This class must implement methods declared in the parent interface and in the child interface |
Try catch | try{ ... }catch ( Exception e ){ use e } |
Declare which kind of exception a method can encounter | myMethod(parameters) throws ExceptionType |
Execute code whether there is an exception or not. If there is an exception, the program will stop and not execute what is after the catch clause, but will execute this code | try{ ... }catch ( Exception e ){ use e }finally{ codetoexecutealways; } |
Get the exception that occured before the thrown exception | e.getCause() |
Get the description of the exception | e.getMessage() |
Provoke an exception | throw exceptionType; |
Define your own exception accepting parameters, and use it | class MyException extends Exception{ ... myException(parameters){ ... }.. } .... throw myException(parameters); |
Keep the cause of the error before throwing it, and then use this cause when catching | ExceptionType e=new ExceptionType("exceptionname"); e.initCause(new ExceptionType("indicationofthecause"); throw e; ... catch .(ExceptionType e){ .. e.getCause(); } |
Catch two types of exception | catch( ExceptionType1 | ExceptionType2 e) |
Get nth character from a String | myString.charAt(n) n starts at 0 |
Take characters from position i to j of a string and put in an array of character, putting the first character at position k in this array | myString.getChars(i,j,myArrayOfChars,k) |
Check if two Strings are equal | string1.equals(string2) |
Check if two Strings are equal, ignoring cases | string1.equalsIgnoreCase(string2) |
Check if n characters in string 1, starting from position i, match with n charachters from string2, starting from j | string1.regionMatch(i,string2,j,n) |
Check if String1 starts with String2 | string1.startsWith(string2) |
Check if String1 ends with String2 | string1.endsWith(string2) |
Check position of first occurence of String1 is inside String2 | string2.indexOf(string1) |
Check position of last occurence of String1 is inside String2 | string2.lastIndexOf(string1) |
Check position of first occurence of String1 is inside String2 : value if cannot find | -1 |
Get part of a String | result=myString.substring(firstPosition,lastPosition); or result=myString.substring(firstPosition);to get the string from firstPosition until the end of the string |
Concatenate two strings | string3=string1.concat(string2); |
Replace character1 by character2 in a string | string2=string1.replace(character1,character2); |
Take off all leading and trailing spaces from a string | string2=string1.trim(); |
Convert a non-string to a string | string1=String.valueOf(nonstring); |
Convert a string to all upper case | string1=string2.toUpperCase(); |
Convert a string to all lower case | string1=string2.toLowerCase(); |
Class having more functionalities than string | StringBuffer |
Check if a string buffer contains a char sequence | myStringBuffer.contains(charsequence) |
Check if a string buffer is empty | myStringBuffer.contains(charsequence) |
In a string buffer, replace the first occurence of a pattern by a string | myStringBuffer.replaceFirst(regularExpression,string2) |
In a string buffer, replace the all occurences of a pattern by a string | myStringBuffer.replaceAll(regularExpression,string2) |
Append a string to a string buffer | myStringBuffer.append(myString); |
Convert a string buffer to a string | myString=myStringBuffer.toString(); |
Delete characters in a string buffer | myStringBuffer.delete(start,end); or myStringBuffer.deleteCharAt(position); |
In a string buffer, replace characters from i to j with a string | myStringBuffer.replace(i,j,newString); |
Interface related to array of objects with the minimum functionality to handle the array: add an element, clear, check if empty, get size | Interface is Collection |
Add an element in an array of objects | booleanResult=myArray.add(myObject); |
Add array2 at the end of array1 | booleanResult=arrays1.addAll(array2); |
Delete all elements in an array of objects | myArray.add(myObject); |
Condition: is the array empty | myArray.isEmpty() |
Condition: does the array contains an object | myArray.contains(myObject) |
Create an array of objects with the ability to keep the objects in sequence and so for instance get the position of an element | Interface is List ArrayList The size of ArrayList augments automatically, but you can use myArray.ensureCapacity(n) to augment the capacity myArray.trimToSize() to reduce it to the minimum necessary to keep the existing elements in the array |
Get the nth element of an array | myObject=myArray.get(n); |
Get the position of the first occurence of an object in an array of object. What is the value if the object is not found | position=myArray.indexOf(object); if nothing is found, position is -1 |
Get the position of the first occurence of an object in an array of object. What is the value if the object is not found | position=myArray.lastIndexOf(object); if nothing is found, position is -1 |
Create an array of objects with the ability to keep the objects in sequence and not accepting duplicates | Interface is Set Can use HashSet for very big arrays - uses a hash table HashSet Can use LinkedHashSet to return sequences of objects. LinkedHashSet |
Create an array of objects with the ability to keep the objects in sequence, not accepting duplicates and sorting elements inside ( as a result, you can return elements greater than a value) | Interface is SortedSet Can use TreeSet that gives instant access to lists of ordered data TreeSet |
Get the first element of a sorted array | myObject=myArray.first(); |
Get an array of object lesser than an object | myNewArray=myArray.headSet(myObject); |
Get the last element of a stort array | myObject=myArray.last(); |
Get an array of object equal or greater than an object | myNewArray=myArray.tailSet(myObject); |
Get an array of object between object1 and object2 | myNewArray=myArray.subSet(firstObject,lastObject); lastObject is not included |
Create an array of object with the possibility to check with objects are the closest match to a given object | NavigableSet myArray= |
Get the smallest object greater or equal to object1 | myObject=myArray.ceiling(object1); remember that the lowest element is first, so at the top |
Get the greatest object smaller or equal to object1 | myObject=myArray.floor(object1); |
Create an array of object with the possibility to use fifo functionality | Interface is queue: Can use LinkedList: LinkedList |
Create an array of object with the possibility to use bidirectional fifo functionality ( fifo + lifo ) | Interface is Deque Can use class ArrayDeque |
Get the first element in a fifo queue, giving an exception if there is no element left | myObject=myArray.element(); |
Get the first element in a fifo queue, returning null if there is no element left | myObject=myArray.peek(); |
Get the first element in a fifo queue and delete it, returning null if there is no element left | myObject=myArray.remove(); |
Get the first element in a fifo queue and delete it, returning null if there is no element left | myObject=myArray.pool(); |
Iterate through a collection with an iterator, each time changing the value. What to be careful with | Iterator while(myIterator.hasNext()){ ObjectType currentObject=myIterator.next(); myIterator.set(newvalue); } Careful: at the end the iterator will be pointing to the end of the table |
Iterate through a collection with an iterator backwards. What to be careful with | ListIterator while(myIterator.hasPrevious()){ ObjectType currentObject=myIterator.previous); myIterator.set(newvalue); } Careful: you must be at the end of the table to be able to execute this |
Iterate through a collection without using an iterator. What to be careful with | for ( ObjectType currentObject : myArray ){ use currentObject; } Careful: with this method you can not modify elements in the array |
Create an object to be able to have a key=> value functionality | Interface is Map Can use class HashMap HashMap |
Get the value corresponding to a key | myMap.get(myKeyObject) returns null if there is no correspondance |
Add a key/pair value | myMap.put(myKeyObjectKey,myValueObject) |
Remove an entry corresponding to a given key | myMap.remove(myObjectKey) |
Create an object to be able to have a key=> value functionality and have elements sorted by the value of the key | Interface is SortedMap |
Get the first key of a hash | myValue=myMap.firstKey(); |
Get the last key of a hash | myValue=myMap.lastKey(); |
Iterate through a map | Set for(Map.Entry use currentEntry.getKey() and currentEntry.getValue() } |
Create an object to be able to have a key=> value functionality, have elements in a sorted tree structure | Interface is AbstractMap Can use class TreeMap TreeMap |
Create an object to be able to have a key=> value functionality, have elements in a sorted tree structure and remember in which order the elements were added | HashMap Can put in parameter the capacity and the order. If order is true, it means that when you iterate the order is the order you entered the entry |