Difference between revisions of "Java"

From RHS Wiki
Jump to navigation Jump to search
Tag: visualeditor
Line 1: Line 1:
 
All the code can be found at: [https://github.com/rafahsolis/javaTutorial javaTutorial]
 
All the code can be found at: [https://github.com/rafahsolis/javaTutorial javaTutorial]
== Install ==
+
==Install==
=== With apt ===
+
===With apt===
 
  <nowiki>sudo apt-add-repository ppa:webupd8team/java
 
  <nowiki>sudo apt-add-repository ppa:webupd8team/java
sudo apt-get update
+
sudo apt-get update
sudo apt-get install oracle-java8-installer</nowiki>
+
sudo apt-get install oracle-java8-installer</nowiki>
  
 
Also ensure your JAVA_HOME variable has been set to:
 
Also ensure your JAVA_HOME variable has been set to:
 
  /usr/lib/jvm/java-8-oracle
 
  /usr/lib/jvm/java-8-oracle
  
=== From Source ===
+
===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
 
  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/java java /usr/lib/jvm/oracle_jdk8/jre/bin/java 2000
Line 16: Line 16:
 
  update-alternatives --display javac
 
  update-alternatives --display javac
  
== hello world ==
+
==hello world==
 
<source lang="java">
 
<source lang="java">
 
public class aplication {
 
public class aplication {
Line 27: Line 27:
  
 
}</source>
 
}</source>
== Numeric variables ==
+
==Numeric variables==
 
<source lang="java">
 
<source lang="java">
 
public class variables {
 
public class variables {
Line 45: Line 45:
  
 
}</source>
 
}</source>
== Strings ==
+
 
 +
== 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==
 
<source lang="java">
 
<source lang="java">
 
public class stringstuto {
 
public class stringstuto {
Line 58: Line 80:
 
}
 
}
 
}</source>
 
}</source>
== Enum type ==
+
==Enum type==
 
See code example:<br />
 
See code example:<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/EnumTypes.java EnumTypes.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/EnumTypes.java EnumTypes.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Animal.java Animal.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Animal.java Animal.java]<br />
  
== Operators ==
+
==Operators==
=== Asignment ===
+
===Asignment===
 
= Asignment
 
= Asignment
=== Arithmetic ===
+
===Arithmetic===
 
+ Additive<br />
 
+ Additive<br />
 
- Substraction<br />
 
- Substraction<br />
Line 73: Line 95:
 
% Remainder<br />
 
% Remainder<br />
  
=== Increment / Decrement ===
+
===Increment / Decrement===
 
++ Increment<br />
 
++ Increment<br />
 
-- Decrement<br />
 
-- Decrement<br />
=== Logic ===
+
===Logic===
 
== Equal to (*)<br />
 
== Equal to (*)<br />
 
!= Not Equal to<br />
 
!= Not Equal to<br />
Line 88: Line 110:
 
<br />
 
<br />
 
(*) Check .equals()<br />
 
(*) Check .equals()<br />
=== Bitwise and Bit Shift Operators ===
+
===Bitwise and Bit Shift Operators===
 
~ Unary bitwise complement<br />
 
~ Unary bitwise complement<br />
 
<< Signed left shift<br />
 
<< Signed left shift<br />
Line 96: Line 118:
 
^ Bitwise exclusive OR<br />
 
^ Bitwise exclusive OR<br />
 
| Bitwise inclusive OR<br />
 
| Bitwise inclusive OR<br />
=== Type comparison operator ===
+
===Type comparison operator===
 
instanceof
 
instanceof
  
== Loops ==
+
==Loops==
=== While ===
+
===While===
 
<source lang="java">
 
<source lang="java">
 
int myInt = 0;  
 
int myInt = 0;  
Line 109: Line 131:
 
}</source>
 
}</source>
  
=== For ===
+
===For===
 
<source lang="java">
 
<source lang="java">
 
for(int i=0; i<5;i++){
 
for(int i=0; i<5;i++){
 
System.out.printf("The value of i is %d\n", i);
 
System.out.printf("The value of i is %d\n", i);
 
}</source>
 
}</source>
=== Do While ===
+
===Do While===
 
