Java

From RHS Wiki
Jump to navigation Jump to search

All the code can be found at: javaTutorial

Install

With apt

sudo apt-add-repository ppa:webupd8team/java
                  sudo apt-get update
                  sudo apt-get install oracle-java8-installer

Also ensure your JAVA_HOME variable has been set to:

/usr/lib/jvm/java-8-oracle

From Source

wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u5-b13/jdk-8u5-linux-x64.tar.gz
sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/oracle_jdk8/jre/bin/java 2000
sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/oracle_jdk8/bin/javac 2000
update-alternatives --display java
update-alternatives --display javac

hello world

public class aplication {

	public static void main(String[] args) {
		System.out.println("Hello world!");
		

	}

}

Numeric variables

public class variables {

	public static void main(String[] args) {
		int myInt = 88; //Integer 32 bit
                short myShort; //Short 16 bit
                long myLong; //Long 64 bit
                byte myByte; //Byte 8 bit

                double myDouble; //Double 
                float myFloat = 325.25f //Float
                
		char myChar = 'y'; //Char
                boolean myBoolean = true; //Boolean
	}

}

Data types

byte b; byte (8 bits)

short s; short (16 bits)

int i; Integer (32 bits)

long lo; long (64 bits)

float f=4.0f; (32 bits) Not precise use big decimal instead

double d; (64 bits) Not precise use big decimal instead

char c; (16 bits)

String st; String

boolean isTrue; true/false

Todo: Arrays etc...

Strings

public class stringstuto {
	public static void main(String[] args) {
                int myInt = 7;
		String myString1 = "Hello ";
                String myString2 = "Rafa";
                String myString3 = myString1 + myString2;
                
                System.out.println(myString3);
                System.out.println("My integer is: " + myInt);
	}
}

Enum type

See code example:
EnumTypes.java
Animal.java

Operators

Asignment

= Asignment

Arithmetic

+ Additive
- Substraction

* Multiplication

/ Division
% Remainder

Increment / Decrement

++ Increment
-- Decrement

+= 1 Increment by one

-= 1 Decrement by one

/=2 Divide by 2

*= 2 multiplied by 2

Logic

== Equal to (*)
!= Not Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
&& Conditional-AND
|| Conditional-OR

?: Ternary (shorthand for if-then-else statement: CONDITION? VALUE_IF_TRUE : VALUE_IF_FALSE)

int number = 2;
boolean isEven = ( number % 2 == 0 ? true : false)



(*) Check .equals()

Bitwise and Bit Shift Operators

~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

Type comparison operator

instanceof

Loops

While

int myInt = 0; 
	
while(myInt < 10){
	System.out.println("Hello");
	myInt = myInt++;
}

For

for(int i=0; i<5;i++){
	System.out.printf("The value of i is %d\n", i);
}

Do While

public static void main(String[] args) {
	Scanner myScanner = new Scanner(System.in);
	int value = 0;
		
	do{
		System.out.println("Enter a number: ");
		value = myScanner.nextInt();
	}
	while(value != 5);
	System.out.println("5!");
}

Conditional

if

int value = 20;
		
if(value < 10){
	System.out.println("Value < 10");
}
else if(value >= 10 && value < 20){
	System.out.println("value >=10 and value < 20");
}
else {
	System.out.println("value >= 20");
}

switch case

switch(VariableIntOrString){
case "start":
	System.out.println("Machine started!");
	break;
	
case "stop":
	System.out.println("Machine stopped");
	break;

default:
	System.out.println("Command not recognized");
}

User Input

import java.util.Scanner;

public class UserInput {
	public static void main(String[] args) {
		Scanner myInput = new Scanner(System.in);
		
		System.out.println("Enter a line of text: ");
		String line = myInput.nextLine();
		System.out.println("You entered: " + line);

                System.out.println("Enter a number: ");
                int value = myInput.nextInt();
                System.out.println("You entered: " + value);

                System.out.println("Enter a number: ");
                double dvalue = myInput.nextDouble();
                System.out.println("You entered: " + dvalue);
	}
}
  • Note: Ctrl + Shift + O in eclipse adds all the imports you need.

Arrays

int[] values;
values = new int[3];
int[] values2 = {5, 24, 12};
values[0] = 10;

values.length; → returns the array lenght

Iterating trough an array

String[] fruits = {"apple", "banana", "pear", "kiwi"};
for(String fruit: fruits){
        System.out.println(fruit);
}

Fill array

int[] marks = new int[5]
Arrays.fill(marks, 100)

Other

Arrays.equals(array1, array2)  // Compare 2 arrays
Arrays.sort(array1)  // Sort array

Array of arguments

void print(int... values) {
    System.out.print(Arrays.toString(values));
}

Multidimensional arrays

