ZOFTINO.COM android and web dev tutorials

Introduction to Java Programming

Java is a powerful object oriented programming language. Java programs are translated into bytecode by java compilers. The compiled java bytecode runs on the virtual computer called Java Virtual Machine (JVM). Interpreter in the JVM translates java bytecode into machine understandable instructions. So to run a complied java program on a machine, all you need is the JVM with interpreter that can translate java bytecode into the machine understandable instructions.

This way of running java programming using bytecode compiler and machine specific interpreter is what makes java programs portable, meaning write once and run anywhere.

Java is an object oriented programming language, allows defining objects which are self sufficient entities meaning objects contain data and behavior which operates on the data.

Table of Contents

Data Types

A program consists of two elements, data and behavior which use data. To store data in a program, variables need to be declared. To declare a variable, type of data needs to be specified. Java supports byte, short, int, long, float, double, boolean and char data types. These data types are called primitive data types.

Data type byte is an 8 bits signed integer and you can assign values from -128 to 127 range to a variable of byte type. Data type short is a 16 bit signed integer and value range is -32,768 and 32,767. Data type int is a 32 bit integer, int data type can be used as signed and unsigned. For unsigned int, value range starts from 0. Data type long is a 64 bit integer and it can be signed and unsigned.

Data type float is a single precision 32 bit floating point. Data type double is a double precision 64 bit floating point.

Data type boolean can have two values true or false. Data type char is 64 bit Unicode character. Java also provides String class which can be used for storing character string data.

You can declare a variable in java using data type and variable name.

private int height;

If values are not assigned to variables, compiler assigns default values. The default values are 0 for byte, short and int, 0L for long, 0.0f for float, 0.0d for double, false for boolean and null for String and any other object types.

Running Java Program

To create and run java programs, first install Java SDK by downloading it from Oracle Java. Then set JAVA_HOME environment variable to jdk directory.

Then install eclipse IDE by downloading it from eclipse.org.

Open the eclipse, create new java project by clicking file / new / java project and following the flow. Then expand the project in eclipse, right click src, click new package, add name and create package. Then right click the package, click new class, add name and create class.

The entry point for any java program is main method. Define main method in the class you created and write some code. Then click Run menu and click Run menu item to run the program you created.

 public class MainClass {
	public static void main(String[] args) {		

		int a = 3;
		int b = 6;
		 
		int c = a+b;
		System.out.println("a+b is "+c);
	}
} 

Arrays

If you have multiple items of the same time type of data, it will be difficult to manage if you declare variable for each data item. Java provides a way to handle multiple variables of same type. You can declare an object called Array which can hold multiple items of same type of data.

You can declare primitive data types or any object type as an array as shown below. You need to specify the number of elements that array can hold. To assign or read value of an element, you can use index. Array index starts from 0. The example shows array declaration, assigning values to it and accessing values stored in array.

 		int[] scores = new int[3];
		
		scores[0] = 80;
		scores[1] = 80;
		scores[2] = 80; 
System.out.println("array element at index 1 is "+scores[1]);</

Operators

Java operators can be classified into assignment, arithmetic, unary, rational, equality, conditional and bitswise operator categories.

Arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division), and % (remainder).

Unary operators such as +, -, ++ (increment), -- (decrement), and ! (boolean inverter) operate on only one operand.

Equality and relational operators are == (equals to), <= (less than or equals to), >= (greater than or equals to), < (less than), > (greater than).

Conditional operators are && (conditional and) and || (conditional or). To compare an object to a type, instanceof operator is provided in java.

