Introduction to Java

Java is a general-purpose object-oriented programming language initiated by James Gosling, Patrick Naughton, and Mike Sheridan in 1991 and specifically designed to have as few implementation dependencies as possible.

Object Oriented

Java treat everything as an Object. It is based on the Object model so it is easy to extend. OOP methodology simplify the development and maintenance of software. Following are some basic concepts of object oriented programming which will be covered in next chapters.

  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Platform independent

Java is compiled into platform independent byte code unlike other programming languages which are compiled into platform dependent machine code. The byte code in interpreted by Java Virtual Machine (JVM) on whichever platform it is running.

Simple

Java is designed to be simple. The syntax of java is based on C++ and with basic concepts of OPP java is easy to learn.

Secure

Java enables you to develop secure, virus free and temper free applications with following features.

  • No explicit pointers
  • Classloader
  • Bytecode Verifier
  • Programs running in virtual machine

Architectural-neutral

In Java there is no implementation dependent aspects of the specification.

Portable

Java byte code is platform independent and can run on any environment.

Robust

Java has a strong memory management system and with no explicit pointers it reduce security problems. Garbage collection, Exception handling and type checking mechanism makes java robust.

Multi-threaded

Java has multi-threading feature which enables to write programs to perform multiple tasks simultaneously. Threads are separate programs which executes concurrently.

High Performance

Java has high performance because of its Just-In-Time compilers.

Distributed

With RMI and EJB Java can be used to create distributed applications.

Java Basic Concepts

Every program in java is a collection of objects communicating via invoking each others methods. Here are few java basic concepts.

Java Class

A class is a template or blueprint which defines the properties, states and behavior that objects of the class support.

Java Object

Object is an instance of a class which has behaviors and states. The properties and behaviors defined in a class are achieved through their objects.

Java Methods

Methods are behaviors which are defined inside a class. Logic is written is methods and many methods can be written in a class.

Instance Variables

Instance variables are used to store the states of objects. They are declared in class outside any method declaration or constructor.

Java Keywords

The keywords are reserved words with predefined meaning in java. They cannot be used by programmer as variable name, class name, method name or any other identifier name. Java has total 50 keywords.

Java Comments

comments are used to help the person reading code to better understand the functionality of the program. They are the integral part of any program.

Java Syntax

In computer programming the syntax is a set of rules which define how a program is written and interpreted. The java syntax is similar to C++.

Java Hello World

public class JavaHelloWorld {

/* This program will print Java Hello World on screen */

public static void main(String []args) {

System.out.println(“Java Hello World”);

}

}

Save this program in JavaHelloWorld.java file.

In command prompt go to the directory where this file is located and type ‘javac JavaHelloWorld.java’

It will compile your program. after that type ‘java JavaHelloWorld’ to see the output.
Code blocks

In java braces { and } are used for code blocks. Body of a method, if statement, loops etc are written inside these braces.

void myFun() {

int a;

a = 5;

}

Java Comments

Comments are ignored in program execution. Comments are also used by javadoc tool to generate automatic documentations. In java we can add comments in following ways.

// This is a single line comment

/* multi-line comment.

…. */

/**
* This is a javadoc comment.
*
* @author Allen Kooper
* @version 1.0.1
*/

Java Objects & Classes

Java is an object-oriented programming language and classes are fundamental part of any java program. Individual objects are created from these classes. Below is a java class example.

public class Employee{

int empAge;
String empName;

public void setEmpAge(int age){

}

public int getEmpAge(){

}

}

Java Objects

The java objects are similar to real world objects like human, cat, car etc. Each object has their own states and behaviors. The state of an object in java is stored in fields and behaviors are implemented through methods. The communication between objects are done through methods.

Local Variables

Variables which are defined inside method or constructor body are called local variables. The variable can be accessed inside that method and are destroyed when method completed.

Instance variables

Variables which are defined in class body but outside any method or constructor are instance variables. They are initialized when class is instantiated and can be accessed in method or constructor of that class.

Class Variables

Variables which are defined inside class body but outside any method or constructor with static keyword are called class variables.

Java Constructors

In java each class has a constructor method. If you do not write a constructor method in your class java compiler will automatically bind the default constructor with your class. The constructor method should have same name as of class name. When object of a class is created constructor will be invoked. There can be multiple constructors in same class.

Constructor Example

public class Employee{

public Employee(String name){

// constructor code goes here.

}

}

Creating Objects

Objects are created from classes. ‘new’ keyword is used to create object of a class. See the example below.

public class Employee{

public Employee(String empName){

System.out.println(“Employee Name is :” + empName );

}

public static void main(String []args){

// Creating an object newEmployee
Employee newEmployee = new Employee(“Jhon”);

}

}

Java Data Types

Variables are reserved memory locations which are used to store values. Different data types are assigned to variables depending on the value it will store in memory. Java has two data types.

  • Primitive Data Type
  • Object Data Type

Primitive Data Types