int[][] grid = {
         {3, 5, 12},
         {2, 4},
         {25, 12, 0}
};
System.out.println(grid[1][1];
String[][] = new String[2][3];

Collections

List: Can't add elements.

ArrayList: Access very slow, efficient insert and delete

LinkedList: Iteration very slow faster insertion and deletion

Vector: Thread safe (syncronized)

List

List<String> words = List.of("Apple", "Bat", "Cat");
words.size();
words.isEmpty();
words.get(0);
words.contains("Dog");
words.indexOf("Cat");

ArrayList

List<String> words = List.of("Eagle", "Dog", "Pear");
List<String> wordsArrayList = new ArrayList<String>(words)

ArrayList<String> items = new ArrayList<String>()
items.add("Apple")
items.add("Bat")
items.add(2, "Cat")
items.remove("Pear")
items.remove(0)
items.size()
Colections.max(items)
List<String> newList= List.of("Table", "Pencil", "Hole");
wordsArrayList.addAll(newList)
wordsArrayList.set(6, "Fish")  // Modify element on position 6

Classes and Objects

class Person {
    String name;
    int age;
    
    void speak(String text) {
            System.out.println(text + name + " and i am " + age + " years old."); 
    }
    int yearsToRetire () {
            int yearsLeft = 67 - age;
            return yearsLeft;
    }
    publick String toString(){
        return name + ' (' + age + ')'
    }
}

class Student extends Person {
    String college;
}

public class Classes {
    public static void main(String[] args){
            Person person1 = new Person();
            
            person1.name = "Joe Doe";
            person1.age = 37;

            person1.speak("My name is: ");
            System.out.println("Years to retirement= " + person1.yearsToRetire());
            System.out.println(person1 instanceof Person);  // true
            System.out.println(person1 instanceof Object);  // true
            System.out.println(person1 instanceof Student);  // false
    }
}

Setters and 'this'

package tutorial1;

class Frog {
	private String name;
	private int age;
	
	public void setName(String name){
		this.name = name;
	}
	
	public void setAge(int newAge){
		age = newAge;
	}
	
	public String getName(){
		return name;
	}
	
	public int getAge(){
		return age;
	}
	
}

public class setters {

	public static void main(String[] args) {
		Frog frog1 = new Frog();
		
		frog1.setName("Steven");
		frog1.setAge(1);
		
		System.out.println(frog1.getName()+ " " + frog1.getAge());

	}

}

Constructors

Methods that are executed at the instantiation of a class.
There can be more than one, diferentiated on the number of parameters that are passed at the instantiation of a class.
example code

static

static is used to define class variables and methods.
static objects are referenced by the class, not the instance.
example code

final

final is used to declare constants. The asignment of value must be at the declaration
example code

StringBuilder / formatting

StringBuilder is more efficient for strings appending than using += example code

Inheritance & abstract

Use key word extends at the class declaration
private variables and methods are not inherited.
protected would be the appropiated declaration to be able to inherit variables without being public.

public abstract class Machine {
    abstract public void move();
}

public class Car extends Machine {
    public void move() {
        System.out.println("Moving...")
    }
}

sample code files:
inheritance.java
Machine.java
Car.java

Packages

Packages allow to have classes with the same name as long as they are in diferent packages.
In orther to be able to use the classes from a package it must be imported.
Each package classes will be on a package folder.
The first line of the .java file for the classes of one package must be: package package_name Example:

import tutorial1.ocean.fish

Example files:
tutorial1.ocean package
packageexample.java

Interfaces

If you whant to define a method for more than one class, you should use an interface (rigt click on project > new > interface)

Interfaces file names should start with upper case.

public interface GamingConsole {
    public void up();
    public void down();
    public void left();
    public void right();

    default void start() {
        System.out.println("Start");
    }
}

public class MarioGame implements GamingConsole {
    @Override
    public void up() {
        System.out.println("Jump");
    }

    @Override
    public void down() {
        System.out.println("Goes into a hole");    
    }

    @Override
    public void left() {
        System.out.println("Go back");    
    }

    @Override
    public void right() {
        System.out.println("Go forward");    
    }
}


Example files:
interfaces.java
PersonInterface.java
Machine.java
Info.java

public/private/protected variables

public → can be accesed from anywhere.
public final static → constant.
private → can only be accesed from the class where it was declared.
protected → can only be by the class where it was declarated, subclasses and from it's package.
no access specifier → only accesible from the same package.

Polymorphism

You can point a variable of a parent type to a child type, it will have the methods from it's type but overriden by the subclass.
You wont be able to call methods from the subclass that are not implemented on the variable type.
Example files:
Polymorphism.java
Plant.java
Tree.java

Encapsulation and the API

Variables whithin a class should be private and if you need to change them use getters and setters.
Java 8 API

Casting Numerical Values

See examples

Upcasting and Downcasting

Code examples:
UpcastingDowncasting.java
Camara.java
Machine.java

Generic class

Can work with other objects specified at the class instantiation.
Generic.java

import java.util.ArrayList;
import java.util.HashMap;

public class Generic {
	public static void main(String[] args) {
		
		//////////// Before Java 5 //////////
		ArrayList list1 = new ArrayList();
		list1.add("Banana");
		list1.add("Apple");
		list1.add("Orange");
		
		String fruit = (String)list1.get(1);
		System.out.println(fruit);
		
		///////// After Java 5 /////////////
		ArrayList<String> strings = new ArrayList<String>();
		strings.add("cat");
		strings.add("dog");
		strings.add("fish");
		
		String animal = strings.get(2);
		System.out.println(animal);
		
		///////// There can be more than one type argument //////
		HashMap<Integer, String> map= new HashMap<Integer, String>();
		
		//////// Java 7 //////////////////////
		ArrayList<Integer> someList = new ArrayList<>();
		
		
	}
}

Generics and Wildcards

See: Generic.java

Files

Reading text files

See: ReadTextFile.java

Reading files (Try-With-Resources)

This requires at least Java 7

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FilesTryWithResources {
	public static void main(String[] args) {
		File file = new File("./src/tutorialJava/textFile.txt");

		try (BufferedReader br = new BufferedReader(new FileReader(file))) {
			String line;

			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}

		} catch (FileNotFoundException e) {
			System.out.println("File not found: " + file.toString());

		} catch (IOException e) {
			System.out.println("Unable to read the file: " + file.toString());
		}

	}
}

