Install Java from oracle, windows machine need extra steps to get the path of java right.
Â
Once its done, run java --version in terminal to see if it works the same
Â
First Java
Create a new file HelloWorld.java
public class HelloWorld{
public static void main (String[] args){
/*
*/
System.out.println("HelloWorld");
}
}
class name MUST be the same as the file name
method name need to start with small casing and subsequent words use camel casing
There needs to have a entry point for the code and it has to be public static void main so this must be remembered
Semicolon is needed for every line of code except the ones with the {} brackets
Â
Once done coding, in terminal navigate to the folder contain your java file. Run javac HelloWorld.java this c
Once compiled a HellowWorld.classwill be created in the same directory. Now just run java HelloWorld to run your code.
Â
What is package?
It is for better naming structure
you can create package by creating directory with small letter and level separated by .
The java program created in the package directory need to include a line package your.package.name then continue with the public class TestClass ... stuff
Â
Some common packages that comes with java JDK
java.lang the basic package automatically imported for every java program. Including stuff like Object, String, String Buffer, System, etc
java.util the utilities packages
java.iosystem input and output
java.netfor network related functions
Â
To import and use a package
//import the Date class under the util
import java.util.Date;
//import the Random class under util
import java.util.Random;
// for the package that we created ourselves
import your.package.name.TestClass;
public class HelloWorld{
public static void main (String[] args){
System.out.println("HelloWorld");
Random random = new Random();
boolean flag = random.nextBoolean();
System.out.println(flag);
}
}
After importing the class, use then in your function by Random random = new Random(); this line has 3 'random' so lets look at it closely.
The first Random at the start of the line says the you are going to declare a variable of the type Random
The second random is the name of the variable that you are declaring it can be anything that you want but we will just use random in this case
The third section with new Random();creates a new object from the class Random that we imported and it is assigned to the random variable that we declared
Â
random.nextBoolean() just gives us a random boolean value and it is assigned to the flag variable that is of the type boolean
Â
Java access modifier
It is to determine how the code can be accessed.
Private < Default < Protected < Public
Public allow the code to be access by all external parties
Protected allow access for the code in the same package and all child class
Default allow access for code in the same package
Private allow access for code in the same class only
For protected
Example:
package Chap4_2.Father;
public class Father {
protected static void protected_method(){
System.out.println("under protected");
private_method();
}
private static void private_method(){
System.out.println("This is printed under private");
}
}
This class defines two method one protected one private, both cannot be accessed normally like a public method.
package Chap4_2.MainTest;
import Chap4_2.Father.Father;
public class MainTest extends Father{
public static void main(String[] arg){
Father father = new Father();
father.protected_method();
System.out.println("This is from the main function");
}
}
In order to access the protected and private method, the class MainTest in this case need to extend the Father class to make it a child class to inherit the protected method and variables. However, private method cannot be accessed by the child class, so we can only call it from the protected method that is in the same class.
Â
Java basic data types
Primitive datatypes
byte
8 bit
max 127 min -128 which is 2^8
saves the most space, it is 1/4 of the int type
default 0
short
16 bit
max 32767 min -32768 which is 2^16
size of 1/2 of int type
default 0
int
32 bit
max 2147483647 min -2147483648 which is 2^32
whole number default to int type
default 0
long
64 bit
max 9223372036854774807 min -9223372036854774808 which is 2^64
default 0L
float
32 bit
Stores fractional numbers.
Sufficient for storing 6 to 7 decimal digits
default 0.0f
double
64 bit
Stores fractional numbers.
Sufficient for storing 15 decimal digits
default 0.0
boolean
1 bit
Stores true or false
default 0
char
16 bit unicode character
2 bit for 1 character
Â
Change of data types double >float >long>int>short>byte
Direct conversion from bigger datatype to smaller ones.
Force conversion from smaller datatype to bigger datatypes, may lead to lose of precision of the data.
Â
Non-primitive data
Basically it refers to objects that are created by programmers
String is also a primitive data
default to null
Â
Java Array
It is a kind of datatype that stores a collection of data of the same datatype
Â
//Declare array without initalising values
int [] numbers;
//use new to create array
int [] numbers2 = new int[100];
//initialise an array
int[] numbers = { 1,2,3,4,5,6 };
int [] numbers2 = new int[100]gives a new array of size 100, the values in the array are default to zero, since the default value of int is zero.
Â
int [] numbers = {1,2,3,4,5,6} declares an array of 1-6, the size of the array is the number of data that you have initialised
Once the size of array is determined, the size can not be changed.
Â
multi-dimension array
//create and initialise
int [][] numbers = {[1,2,3],[4,5,6],[7,8,9]}
//create
int [][] numbers2 = new int[3][3];
Â
Stack and Heap
Java has two storage space in the ram one is stack one is heap
Â
Primitive data are all store in the Stack
direct transfer of data from the stack to the program
changes in the data will not affect the original value
Non-primitive data have two storage area (one in stack one in heap)
an object will request a space in heap in the ram to store it
another area in the stack will be requested to store the address of the object in the heap space
Â
int [] a = {1,2,3};
int [] b = a;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
b[0] = 0;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
change the value of b[0] will change the value of the of the data stored in the heap space which lead to the a change in output also, since it points to the same address in the heap space
Â
Variable types
Â
class variable (static variable)
declared using a static modifier
can exist without any object
can be access by ClassName.staticVariableName
No matter now many objects has created from the class there is only one set of class varaible
it is shared with all the objects created
it is stored in method area different from heap and stack
public class Student{
public static final String Prefix = "My name";
}
Object variable (properties)
Need to use Object.VariableName to access (for public variable)
After instantiation the variable value is confirmed
It is destroyed when the object is destroyed
The object variable usually declared with private modifiers
access to these variables through methods
public class Student{
private age;
private name;
public void setAge(int age){
this.age = age;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return this.age;
)
public String getName(){
return this.name;
}
}
Â
Local variable
the variable in method
they are destroyed when the method finish executing
modifiers cannot be used in the local variables
public class Student(){
public void introduce(){
String content = "My name is bla bla bla";
System.out.println(content);
}
}
Â
Java method parameter and return type
//if got something to return for the method
modifier returnType methodName (dataType1 dataName1,dataType2 dataName2...){
//Code Block
return
}
//if got nothing to return for the method
modifier void methodName (dataType1 dataName1,dataType2 dataName2...){
//Code Block
}
Â
While loop
Â
while loop
//keep carry out the loop content until the booleanExpression is false
while (booleanExpression){
//loop content
}
do..while
//carry out the loop content once before looking at the boolean expression
do{
//loop content
}while(booleanExpression);
Â
For loop
normal for loop
for(initalisation;booleanExpression;update){
//for loop content
}
//example
for (i=0;i<20;i++){
Sysyem.out.println(i);
}
First item in the for loop is to initialise a variable, can be empty.
Second item is the boolean expression if its true then it will execute the loop if not it will exit the loop
Third item controls the change of variable, it is carried out every time after the loop is finished.
After the update of the variable the boolean expression is checked again.
the variable type must be the same as the variable in the array
Â
Switch
switch case
switch(expression){
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default : //optional
//statements
}
Example
public class Test {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Data Structures
data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.(from wiki)
Â
Common data structures
Stack
First in last out
insert from top and delete from the top also
Queue
First in First out
Data is inserted from the rear of the queue and removed from the front of the queue
Works like a real life queue, the earlier you come, the earlier you get served
Array
It stores data of the same data type in the same collection
Linked List
Elements are connected using a chain like structure
Each data point has two part, one stores the data, the other stores the pointer to the next data
Hash table
The key value is first pass through a hash function to create a hash value
Hash value is the position to store the key
Increase the speed of searching since the position is computed directly.
Collection containers
Collection containers mainly used to store objects. The three main types of containers are ListSet and Map
Â
List (Ordered, Repetitive)
Set (Unordered, Unrepetitive)
Map (Key and value pair)
Â
List Interface
The list interface is a ordered collection(data are stored orderly in the same ram space). It uses indexing to access the specific data
Â
ArrayList
It is a dynamic array, the capacity can grow on demand
can only store objects but not primitive datatypes like int
get and set operation are faster than LinkList
Â
LinkList
The nodes have data and pointer segment where the pointer store the address of the next node
The storage space in ram does not have to be continuous
insertion and deletion of data is fast
searching for data is slow since it involve the navigation of the pointer
import java.util.LinkedList;
public class ListTest {
public static void main(String []args){
LinkedList<String> linkedList = new LinkedList<>();
//Operation similar to ArrayList, with few additional function
linkedList.getFirst(); //first element in the linked list
linkedList.getLast();//last element in the linked list
}
}
Map
The fundamental structure is Array Each element in the array stores a linked list and the link list with node of an entry and an entry has a key and value pair and a node that points to the next entry.
Hash Map
When put()is called to put data into the map, hashCode()will be called to calculate the hashCode to find the position in the Array to store the entry
Tree Map
When storing the data, the data are automatically sorted. It is an implementation of the Sorted Map Interface
By default, data are sorted in ascending order using the key of the dictionary. Customised sorting rules is possible by implementing the Comparator interface.
Â
Map Code Demo
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapTest {
public static void main(String [] args){
HashMap <String, Integer> hashMap = new HashMap<>();
hashMap.put("Bob",20);
hashMap.put("Sandy",21);
hashMap.put("Bob",22); // overwrite the previous Bob with new value 22
hashMap.put("Maria",20);
hashMap.put("Fahar",20);
System.out.println(hashMap.get("Sandy"));
//21
System.out.println(hashMap.containsKey("Fahar"));
//true
System.out.println(hashMap.containsValue(20));
//true
System.out.println(hashMap.values());
//[22, 20, 21, 20]
System.out.println(hashMap.size());
//4
System.out.println(hashMap.keySet());
//[Bob, Fahar, Sandy, Maria]
Set<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();
System.out.println(entrySet);
//[Bob=22, Fahar=20, Sandy=21, Maria=20]
hashMap.clear();
System.out.println(hashMap.isEmpty());
//true
}
}
Â
Hash Map vs Tree Map
Hash map is quick in indexing and storing but it is unsorted
Tree map is sorted but slower in indexing and storing
jdk1.7 vs jdk 1.8
In jdk 1.7 Hash Map uses a combination of Array and Linked list
in jdk 1.8 Hash Map uses a combination of Array, Linked list and red-black tree
When the linked list is greater than 8(by default), it will be changed to a red-black tree