Primitive data types are predefined in java and there is a unique keyword for each data type. Following are primitive data type examples.

byte

  • 8-bit signed integer
  • Range: -128 to 127
  • Example: byte a = 50

short

  • 16-bit signed integer
  • Range: -32,768 to 32,767
  • Example: short a = 1050

int

  • 32-bit signed integer
  • Range: -2,147,483,648 to 2,147,483,647
  • Example: int a = 100000

long

  • 64-bit signed integer
  • Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  • Example: long a = 10000000

float

  • single-precision 32-bit floating point
  • should not use for precise values like currency
  • Example: float a = 453.46

double

  • single-precision 64-bit floating point
  • should not use for precise values like currency
  • Example: float a = 445353.46

boolean

  • 1-bit
  • possible values (true and false)
  • Example: boolean a = true

char

  • 16-bit single Unicode character
  • Example: char a =’A’

Reference Data Types

Reference data types are used to create and access objects. The reference variables are declared with a specific data type and it cannot be changed e.g. Car, Employee, Dog etc.

Example: Employee newEmployee = new Employee(“Jhon”);

Java Access Modifiers

Access modifiers are used to set access levels for variables, methods, constructors and classes. A special keyword is used for each access modifier except the default. Default access modifier has no keyword. There are following type of access modifiers in java.

  • default
  • public
  • private
  • protected

In java there are some non-access modifiers which are static, synchronized, abstract, native, volatile, transient etc.

Default Access Modifier

The default access modifier is not explicitly declared for a class, variable or method. Any method or variable without any access modifier is accessible in any class in same package.

String chapter= “5”;

int countPages() {
/*some code here*/
}

Public Access Modifier

The public access modifier is declared with public keyword and it is accessible everywhere.

public class HelloWorld{

public void msg(){
System.out.println(“Hello World”);
}

}

Private Access Modifier

Any variable, method or constructor declared with private access modifier can be accessed only in that class in which it is defined. it is the most restrictive access modifier. We cannot declare class and interfaces with private access modifier in java.

public class Car {

private int carMake;

public String getCarMake() {
return this.carMake;
}
public void setCarMake(String carMake) {
this.carMake = carMake;
}

}

Protected Access Modifier

Any variable, method or constructor declared with protected access modifier can only be access in sub-classes within package or any other package through inheritance. Class and interface cannot be declared protected also methods and variables in an interface cannot be declared protected.

public class HelloWorld{

protected void msg(){
System.out.println(“Hello World”);
}

}

Java Operators

Operators are used to manipulate variables. There are following type of operators in java.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations. Following is the list of arithmetic operators in java.

Symbol Operator Example
 + Additive Operator  r =  n + 1;
 – Subtraction Operator  r =  n – 1;
 * Multiplication Operator  r =  n * 1;
 / Division Operator  r = n / 1;
 % Remainder Operator  r = n % 1;

Relational Operators

Relational operators are used to compare two variable and it will return true or false depending on the operator and values are variables being compared.

Symbol Operator Example
 == Equal to  a = = b
 != Not equal to  a ! = b
 > Greater than  a > b
 <  Less than  a < b
 >= Greater than or equal to  a > = b
 <= Less than or equal to  a > = b

Bitwise Operators

The bitwise operators work on bit level. They are used to manipulate the contents of variables at a bit level.

Symbol Operator Example
 ~ Unary bitwise complement ~var1
 & Bitwise AND var1 & var2
 | Bitwise inclusive OR var1 | var2
 ^ Bitwise exclusive OR var1 ^ var2
 << Signed left shift var1 << var2
 >> Signed right sift var1 >> var2
 >>> Unsigned right shift var1 >>> var2

Logical Operators

Logical operators are used to perform logical operations on variables. It return true or false depending on the value of variables and operator used.

Symbol Operator
 & AND
 && Conditional-AND
 | OR
 || Conditional-OR
 ! NOT
 ? : Ternary

Assignment Operators

Assignment operators are used to perform assignment operations on variables.

Symbol Operator Example
 = Simple assignment r = a + b
 += Add and Assignment r += a equivalent r = r + a
 -= Subtract and Assignment r -= a equivalent r = r – a
 *= Multiply and Assignment r *= a equivalent r = r * a
 /= Divide and Assignment r l= a equivalent r = r / a

Java Conditional Statements

Conditional statements are used to evaluate one or more logical conditions along with a block of statements to be executed if the condition return true and optionally another block of statements to be executed if the logical condition return false. There are following conditional statements in java.

If Statement

The if statement is used to execute a block of code only if the applied condition (Boolean expression) return true.

Syntax:

if (condition) {

statements to be executed

}

The default and break statements are optional. Also there can be any number of case blocks in switch statement.

If – Else statement

The if – else statement consist of one if statement with a block of code to be executed if the condition return true and another block of code under else clause which is executed if the condition return false.

Syntax:

if (condition) {

statements to be executed if condition return true

} else {

statements to be executed if condition return false

}