Bitswise operators such as ~, >>, >>, &, | and ^ are very rarely used.

 
public class MainClass {
	public static void main(String[] args) {		

		int x = 5;
		int y = 8;
		
		int z = x+y;		
		System.out.println("x+y is "+ z);
		 z = y-x;		
		System.out.println("y-x is "+z);
		 z = x*y;		
		System.out.println("x*y is "+z);		
		 z = y/x;		
		System.out.println("y/x is "+z);
		
		 z = y%x;		
		System.out.println("y%x is "+z);
		
		x = +4;
		System.out.println("after unary operation "+x);
		x = -2;
		System.out.println("after unary operation "+x);
		x++;
		System.out.println("after unary operation "+x);
		x--;
		System.out.println("after unary operation "+x);
		
		boolean isIt = false;
		System.out.println("boolean invert operator "+ !(isIt));
		
		
		int a = 3;
		int b = 3;
		if(a == b) {
			System.out.println("numbers equal");
		}
		
		b=5;
		if(a < b) {
			System.out.println("a is less than b");
		}
		
		if(b >  a) {
			System.out.println("b is greater than a");
		}
		
		x=5; y=5; a=6; b=6;
		
		if(x==y && a==b) {
			System.out.println("x equals to y and a equals to b");
		}
		if(a < x || b > y) {
			System.out.println("a is less than x or b is greater than y");
		}
	}
}
 

Output

x+y is 13
y-x is 3
x*y is 40
y/x is 1
y%x is 3
after unary operation 4
after unary operation -2
after unary operation -1
after unary operation -2
boolean invert operator true
numbers equal
a is less than b
b is greater than a
x equals to y and a equals to b
a is less than x or b is greater than y 

Control Flow Statements

If you want to run a piece of code when a variable has certain value, then you can use if and if-else statements.

 		if(a > b) {
			c = a-b;
		}else {
			c = a+b;
		} 

If you have multiple blocks of code and you want to execute a block of code based on the value of a variable then switch statement can be used. Variable of a data type such as byte, short, char, int, enum types, String, Character, Byte, Short, and Integer can be used as switch variable.

 		int category = 3;

		switch (category) {

			case 2: {
				System.out.println("selected category is fashion");
				break;
			}
			case 3: {
				System.out.println("selected category is mobiles");
				break;
			}
			case 4: {
				System.out.println("selected category is appliances");
				break;
			}
			default : {
				System.out.println("selected category is electronics");
				break;
			}
		}
 

Output:

selected category is mobiles

You need to add break statement to all case blocks. If break is not added, all the case blocks, which come after the matching case block, will be executed.

If you want to run a block of code repeatedly as long as a variable has certain value, then you can use while or do-while statements.

Both while and do-while statement evaluate an expression, if the expression returns true then the block of code in the while or do-while will be executed. The difference between while and do-while is that the statements get executed at least once using do-while as expression evaluation is done at the bottom.

 		int offerType = 3;
		int maxOffer = 5;
		int counter = 1;
		while(offerType == 3) {
			System.out.println("you used cashback offer");
			if(counter < maxOffer) {
				counter++;
			}else {
				offerType = 0;
			}
		}
		
		maxOffer = 5;
		counter = 1;
		do {
			System.out.println("you used coupon offer");
			if(counter < maxOffer) {
				counter++;
			}else {
				offerType = 4;
			}
		}while(offerType == 0); 

Output:

you used cashback offer 1
you used cashback offer 2
you used cashback offer 3
you used cashback offer 4
you used cashback offer 5
you used coupon offer 1
you used coupon offer 2
you used coupon offer 3
you used coupon offer 4
you used coupon offer 5 

If you need to run a task for a certain number of times, you can use for-loop. In the for-loop, you need to initialize a counter variable, add expression to see if counter has not exceeded the range and increment the counter variable. The variable initialization and range check is performed first, then code block is executed, then counter is incremented and range check is performed again to exit the loop if expression evaluates to false otherwise it will execute the block of code again. The loop continues till the expression is evaluated to true.

 		for(int s=1; s<4; s++) {
			System.out.println("in for loop "+s);
		} 

Output:

in for loop 1
in for loop 2
in for loop 3 

With the loop statements, you can use break and continue statements to exit from the loop and to continue the next iteration of the loop respectively.

 		for(int s=1; s<4; s++) {
			if(s == 2) {
				continue;
			}
			System.out.println("in for loop "+s);
		} 
in for loop 1
in for loop 3 
 		for(int s=1; s<4; s++) {
			if(s == 3) {
				break;
			}
			System.out.println("in for loop "+s);
		} 
in for loop 1
in for loop 2 

Object Oriented Programming Concepts

Object

Object oriented programming makes it possible to keep state and its related behavior together in a module called object. Object contains the fields which represent state and the methods which represent behavior and the methods are exposed to outside entities.

