Java

From RHS Wiki
Revision as of 10:36, 3 April 2015 by Rafahsolis (talk | contribs)
Jump to navigation Jump to search

hello world

public class aplication {

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

	}

}

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
	}

}

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

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

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