If- Else – If statement

This is a nested if – else statement. It consist of multiple if conditions and an else statement. Each if condition has a block of code which is execute when the condition return true.

Syntax:

if (condition 1) {

statements to be executed if condition 1 return true

} else if(condition 2){

statements to be executed if condition 2 return true

} else {

statements to be executed if all condition return false

}

Switch Statement

The switch statement is used to test a variable for equality against a list of values. The switch statement is enclosed in a switch block and one or more case and/or default labels. The switch statement evaluate each case and execute the appropriate case block.

Syntax:

switch(expression){

case value1 :

statements to be executed

break;

case value2 :

statements to be executed

break;

case value3 :

statements to be executed

break;

default :

statements to be executed

}

The default and break statements are optional also there can be any number of case blocks in switch statement.

Java Loops

Loops are used to repeat the execution of a statement or block of statements while the provided condition returns true. There are following type of java loops.

Java For Loop

for loop executes a bunch of statements continuously to accomplish a particular condition. A for loop is used when you know how many time a block of code to be repeated.

For Loop Syntax

for(initialization; condition; update)

{

//for loop body

}

Initialization: initialize the loop control variable

Condition: a boolean expression

Update: update loop control variable

For Loop Example

public class JavaLoop {

public static void main(String args[]) {

for(int i = 1; x <= 10; i++) {

System.out.print(“i = ” + i );

System.out.print(“\n”);

}

}

}

Output:

i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

Java While Loop

The while loop is used when you don’t want to repeat the execution of the code for a specific number of time. Instead you want to repeatedly execute code until a specified condition is met. The condition is tested each time before execution of the loop body.

While loop syntax

while(condition)

{

//while loop body

}

While loop example

public class JavaLoop{

public static void main(String args[]) {

int i = 1;

while( i <= 10 ) {

System.out.print(“Repetition number = ” + i );

System.out.print(“\n”);

i++;

}

}

}

Output:

Repetition number = 1
Repetition number = 2
Repetition number = 3
Repetition number = 4
Repetition number = 5
Repetition number = 6
Repetition number = 7
Repetition number = 8
Repetition number = 9
Repetition number = 10

Java do..while loop

The only difference between while and do..while loop is that the body of do..while is executed before testing the condition which mean the body of do..while loop will be executed at least once.

do..while loop syntax

do

{

//do..while loop body

} while(condition);

do..while loop example

public class JavaLoop{

public static void main(String args[]) {

int i = 1;

do {

System.out.print(“Repetition number = ” + i );

System.out.print(“\n”);

i++;

} while( i <= 10 );

}

}

Output:

Repetition number = 1
Repetition number = 2
Repetition number = 3
Repetition number = 4
Repetition number = 5
Repetition number = 6
Repetition number = 7
Repetition number = 8
Repetition number = 9
Repetition number = 10

Java Arrays

The array data structure is a collection of same type of variables. Java arrays are used to store fixed size sequential collection of same type of elements. Items in array are called elements and they can be accessed by their index. This is how to declare, initialize and access arrays in java.

//declaring array of type integer
int[] myArray;

//allocating memory
myArray= new int[10];

//assigning values
myArray[0] = 5;
myArray[1] = 10;
myArray[2] = 15;
myArray[3] = 20;
myArray[4] = 25;
myArray[5] = 30;
myArray[6] = 35;
myArray[7] = 40;
myArray[8] = 45;
myArray[9] = 50;

//retrieving values
System.out.println(“Value at index 0 = “+ myArray[0]);
System.out.println(“Value at index 5 = “+ myArray[5]);

Processing Arrays

Usually loops are used to process arrays. We can use for loop and foreach loop to process array.

Processing Array Example

public class ArrayExample {

public static void main(String[] args) {

int[] myArray= {5,10,15,20,25,30,35,40,45,50};

int total = 0;

// processing array elements

for (int i = 0; i < myArray.length; i++) {

System.out.println(“Value at index ” + i + ” is = ” + myArray[i]);

total = total + myArray[i];

}

System.out.println(“Total is = ” + total);

}

}

Output:

Value at index 0 is = 5
Value at index 1 is = 10
Value at index 2 is = 15
Value at index 3 is = 20
Value at index 4 is = 25
Value at index 5 is = 30
Value at index 6 is = 35
Value at index 7 is = 40
Value at index 8 is = 45
Value at index 9 is = 50
Total is = 275

foreach Loop

The foreach loop makes it more easy to process arrays in java. You don’t need to use the index to access array element.

foreach Example

public class ArrayExample {

public static void main(String[] args) {

int[] myArray= {5,10,15,20,25,30,35,40,45,50};

int total = 0;

// processing array elements

for (int myVal: myArray) {

System.out.println(myVal);

total = total + myVal;

}

System.out.println(“Total is = ” + total);

}

}

Output:

5
10
15
20
25
30
35
40
45
50
Total is = 275