<source lang="java">
 
<source lang="java">
 
public static void main(String[] args) {
 
public static void main(String[] args) {
Line 128: Line 150:
 
}</source>
 
}</source>
  
== Conditional ==
+
==Conditional==
=== if ===
+
===if===
 
<source lang="java">
 
<source lang="java">
 
int value = 20;
 
int value = 20;
Line 143: Line 165:
 
}</source>
 
}</source>
  
=== switch case ===
+
===switch case===
 
<source lang="java">
 
<source lang="java">
 
switch(VariableIntOrString){
 
switch(VariableIntOrString){
Line 158: Line 180:
 
}</source>
 
}</source>
  
== User Input ==
+
==User Input==
 
<source lang="java">
 
<source lang="java">
 
import java.util.Scanner;
 
import java.util.Scanner;
Line 181: Line 203:
  
 
*Note: Ctrl + Shift + O in eclipse adds all the imports you need.
 
*Note: Ctrl + Shift + O in eclipse adds all the imports you need.
== Arrays ==
+
 
 +
==Arrays==
 
<source lang="java">
 
<source lang="java">
 
int[] values;
 
int[] values;
Line 190: Line 213:
  
 
values.length; → returns the array lenght<br />
 
values.length; → returns the array lenght<br />
=== Iterating trough an array ===
+
===Iterating trough an array===
 
<source lang="java">
 
<source lang="java">
 
String[] fruits = {"apple", "banana", "pear", "kiwi"};
 
String[] fruits = {"apple", "banana", "pear", "kiwi"};
Line 197: Line 220:
 
}
 
}
 
</source>
 
</source>
=== Multidimensional arrays ===
+
===Multidimensional arrays===
 
<source lang="java">
 
<source lang="java">
 
int[][] grid = {
 
int[][] grid = {
Line 208: Line 231:
 
</source>
 
</source>
  
== Classes and Objects ==
+
==Classes and Objects==
 
<source lang="java">
 
<source lang="java">
 
class Person {
 
class Person {
Line 235: Line 258:
 
}
 
}
 
</source>
 
</source>
== Setters and 'this' ==
+
==Setters and 'this'==
 
<source lang="java">
 
<source lang="java">
 
package tutorial1;
 
package tutorial1;
Line 275: Line 298:
 
}
 
}
 
</source>
 
</source>
== Constructors ==
+
==Constructors==
 
Methods that are executed at the instantiation of a class.<br />
 
Methods that are executed at the instantiation of a class.<br />
 
There can be more than one, diferentiated on the number of parameters that are passed at the instantiation of a class.<br />
 
There can be more than one, diferentiated on the number of parameters that are passed at the instantiation of a class.<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/constructors.java example code]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/constructors.java example code]
  
== static ==
+
==static==
 
static is used to define class variables and methods.<br />
 
static is used to define class variables and methods.<br />
 
static objects are referenced by the class, not the instance.<br />
 
static objects are referenced by the class, not the instance.<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/staticMethod.java example code]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/staticMethod.java example code]
  
== final ==
+
==final==
 
final is used to declare constants. The asignment of value must be at the declaration<br />
 
final is used to declare constants. The asignment of value must be at the declaration<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/constructors.java example code]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/constructors.java example code]
  
== StringBuilder / formatting ==
+
==StringBuilder / formatting==
 
StringBuilder is more efficient for strings appending than using +=
 
StringBuilder is more efficient for strings appending than using +=
 
[https://github.com/rafahsolis/javaTutorial/blob/master/StringBuilderBufferFormatting.java example code]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/StringBuilderBufferFormatting.java example code]
  
== Inheritance ==
+
==Inheritance==
 
Use key word extends at the class declaration<br />
 
Use key word extends at the class declaration<br />
 
private variables and methods are not inherited.<br />
 
private variables and methods are not inherited.<br />
Line 305: Line 328:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Car.java Car.java]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Car.java Car.java]
  
== Packages ==
+
==Packages==
 
Packages allow to have classes with the same name as long as they are in diferent packages. <br />
 
Packages allow to have classes with the same name as long as they are in diferent packages. <br />
 
