Tutorial

Java tutorial

November 11th, 2019 - Vincent Luciani

The tables below will help you to rehearse Java's most useful functionalities. Use the quick links below to jump directly to the type of information you are interested in.



Direct links:

Data types, variables and tables


Type going from -128 to 127byte
Type going from -32 768 to 32767short
Type going from -2 billions to 2 billionsint
Type going from -9 million billion to 9 million billionlong
Type going from 4.9e-324 to 1.8e+038double
Type going from 1.4e-045 to 3.4e+038float
Type of double * shortdouble
Type of float * bytefloat
Type of double + floatdouble
Type int / shortint
Declare and initialize table of intsint my_table[]=new int[mytablesize];
Declare a table of doubles and put 1.1 and 1.2 in itdouble nums[]={1.1,1.2}
Declare and initialize a two dimension array of integersint my_table[][]=new int[mysizex][mysizey]
Get the maximum number of elements in a tablemytable.length

Logic


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 lineresultparameter=condition ? valueiftrue : valueiffalse
if else ifif (condition1){...}
else if ( condition2 ){...}else{...}
use of the switch operatorswitch(valuetotest){
case value1:
...
break;
case value2:
case value3:
...
break;
default:
...
}
do whiledo{
...
}while (conditiontocontinue)
Loop through a table of intfor(int currentvalue : mytable){
use currentvalue ...
}
You can use currentvalue but cannot change it (read only)
Loop through a bidimensional array of intfor (int currentable[] : mybimensionaltable){
for ( int currentvalue : currentable ){
use currentvalue
}
}
Equivalent of go tomymark : lineofcode
...
continue mymark;

Classes