Reading files with FileReader

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadingFiles {

	public static void main(String[] args) {
		File file = new File("./src/tutorialJava/textFile.txt");
		BufferedReader br = null;

		try {
			FileReader fr = new FileReader(file);
			br = new BufferedReader(fr);

			String line;

			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}

		} catch (FileNotFoundException e) {
			System.out.println("File not found" + file.toString());
		} catch (IOException e) {
			System.out.println("Unable to read the file: " + file.toString());
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				System.out.println("Can't close the file.");
			}

		}

	}
}

Writing files

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class WritingFiles {

	public static void main(String[] args) {
		File file = new File("./src/tutorialJava/textFile2.txt");

		try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
			br.write("This is line 1");
			br.newLine();
			br.write("This is line 2");
			br.newLine();
			br.write("Last line");
			br.newLine();

		} catch (IOException e) {
			System.out.println("Unable to read the file: " + file.toString());
		}

	}

}

Anonymous class

see: AnonymousClass.java

Exceptions

Class Exception

trows

package tutorialJava;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class HandlingExceptions {

	public static void main(String[] args) trows FileNotFoundException {
		
		File file = new File("test.txt");
		
		FileReader fr = new FileReader(file);
	}

}

try/catch

import java.io.IOException;
import java.text.ParseException;

public class MultipleExceptions {
	public static void main(String[] args) {
		Test test = new Test();
		
		//Option 1
		try {
			test.run();
		} catch (IOException e) {
		//	e.printStackTrace();
			System.out.println("File not found.");
		} catch (ParseException e) {
		//	e.printStackTrace();
			System.out.println("Parse error.");
		}
		
		//Option 2
		try {
			test.run();
		} catch (IOException | ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Option 3
		try {
			test.run();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Option 4 
		// add throws to main declaration... 
	}
}

Runtime exceptions

The compiler does not force you to handle them.

package tutorialJava;

public class RuntimeExceptions {

	public static void main(String[] args) {
		int value = 7;
		String[] texts = {"cero", "one", "two"};
		
		//runtime exceptions
		//// division by 0(ArithmeticException)
		try {
			value = value/0;
		} catch (Exception e){
			System.out.println(e.getMessage());
			System.out.println(e.toString());
			e.printStackTrace();
		}
		//// ArrayIndexOutOfBoundsException
		System.out.println(texts[3]);
		// NoPointerException

	}

}

Abstract Class

Classes that can't be instantiated, only inherited.
See example files:
AbstractClasses.java
AbstractClassChild2.java
AbstractClassChild1.java

.equals() Method

It's used to compare if two objects of the same class are equal. In order to be able to use it you must override this method by:
Right click on the class > source > Generate hashCode() and Equals()...
Select the fields you whant to compare.
See code examples:
EqualsMethod.java
Persona.java

Inner Classes

Clases declared inside other classes.
Code examples:
InnerClasses.java
Robot.java

Recursion

See code example:
Recursion.java

Serialization

Turning an object into binary data, deserialization is the opposite.
Code examples:
WriteObjects.java
ReadObjects.java
Persona.java

Multiple Objects

WriteMultipleObjects.java
ReadMultipleObjects.java

Transient Keyword

To prevent the serialization of some variable in a class you can declare it as:

private transient int variableName;

Static fields aren't serialized too.

Eclipse shortcuts

Ctrl + Space → Autocomplete.
Ctrl + d → Delete Line
Ctrl + o → Automatically add imports
Ctrl + Shift + f → Indent
Ctrl + m → Toogle fulscreen

Notes

Hibernate → Java ORM framework for web design