In orther to be able to use the classes from a package it must be imported.<br />
 
In orther to be able to use the classes from a package it must be imported.<br />
Line 318: Line 341:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/packageexample.java packageexample.java]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/packageexample.java packageexample.java]
  
== Interfaces ==
+
==Interfaces==
 
If you whant to define a method for more than one class, you should use an interface (rigt click on project > new > interface)<br />
 
If you whant to define a method for more than one class, you should use an interface (rigt click on project > new > interface)<br />
 
Interfaces file names should start with upper case.<br />
 
Interfaces file names should start with upper case.<br />
Line 327: Line 350:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Info.java Info.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Info.java Info.java]<br />
  
== public/private/protected variables ==
+
==public/private/protected variables==
 
public → can be accesed from anywhere.<br />
 
public → can be accesed from anywhere.<br />
 
public final static → constant.<br />
 
public final static → constant.<br />
Line 334: Line 357:
 
no access specifier → only accesible from the same package.<br />
 
no access specifier → only accesible from the same package.<br />
  
== Polymorphism ==
+
==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.<br />
 
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.<br />
 
You wont be able to call methods from the subclass that are not implemented on the variable type.<br />
 
You wont be able to call methods from the subclass that are not implemented on the variable type.<br />
Line 342: Line 365:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Tree.java Tree.java]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Tree.java Tree.java]
  
== Encapsulation and the API ==
+
==Encapsulation and the API==
 
Variables whithin a class should be private and if you need to change them use getters and setters.<br />
 
Variables whithin a class should be private and if you need to change them use getters and setters.<br />
 
[https://docs.oracle.com/javase/8/docs/api/ Java 8 API]
 
[https://docs.oracle.com/javase/8/docs/api/ Java 8 API]
  
== Casting Numerical Values ==
+
==Casting Numerical Values==
 
See [https://github.com/rafahsolis/javaTutorial/blob/master/Casting.java examples]
 
See [https://github.com/rafahsolis/javaTutorial/blob/master/Casting.java examples]
  
== Upcasting and Downcasting ==
+
==Upcasting and Downcasting==
 
Code examples:<br />
 
Code examples:<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/UpcastingDowncasting.java UpcastingDowncasting.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/UpcastingDowncasting.java UpcastingDowncasting.java]<br />
Line 355: Line 378:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Machine.java Machine.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Machine.java Machine.java]<br />
  
== Generic class ==
+
==Generic class==
 
Can work with other objects specified at the class instantiation.<br />
 
Can work with other objects specified at the class instantiation.<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Generic.java Generic.java]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Generic.java Generic.java]
Line 393: Line 416:
 
}
 
}
 
</source>
 
</source>
=== Generics and Wildcards ===
+
===Generics and Wildcards===
 
See: [https://github.com/rafahsolis/javaTutorial/blob/master/Generic.java Generic.java]
 
See: [https://github.com/rafahsolis/javaTutorial/blob/master/Generic.java Generic.java]
== Files ==
+
==Files==
=== Reading text files ===
+
===Reading text files===
 
See: [https://github.com/rafahsolis/javaTutorial/blob/master/ReadTextFile.java ReadTextFile.java]
 
See: [https://github.com/rafahsolis/javaTutorial/blob/master/ReadTextFile.java ReadTextFile.java]
=== Reading files (Try-With-Resources) ===
+
===Reading files (Try-With-Resources)===
 
This requires at least Java 7<br />
 
This requires at least Java 7<br />
 
<source lang="java">
 
<source lang="java">
Line 427: Line 450:
 
}
 
}
 
}</source>
 
}</source>
=== Reading files with FileReader ===
+
===Reading files with FileReader===
 
<source lang="java">
 
<source lang="java">
 
import java.io.BufferedReader;
 
import java.io.BufferedReader;
Line 467: Line 490:
 
}</source>
 
}</source>
  
=== Writing files ===
+
===Writing files===
 
<source lang="java">
 
<source lang="java">
 
import java.io.BufferedWriter;
 
import java.io.BufferedWriter;
Line 496: Line 519:
 
}</source>
 
}</source>
  
== Anonymous class ==
+
==Anonymous class==
 