The concept of hiding information in object and performing actions on the information using the exposed behavior of the object is called encapsulation.

For example television, it has channel, color, brightness, volume, etc states and increase or decrease volume, color, brightness, change channel, etc behavior.

Class

Class is a kind it defines properties and behavior. Instance of a class with a state meaning with certain values assigned to the properties of the class is called object.

public class Table {

	private String purpose;
	private int height;
	
	public void addUpdatePurpose(String purpose) {
		purpose = purpose;
	}
	
	public void increaseHeight(int extraHieght) {
		height = height-extraHieght;
	}
	public void decreaseHeight(int extraHieght) {
		height = height - extraHieght;
	}
}

Inheritance

Inheritance allows for defining a new class by extending a class and adding additional state and behavior to it. The class which extended the other class is called subclass. The class which is extended by other class is called super class. One class can be extended by many classes, meaning there can be many subclasses of a class.

For example, Table class can be extended to create OfficeTable to add drawer state and behavior.

public class OfficeTable extends Table{
	private int[] drawerStates = new int[5];

	public void setDrawersState(int drawer, int state) {
		drawerStates[drawer] = state;
	}	
}

Interface

Specification of methods of the object can be defined separately in java. The component which just defines methods of an object without any implementation is called interface. When a program needs to interact with an object, it can use interface to interact with it. This way the calling program doesn’t need to know about implementation and this decoupling makes switching to different implementation of the interface easy.

For example table interface.

 public interface TableInterface {
	public void addUpdatePurpose(String purpose);
	
	public void increaseHeight(int extraHieght);
	
	public void decreaseHeight(int extraHieght);
} 

The class that implements an interface should implement all methods defined in the interface.

 public class DinningTable implements TableInterface{

	private String purpose;
	private int height;
	private int capacity;
	
	public void addUpdatePurpose(String purpose) {
		purpose = purpose;
	}
	
	public void increaseHeight(int extraHieght) {
		height = height + extraHieght;
	}
	public void decreaseHeight(int extraHieght) {
		height = height - extraHieght;
	}
} 

Polymorphism

Outside entity interacts with an object using the exposed methods. Objects can provide different implementations for a method, meaning object can expose one interface but provide multiple implementations. The concept of existence of multiple implementations for one interface is called polymorphism.

In java, polymorphism can be achieved by creating over loaded methods, meaning different method implementations with the same method name but different parameters can be provided in an object. At compile time right method will be chosen based on the number and type of arguments and return type. Method over loading is calling compile time polymorphism.

For example, two add() methods in the Calculator class are overloaded methods.

 public class Calculator {
	
	public int add(int a, int b) {
		return a+b;
	}
	public float add(int a, int b, int c) {
		return a+b+c;
	}
} 

Polymorphism can also be achieved by overriding methods. Meaning, subclass can provide new implementation for the same method which is implemented in the super class. Which version of the method will be run is decided at run time depending on the object to which the object variable is referencing.

For example, TaxCalculator and its subclass SuperRichTaxCalculator have implementation for the same methods.

 public class TaxCalculator {
	
	public float calculateTax(int earnings) {
		return earnings*25/100;
	}

} 
 
public class SuperRichTaxCalculator extends TaxCalculator{
	
	public float calculateTax(int earnings) {
		return earnings*65/100;
	}	
} 

The method will be chosen at run time and it depends on the object the variable is pointing to. This type of polymorphism is called run time polymorphism.

 	public static void main(String[] args) {		
		TaxCalculator a = new TaxCalculator();
		TaxCalculator b = new SuperRichTaxCalculator();
		
		System.out.println("tax from a "+a.calculateTax(2000));
		System.out.println("tax from b "+b.calculateTax(2000));
	} 

Output:

tax from a 500.0
tax from b 1300.0 

Package

Like folders in the file system, packages make organizing Java classes and interfaces easy by keeping related classes and interfaces in a package. Packages make it possible to create classes with same name in different packages in an application.

For example, com.zoftino.furniture and com.zoftino.furniture.kitchen are packages.

Advantage of object oriented programming

Because code is kept in a class and separate from other classes, it makes it easy to independently maintain it and do enhancements.

State information is accessible using only methods exposed and hidden from outside.

Because of code modularity, components can be reused.