What happens with b when MyClass a=new MyClass();MyClass b=a;a=nullb is still pointing to new MyClass()
Assign parameter to class parameterthis.myvariable=myvariable;
Passing parameter in a fonction : when by value, when by referenceObject passed by reference ( can change the value ), for the rest it is by value ( cannot change the value)
static variableLike 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 variablescannot use functions or variables other than static. Cannot use this nor super
final variableCannot change its value once initialized. Usually used for constants
Put as parameter a undefined number of variables of type int. Then use all these parametersmyfunction(int ... myparams ){... for (int currentvalue : myparams){...}}
Class B is child of class Aclass B extends A{....
Intialize class B child of class A, taken int parameter a from A and adding int parameter bB(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 classesabstract class classname{
abstract returntype mandatoryfunction(listofparameters);
..
}
Restriction with abstractcannot declare abstract constructors nor abstract methods
Inside abstract class, what the class has a non-abstract methodThe 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 childParentClass 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 itfinal mytype mymethodname(myparams)
Where can you access what is privateIn the same class
Where can you access what is not marked as private nor public nor protectedIn the same package
Where can you access what is protectedEverywhere except in another package, another class ( can be child class from another package)
use the name of class from another packageotherpackagename.classname

Interfaces


How to write an interfaceinterface InterfaceName{
methodtype methodname(parameters);
...
}
Class A is child of B and implementing interface Cclass A extends B implements C
If A implements interface B, what will cause a compilation error. Exceptionif 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 BC myCObject;
A myAObject=new A(parameters);
B mybObject=new B(parameters);

myCObject=myAObject;
myCObject.myCommonMethod;

myCObject=myBObject;
myCObject.myCommonMethod;
Interface and abstract classIf 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 interfacesYou 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 interfaceThis class must implement methods declared in the parent interface and in the child interface

Error Handling


Try catchtry{
...
}catch ( Exception e ){
use e
}
Declare which kind of exception a method can encountermyMethod(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 codetry{
...
}catch ( Exception e ){
use e
}finally{
codetoexecutealways;
}
Get the exception that occured before the thrown exceptione.getCause()
Get the description of the exceptione.getMessage()
Provoke an exceptionthrow exceptionType;
Define your own exception accepting parameters, and use itclass MyException extends Exception{
...
myException(parameters){
...
}..
}

....
throw myException(parameters);
Keep the cause of the error before throwing it, and then use this cause when catchingExceptionType e=new ExceptionType(""exceptionname"");
e.initCause(new ExceptionType(""indicationofthecause"");
throw e;
...
catch .(ExceptionType e){
.. e.getCause();
}
Catch two types of exceptioncatch( ExceptionType1 | ExceptionType2 e)

Dealing with Strings


Get nth character from a StringmyString.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 arraymyString.getChars(i,j,myArrayOfChars,k)
Check if two Strings are equalstring1.equals(string2)
Check if two Strings are equal, ignoring casesstring1.equalsIgnoreCase(string2)
Check if n characters in string 1, starting from position i, match with n charachters from string2, starting from jstring1.regionMatch(i,string2,j,n)
Check if String1 starts with String2string1.startsWith(string2)
Check if String1 ends with String2string1.endsWith(string2)
Check position of first occurence of String1 is inside String2string2.indexOf(string1)
Check position of last occurence of String1 is inside String2string2.lastIndexOf(string1)
Check position of first occurence of String1 is inside String2 : value if cannot find-1
Get part of a Stringresult=myString.substring(firstPosition,lastPosition);
or
result=myString.substring(firstPosition);to get the string from firstPosition until the end of the string
Concatenate two stringsstring3=string1.concat(string2);
Replace character1 by character2 in a stringstring2=string1.replace(character1,character2);
Take off all leading and trailing spaces from a stringstring2=string1.trim();
Convert a non-string to a stringstring1=String.valueOf(nonstring);
Convert a string to all upper casestring1=string2.toUpperCase();
Convert a string to all lower casestring1=string2.toLowerCase();
Class having more functionalities than stringStringBuffer
Check if a string buffer contains a char sequencemyStringBuffer.contains(charsequence)
Check if a string buffer is emptymyStringBuffer.contains(charsequence)
In a string buffer, replace the first occurence of a pattern by a stringmyStringBuffer.replaceFirst(regularExpression,string2)
In a string buffer, replace the all occurences of a pattern by a stringmyStringBuffer.replaceAll(regularExpression,string2)
Append a string to a string buffermyStringBuffer.append(myString);
Convert a string buffer to a stringmyString=myStringBuffer.toString();
Delete characters in a string buffermyStringBuffer.delete(start,end);
or
myStringBuffer.deleteCharAt(position);
In a string buffer, replace characters from i to j with a stringmyStringBuffer.replace(i,j,newString);

Dealing with Arrays


Interface related to array of objects with the minimum functionality to handle the array: add an element, clear, check if empty, get sizeInterface is Collection
Add an element in an array of objectsbooleanResult=myArray.add(myObject);
Add array2 at the end of array1booleanResult=arrays1.addAll(array2);
Delete all elements in an array of objectsmyArray.add(myObject);
Condition: is the array emptymyArray.isEmpty()
Condition: does the array contains an objectmyArray.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 elementInterface is List
ArrayList myArray=new 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 arraymyObject=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 foundposition=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 foundposition=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 myArray=new HashSet();
Can use LinkedHashSet to return sequences of objects.
LinkedHashSet myArray=new 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 myArray=new TreeSet();
Get the first element of a sorted arraymyObject=myArray.first();
Get an array of object lesser than an objectmyNewArray=myArray.headSet(myObject);
Get the last element of a stort arraymyObject=myArray.last();
Get an array of object equal or greater than an objectmyNewArray=myArray.tailSet(myObject);
Get an array of object between object1 and object2myNewArray=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 objectNavigableSet myArray=
Get the smallest object greater or equal to object1myObject=myArray.ceiling(object1);
remember that the lowest element is first, so at the top
Get the greatest object smaller or equal to object1myObject=myArray.floor(object1);
Create an array of object with the possibility to use fifo functionalityInterface is queue:
Can use LinkedList:
LinkedList myArray=new LinkendList
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 leftmyObject=myArray.element();
Get the first element in a fifo queue, returning null if there is no element leftmyObject=myArray.peek();
Get the first element in a fifo queue and delete it, returning null if there is no element leftmyObject=myArray.remove();
Get the first element in a fifo queue and delete it, returning null if there is no element leftmyObject=myArray.pool();
Iterate through a collection with an iterator, each time changing the value. What to be careful withIterator myIterator=myArray.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 withListIterator myIterator=myArray.ListIerator();
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 withfor ( 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 functionalityInterface is Map
Can use class HashMap
HashMap myMap=new HashMap();
Get the value corresponding to a keymyMap.get(myKeyObject)
returns null if there is no correspondance
Add a key/pair valuemyMap.put(myKeyObjectKey,myValueObject)
Remove an entry corresponding to a given keymyMap.remove(myObjectKey)
Create an object to be able to have a key=> value functionality and have elements sorted by the value of the keyInterface is SortedMap
Get the first key of a hashmyValue=myMap.firstKey();
Get the last key of a hashmyValue=myMap.lastKey();
Iterate through a mapSet> mySet=myMap.entrySet();
for(Map.Entry currentEntry : mySet){
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 myMap=new 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 addedHashMap myMap=new 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
This website is non commercial and does not register any of your personal data (no cookie, no statistics). The site and its content are delivered on an "as-is" and "as-available basis".
image/svg+xml