see: [https://github.com/rafahsolis/javaTutorial/blob/master/AnonymousClass.java AnonymousClass.java]
 
see: [https://github.com/rafahsolis/javaTutorial/blob/master/AnonymousClass.java AnonymousClass.java]
== Exceptions ==
+
==Exceptions==
 
[http://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html Class Exception]
 
[http://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html Class Exception]
=== trows ===
+
===trows===
 
<source lang="java">
 
<source lang="java">
 
package tutorialJava;
 
package tutorialJava;
Line 519: Line 542:
 
}</source>
 
}</source>
  
=== try/catch ===
+
===try/catch===
 
<source lang="java">
 
<source lang="java">
 
import java.io.IOException;
 
import java.io.IOException;
Line 559: Line 582:
 
}
 
}
 
}</source>
 
}</source>
=== Runtime exceptions ===
+
===Runtime exceptions===
 
The compiler does not force you to handle them.
 
The compiler does not force you to handle them.
 
<source lang="java">
 
<source lang="java">
Line 586: Line 609:
  
 
}</source>
 
}</source>
== Abstract Class ==
+
==Abstract Class==
 
Classes that can't be instantiated, only inherited.<br />
 
Classes that can't be instantiated, only inherited.<br />
 
See example files:<br />
 
See example files:<br />
Line 593: Line 616:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/AbstractClassChild1.java AbstractClassChild1.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/AbstractClassChild1.java AbstractClassChild1.java]<br />
  
== .equals() Method ==
+
==.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:<br />
 
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:<br />
 
Right click on the class > source > Generate hashCode() and Equals()...<br />
 
Right click on the class > source > Generate hashCode() and Equals()...<br />
Line 601: Line 624:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Persona.java Persona.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Persona.java Persona.java]<br />
  
== Inner Classes ==
+
==Inner Classes==
 
Clases declared inside other classes.<br />
 
Clases declared inside other classes.<br />
 
Code examples:<br />
 
Code examples:<br />
Line 607: Line 630:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Robot.java Robot.java]
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Robot.java Robot.java]
  
== Recursion ==
+
==Recursion==
 
See code example:<br />
 
See code example:<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Recursion.java Recursion.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Recursion.java Recursion.java]<br />
  
== Serialization ==
+
==Serialization==
 
Turning an object into binary data, deserialization is the opposite.<br />
 
Turning an object into binary data, deserialization is the opposite.<br />
 
Code examples:<br />
 
Code examples:<br />
Line 618: Line 641:
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Persona.java Persona.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/Persona.java Persona.java]<br />
  
=== Multiple Objects ===
+
===Multiple Objects===
 
[https://github.com/rafahsolis/javaTutorial/blob/master/WriteMultipleObjects.java WriteMultipleObjects.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/WriteMultipleObjects.java WriteMultipleObjects.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/ReadMultipleObjects.java ReadMultipleObjects.java]<br />
 
[https://github.com/rafahsolis/javaTutorial/blob/master/ReadMultipleObjects.java ReadMultipleObjects.java]<br />
=== Transient Keyword ===
+
===Transient Keyword===
 
To prevent the serialization of some variable in a class you can declare it as:<br />
 
To prevent the serialization of some variable in a class you can declare it as:<br />
 
<source lang="java">
 
<source lang="java">
Line 627: Line 650:
 
Static fields aren't serialized too.
 
Static fields aren't serialized too.
  
== Eclipse shortcuts ==
+
==Eclipse shortcuts==
 
Ctrl + Space → Autocomplete.<br />
 
Ctrl + Space → Autocomplete.<br />
 
Ctrl + d → Delete Line<br />
 
Ctrl + d → Delete Line<br />
Line 634: Line 657:
 
Ctrl + m → Toogle fulscreen<br />
 
Ctrl + m → Toogle fulscreen<br />
  
== Notes ==
+
==Notes==
 
Hibernate → Java ORM framework for web design
 
Hibernate → Java ORM framework for web design

Revision as of 10:53, 12 April 2022

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

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

(*) 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);
}

Multidimensional arrays

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

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;
    }
}

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());
    }
}

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

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 class Car extends Machine {
}

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.
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