Friday, 27 March 2015

Complete Core Java along with OOPs

Java Basic Syntax : Java Basic Posted by Dinesh Rajput Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be in Upper Case.
Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.
When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program.  
Java Identifiers: All java components require names. Names used for classes, variables and methods are called identifiers. In java there are several points to remember about identifiers. They are as follows:  All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-).  After the first character identifiers can have any combination of characters.  A key word cannot be used as an identifier.  Most importantly identifiers are case sensitive.  Examples of legal identifiers:age, $salary, _value, __1_value  Examples of illegal identifiers : 123abc, -salary
Java Modifiers: Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories of modifiers.  Access Modifiers : defualt, public , protected, private  Non-access Modifiers : final, abstract, strictfp We will be looking into more details about modifiers in the next section.  Java Variables: We would see following type of variables in Java:  Local Variables  Class Variables (Static Variables)  Instance Variables (Non static variables)
Java Arrays: Arrays are objects that store multiple variables of the same type. However an Array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.  
Java Keywords: The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while    
Comments in Java:
Java supports single line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler. view plainprint?
1. public class MyFirstJavaProgram{   2.    3.    /* This is my first java program.  4.     * This will print 'Hello World' as the output  5.     * This is an example of multi-line comments.  6.     */   7.    8.     public static void main(String []args){   9.        // This is an example of single line comment   10.        /* This is also an example of single line comment. */   11.        System.out.println("Hello World");    12.     }   13. }     Using Blank Lines:
A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it. Inheritance:
In java classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
This concept allows you to reuse the fields and methods of the existing class with out having to rewrite the code in a new class. In this scenario the existing class is called the super class and the derived class is called the subclass. Interfaces:
In Java language an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.  
Hello World Example in Java Posted by Dinesh Rajput
In this tutorial, we will discuss how to write the hello world java program. Creating hello world java example is too easy. Here, we have created a class named MyFirstJavaProgram that contains only main method and prints a message "hello world". It is the simple program of java.  Requirement for Hello World Java Example:
 create the java program.  install the JDK if you don't have installed it, download the JDK and install it.
 set path of the bin directory under jdk.  compile and execute the program.
Creating hello java example: Let's create the hello world java program: view plainprint?
1. public class MyFirstJavaProgram {   2.    3.    /* This is my first java program.    4.     * This will print 'Hello World' as the output  5.     */   6.    7.     public static void main(String []args) {   8.        System.out.println("Hello World"); // prints Hello World   9.     }   10. }    
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
 Open notepad and add the code as above.  Save the file as : MyFirstJavaProgram.java.  Open a command prompt window and go o the directory where you saved the class. Assume its F:\Javas.  Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no errors in your code the command  prompt will take you to the next line.( Assumption : The path variable is set).  Now type ' java MyFirstJavaProgram ' to run your program.  You will be able to see ' Hello World ' printed on the window.
output: > C : > javac MyFirstJavaProgram.java C : > java MyFirstJavaProgram  Hello World  Understanding first java program: Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
 class is used to declare a class in java.  public is an access modifier which represents visibility, it means it is visible to all.  static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.  void is the return type of the method, it means it doesn't return any value.  main represents startup of the program.  String[] args is used for command line argument. We will learn it later.  System.out.println() is used print statement.
 
As displayed in the above diagram, write the MyFirstJavaProgram program of java in notepad and saved it asMyFirstJavaProgram.java. To compile and run this program, you need to open command prompt by Start -> All Programs -> Accessories -> command prompt.    
Variable and Datatype in Java Posted by Dinesh Rajput
In this tutorial, we will discuss about the variable and data types in java. Variable is a name of memory location. There are three types of variables: 1. local, 2. instance and 3. static. There are two types of datatypes in java, 1. primitive and 2. non-primitive.  Variable: Variable is name of reserved area allocated in memory.  
view plainprint?
1. int var = 10;//Here var is variable   Types of Variable: There are three types of variables in java 1. local variable 2. instance variable 3. static variable  
Local Variable A variable that is declared inside the method is called local variable.
 Local variables are declared in methods, constructors, or blocks.  Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.  Access modifiers cannot be used for local variables.  Local variables are visible only within the declared method, constructor or block.  Local variables are implemented at stack level internally.  There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use. view plainprint?
1. public class TestDemo{    2.    public void calc(){  
3.       int sum = 0;   4.       sum = sum + 17;   5.       System.out.println("Total sum is : " + sum);   6.    }   7.       8.    public static void main(String args[]){   9.       TestDemo test = new TestDemo();   10.       test.calc();   11.    }   12. }   This would produce following result: output: Total sum is : 17
Following example uses sum without initializing it, so it would give an error at the time of compilation. view plainprint?
1. public class TestDemo{    2.    public void calc(){   3.       int sum;   4.       sum = sum + 17;   5.       System.out.println("Total sum is : " + sum);   6.    }   7.       8.    public static void main(String args[]){   9.       TestDemo test = new TestDemo();   10.       test.calc();   11.    }   12. }   This would produce following result: output: TestDemo.java:4:variable number might not have been initialized sum = sum + 17; ^ 1 error Instance Variable A variable that is declared inside the class but outside the method is called instance variable . It is not declared as static.
 Instance variables are declared in a class, but outside a method, constructor or any block.  When a space is allocated for an object in the heap a slot for each instance variable value is created.  Instance variables are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed.  Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object.s state that must be present through out the class.  Instance variables can be declared in class level before or after use.  Access modifiers can be given for instance variables.  The instance variables are visible for all methods, constructors and block in the class. Normally it is recommended to make these variables private (access level).However visibility for subclasses can be given for these variables with the use of access modifiers.  Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) the should be called using the fully qualified name . ObjectReference.VariableName. view plainprint?
1. import java.io.*;   2.    3. public class Employee{   4.    // this instance variable is visible for any child class.   5.    public String name;   6.       7.    // salary  variable is visible in Employee class only.   8.    private double salary;   9.       10.    // The name variable is assigned in the constructor.    11.    public Employee (String empName){   12.       name = empName;   13.    }   14.    15.    // The salary variable is assigned a value.   16.    public void setSalary(double empSal){   17.       salary = empSal;   18.    }   19.       20.    // This method prints the employee details.   21.    public void printEmp(){   22.       System.out.println("name  : " + name );   23.       System.out.println("salary :" + salary);   24.    }   25.    26.    public static void main(String args[]){   27.       Employee empOne = new Employee("Dinesh Rajput");   28.       empOne.setSalary(70000);   29.       empOne.printEmp();   30.    }   31. }   This would produce following result: output: name : Dinesh Rajput salary :70000.0 Static variable A variable that is declared as static is called static variable. It cannot be local.
 Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.  There would only be one copy of each class variable per class, regardless of how many objects are created from it.  Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.  Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.  Static variables are created when the program starts and destroyed when the program stops.  Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks.  Static variables can be accessed by calling with the class name . ClassName.VariableName.  When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.
view plainprint?
1. import java.io.*;   2.    3. public class Employee{   4.    // salary  variable is a private static variable   5.    private static double salary;   6.    7.    // DEPARTMENT is a constant   8.    public static final String DEPARTMENT = "Development ";   9.    10.    public static void main(String args[]){   11.       salary = 70000;   12.       System.out.println(DEPARTMENT+"average salary:"+salary);   13.    }   14. }   This would produce following result: output: Development average salary:70000
Note: If the variables are access from an outside class the constant should be accessed as Employee.DEPARTMENT
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: view plainprint?
1. type identifier [ = value][, identifier [= value] ...] ;  
The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include an initialization. view plainprint?
1. int a, b, c;         // declares three ints, a, b, and c.   2. int d = 3, e, f = 5; // declares three more ints, initializing   3.                      // d and f.   4. byte z = 22;         // initializes z.   5. double pi = 3.14159; // declares an approximation of pi.   6. char x = 'x';        // the variable x has the value 'x'.   view plainprint?
1. class Test{   2.    3. int data=50;//instance variable   4.    5. static int m=100;//static variable  
6.    7. void method(){   8. int n=90;//local variable   9. }   10.    11. }//end of class    Data Types in Java: In java, there are two types of data types
1. primitive data types 2. non-primitive data types
Java Basic Data Types
Posted by Dinesh Rajput
In this tutorial, we will discuss about the basic data types in java. First we look one more time about the Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. There are two data types available in Java:
 Primitive Data Types  Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.
byte:
 Byte data type is a 8-bit signed two's complement integer.  Minimum value is -128 (-2^7)  Maximum value is 127 (inclusive)(2^7 -1)  Default value is 0  Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.  Example : byte a = 100 , byte b = -50
short:  Short data type is a 16-bit signed two's complement integer.  Minimum value is -32,768 (-2^15)  Maximum value is 32,767(inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int  Default value is 0.  Example : short s= 10000 , short r = -20000
int:  Int data type is a 32-bit signed two's complement integer.  Minimum value is - 2,147,483,648.(-2^31)  Maximum value is 2,147,483,647(inclusive).(2^31 -1)  Int is generally used as the default data type for integral values unless there is a concern about memory.  The default value is 0.  Example : int a = 100000, int b = -200000
long:  Long data type is a 64-bit signed two's complement integer.  Minimum value is -9,223,372,036,854,775,808.(-2^63)  Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)  This type is used when a wider range than int is needed.  Default value is 0L.  Example : int a = 100000L, int b = -200000L
float:  Float data type is a single-precision 32-bit IEEE 754 floating point.  Float is mainly used to save memory in large arrays of floating point numbers.  Default value is 0.0f.  Float data type is never used for precise values such as currency.  Example : float f1 = 234.5f
double:  double data type is a double-precision 64-bit IEEE 754 floating point.  This data type is generally used as the default data type for decimal values. generally the default choice.  Double data type should never be used for precise values such as currency.  Default value is 0.0d.  Example : double d1 = 123.4
boolean:  boolean data type represents one bit of information.  There are only two possible values : true and false.  This data type is used for simple flags that track true/false conditions.  Default value is false.  Example : boolean one = true
char:
 char data type is a single 16-bit Unicode character.  Minimum value is '\u0000' (or 0).  Maximum value is '\uffff' (or 65,535 inclusive).  Char data type is used to store any character.  Example . char letterA ='A' Reference Data Types:  Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Animal etc.  Class objects, and various type of array variables come under reference data type.  Default value of any reference variable is null.  A reference variable can be used to refer to any object of the declared type or any compatible type.  Example : Employee employee = new Employee("Dinesh Rajput"); Literals: A literal represents a value that stored into a variable directly in the program. view plainprint?
1. boolean result = false;   2. char gender = 'M';   3. short s = 10000;   4. int i = -1256;   In the preceding statements, the right hand side values are called literals because these values are being stored into the variables shown at the left hand side. As the data type of the variable changes, the type of the literal also changes. So we have different types of literals. These are as follows:
 Integer literals  Float literals  Character literals  String literals  Boolean literals
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Why char uses 2 byte in java and what is \u0000 ? because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of unicode system.To get detail about Unicode see below. Basic Comments in Java Posted by Dinesh Rajput
Whenever we want to write a program, we should first think about writing comments. What are comments? Comments are description about the features of a program. This means whatever we write in a program should be describe using comments. Why should we write comments? When we write comments, we can understand what the program is doing as well as helps others to easily follow our code. This means readability and understandability of a program will be more. If a program is understandable, then only can it be usable in a software. If other members of the software development team can not understand our program, then they may not able to use it in project and will reject it. So writing comments is compulsory in any program. Remember, it is good programing habit.
There are three types of comments in Java. 1. single line comment 2. multi line comment  3. java documentation
Single Line Comments: These comments are for making a single line as a comment. These comments start with double slash symbol // and after this, whatever we written till end of the line is taken as a comment.
Example:
view plainprint?
1. //This is my comment of one line.    Multi Line Comments: These comments are used for representing several lines as comments. These comments start with /* and end with */. In between /* and */, whatever is written is treated as a comment.
Example:
view plainprint?
1. /* This is a multi line comment. This is line one.  2. This is line two of the comment  3. This is line three of the comment. */    Java Documentation Comments: These comments start with /** and end with */. These comments are used to provide description for every feature in a Java program. This description proves helpful in the creation of a .html file called API(Application Programming Interface) document. Java Documentation comments should be used before every feature in the program as shown here:
view plainprint?
1. /** description about the class */   2. Class code{   3.    4. /** description about a method */   5. Method code(){   6.    7.    }   8. }   Basic Operators in Java Posted by Dinesh Rajput
In this tutorial we will discuss about the Basic Operators in Java and its used. Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
 Arithmetic Operators  Relational Operators  Bitwise Operators  Logical Operators  Assignment Operators  Misc Operators The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then: Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
%
Modulus - Divides left hand operand by right hand operand and returns remainder
B % A will give 0
++ Increment - Increase the value of operand by 1 B++ gives 21
-- Decrement - Decrease the value of operand by 1 B-- gives 19
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.
The Bitwise Operators:
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Operator Description Example
&
Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
|
Binary OR Operator copies a bit if it exists in eather operand.
(A | B) will give 61 which is 0011 1101
^
Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
~
Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.
(~A ) will give -60 which is 1100 0011
<<
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
A << 2 will give 240 which is 1111 0000
>>
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
A >> 2 will give 15 which is 1111
>>>
Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.
A >>>2 will give 15 which is 0000 1111
The Logical Operators:
The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Operator Description Example
&&
Called Logical AND operator. If both the operands are non zero then then condition becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is true.
The Assignment Operators:
There are following assignment operators supported by Java language:
Operator Description Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assigne value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by Java Language. Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as :
view plainprint?
1. variable x = (expression) ? value if true : value if false  
Following is the example:
view plainprint?
1. public class Test {   2.    3.    public static void main(String args[]){   4.       int a , b;   5.       a = 10;   6.       b = (a == 1) ? 20: 30;   7.       System.out.println( "Value of b is : " +  b );   8.    9.       b = (a == 10) ? 20: 30;   10.       System.out.println( "Value of b is : " + b );   11.    }   12. }   This would produce following result:
output: Value of b is : 30 Value of b is : 20
instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is written as:
view plainprint?
1. ( Object reference variable ) instanceOf  (class/interface type)   If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side then the result will be true. Following is the example:
view plainprint?
1. String name = = "Dinesh";   2. boolean result = name instanceOf String;     3. // This will return true since name is type of String   This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:
view plainprint?
1. class Vehicle {}   2.    3. public class Car extends Vehicle {   4.    public static void main(String args[]){   5.       Vehicle a = new Car();   6.       boolean result =  a instanceof Car;   7.       System.out.println( result);   8.    }   9. }   This would produce following result:
output: true Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.
Category  Operator  Associativity
Postfix  () [] . (dot operator) Left to right
Unary  ++ - - ! ~ Right to left
Multiplicative   * / %  Left to right
Additive   + -  Left to right
Shift   >> >>> <<   Left to right
Relational   > >= < <=   Left to right
Equality   == !=  Left to right
Bitwise AND  &  Left to right
Bitwise XOR  ^  Left to right
Bitwise OR  |  Left to right
Logical AND  &&  Left to right
Logical OR  ||  Left to right
Conditional  ?:  Right to left
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left
Comma  ,  Left to right
 
Control Statements in Java
Posted by Dinesh Rajput
In this tutorial we are going to discuss the control statements. Different types of control statements: the decision making statements (if-then, if-then-else and switch), looping statements (while, do-while and for) and branching statements (break, continue, return) supported by the Java programming language.
Control Statements: The control statement are used to controll the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic. Java contains the following types of control statements:
1- Selection Statements 2- Repetition Statements 3- Branching Statements
 Selection Statements(The if-then and if-then-else Statements): The if-then Statement: The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:  
Syntax:   if(conditional_expression){   <statements>;   ...;   ...; }  
view plainprint?
1. void applyBrakes() {   2.     // the "if" clause: bicycle must be moving   3.     if (isMoving){    4.         // the "then" clause: decrease current speed   5.         currentSpeed--;   6.     }   7. }   If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement. In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
view plainprint?
1. void applyBrakes() {   2.     // same as above, but without braces    3.     if (isMoving)   4.         currentSpeed--;   5. }   Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
The if-then-else Statement: The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use anif-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.  
Syntax:    if(conditional_expression){
  <statements>;   ...;   ...;   }    else{   <statements>;   ....;   ....;    }  
view plainprint?
1. void applyBrakes() {   2.     if (isMoving) {   3.         currentSpeed--;   4.     } else {   5.         System.err.println("The bicycle has " + "already stopped!");   6.     }    7. }   The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
view plainprint?
1. class IfElseDemo {   2.     public static void main(String[] args) {   3.    4.         int testscore = 76;   5.         char grade;   6.    7.         if (testscore >= 90) {   8.             grade = 'A';   9.         } else if (testscore >= 80) {   10.             grade = 'B';   11.         } else if (testscore >= 70) {   12.             grade = 'C';   13.         } else if (testscore >= 60) {   14.             grade = 'D';   15.         } else {   16.             grade = 'F';   17.         }   18.         System.out.println("Grade = " + grade);   19.     }   20. }   The output from the program is:
    Grade = C You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.
The switch Statement:
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switchworks with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes
that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings). The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement.
Syntax:   switch(control_expression){   case expression 1:   <statement>;   case expression 2:   <statement>;    ...    ...   case expression n:   <statement>;   default:   <statement>;   }//end switch  
view plainprint?
1. public class SwitchDemo {   2.     public static void main(String[] args) {   3.    4.         int month = 8;   5.         String monthString;   6.         switch (month) {   7.             case 1:  monthString = "January";   8.                      break;   9.             case 2:  monthString = "February";   10.                      break;   11.             case 3:  monthString = "March";   12.                      break;   13.             case 4:  monthString = "April";   14.                      break;   15.             case 5:  monthString = "May";   16.                      break;   17.             case 6:  monthString = "June";   18.                      break;   19.             case 7:  monthString = "July";   20.                      break;   21.             case 8:  monthString = "August";   22.                      break;   23.             case 9:  monthString = "September";   24.                      break;   25.             case 10: monthString = "October";   26.                      break;   27.             case 11: monthString = "November";   28.                      break;   29.             case 12: monthString = "December";   30.                      break;   31.             default: monthString = "Invalid month";   32.                      break;  
33.         }   34.         System.out.println(monthString);   35.     }   36. }   In this case, August is printed to standard output.
The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.
You could also display the name of the month with if-then-else statements:
view plainprint?
1. int month = 8;   2. if (month == 1) {   3.     System.out.println("January");   4. } else if (month == 2) {   5.     System.out.println("February");   6. }   7. ...  // and so on  
Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas aswitch statement tests expressions based only on a single integer, enumerated value, or String object. Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year:
view plainprint?
1. public class SwitchDemoFallThrough {   2.    3.     public static void main(String args[]) {   4.         java.util.ArrayList<string> futureMonths =   5.             new java.util.ArrayList<string>();   6.    7.         int month = 8;   8.    9.         switch (month) {   10.             case 1:  futureMonths.add("January");   11.             case 2:  futureMonths.add("February");   12.             case 3:  futureMonths.add("March");   13.             case 4:  futureMonths.add("April");   14.             case 5:  futureMonths.add("May");   15.             case 6:  futureMonths.add("June");   16.             case 7:  futureMonths.add("July");   17.             case 8:  futureMonths.add("August");   18.             case 9:  futureMonths.add("September");   19.             case 10: futureMonths.add("October");   20.             case 11: futureMonths.add("November");   21.             case 12: futureMonths.add("December");   22.                      break;  
23.             default: break;   24.         }   25.    26.         if (futureMonths.isEmpty()) {   27.             System.out.println("Invalid month number");   28.         } else {   29.             for (String monthName : futureMonths) {   30.                System.out.println(monthName);   31.             }   32.         }   33.     }   34. }   35. </string></string>  
This is the output from the code:
August September October November December
Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections.
The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month: view plainprint?
1. class SwitchDemo2 {   2.     public static void main(String[] args) {   3.    4.         int month = 2;   5.         int year = 2000;   6.         int numDays = 0;   7.    8.         switch (month) {   9.             case 1: case 3: case 5:   10.             case 7: case 8: case 10:   11.             case 12:   12.                 numDays = 31;   13.                 break;   14.             case 4: case 6:   15.             case 9: case 11:   16.                 numDays = 30;   17.                 break;   18.             case 2:   19.                 if (((year % 4 == 0) &&    20.                      !(year % 100 == 0))   21.                      || (year % 400 == 0))   22.                     numDays = 29;   23.                 else   24.                     numDays = 28;   25.                 break;   26.             default:  
27.                 System.out.println("Invalid month.");   28.                 break;   29.         }   30.         System.out.println("Number of Days = "   31.                            + numDays);   32.     }   33. }  
This is the output from the code:
Number of Days = 29
Using Strings in switch Statements:
In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example,StringSwitchDemo, displays the number of the month based on the value of the String named month:
view plainprint?
1. public class StringSwitchDemo {   2.    3.     public static int getMonthNumber(String month) {   4.    5.         int monthNumber = 0;   6.    7.         if (month == null) {   8.             return monthNumber;   9.         }   10.    11.         switch (month.toLowerCase()) {   12.             case "january":   13.                 monthNumber = 1;   14.                 break;   15.             case "february":   16.                 monthNumber = 2;   17.                 break;   18.             case "march":   19.                 monthNumber = 3;   20.                 break;   21.             case "april":   22.                 monthNumber = 4;   23.                 break;   24.             case "may":   25.                 monthNumber = 5;   26.                 break;   27.             case "june":   28.                 monthNumber = 6;   29.                 break;   30.             case "july":   31.                 monthNumber = 7;   32.                 break;   33.             case "august":   34.                 monthNumber = 8;   35.                 break;   36.             case "september":  
37.                 monthNumber = 9;   38.                 break;   39.             case "october":   40.                 monthNumber = 10;   41.                 break;   42.             case "november":   43.                 monthNumber = 11;   44.                 break;   45.             case "december":   46.                 monthNumber = 12;   47.                 break;   48.             default:    49.                 monthNumber = 0;   50.                 break;   51.         }   52.    53.         return monthNumber;   54.     }   55.    56.     public static void main(String[] args) {   57.    58.         String month = "August";   59.    60.         int returnedMonthNumber =   61.             StringSwitchDemo.getMonthNumber(month);   62.    63.         if (returnedMonthNumber == 0) {   64.             System.out.println("Invalid month");   65.         } else {   66.             System.out.println(returnedMonthNumber);   67.         }   68.     }   69. }  
The output from this code is 8.
The String in the switch expression is compared with the expressions associated with each case label as if the String.equalsmethod were being used. In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase. Note: This example checks if the expression in the switch statement is null. Ensure that the expression in any switchstatement is not null to prevent a NullPointerException from being thrown.
Repetition Statements(The while and do-while Statements): while loop statements: The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:  
Syntax:
   while(expression){   <statement>;   ...;   ...;   }
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the whilestatement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:  
view plainprint?
1. class WhileDemo {   2.     public static void main(String[] args){   3.         int count = 1;   4.         while (count < 11) {   5.             System.out.println("Count is: " + count);   6.             count++;   7.         }   8.     }   9. }   You can implement an infinite loop using the while statement as follows:
view plainprint?
1. while (true){   2.     // your code goes here   3. }  
do-while loop statements:
This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once. Syntax: do{ ; ...; ...; }while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the followingDoWhileDemo program:
view plainprint?
1. class DoWhileDemo {   2.     public static void main(String[] args){   3.         int count = 1;   4.         do {   5.             System.out.println("Count is: " + count);   6.             count++;   7.         } while (count < 11);   8.     }   9. }  
The for Statement:
 The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
Syntax:     for (initialization; condition; increment or decrement){   <statement>;   ...;   ...;   }  
When using this version of the for statement, keep in mind that:
 The initialization expression initializes the loop; it's executed once, as the loop begins.  When the termination expression evaluates to false, the loop terminates.  The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output: view plainprint?
1. class ForDemo {   2.     public static void main(String[] args){   3.          for(int i=1; i<11; i++){   4.               System.out.println("Count is: " + i);   5.          }   6.     }   7. }   The output of this program is:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors. The three expressions of the for loop are optional; an infinite loop can be created as follows:
view plainprint?
1. // infinite loop   2. for ( ; ; ) {   3.        4.     // your code goes here   5. }   The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
view plainprint?
1. int[] numbers = {1,2,3,4,5,6,7,8,9,10};   The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
view plainprint?
1. class EnhancedForDemo {   2.     public static void main(String[] args){   3.          int[] numbers =    4.              {1,2,3,4,5,6,7,8,9,10};   5.          for (int item : numbers) {   6.              System.out.println("Count is: " + item);   7.          }   8.     }   9. }   In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:
output: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10
We recommend using this form of the for statement instead of the general form whenever possible.
Branching Statements:
The break Statement:
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switchstatement. You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the followingBreakDemo program:
Syntax:
  break;  // breaks the innermost loop or switch statement.   break label;   // breaks the outermost loop in a series of nested loops.
view plainprint?
1. class BreakDemo {   2.     public static void main(String[] args) {   3.    4.         int[] arrayOfInts =    5.             { 32, 87, 3, 589,   6.               12, 1076, 2000,   7.               8, 622, 127 };   8.         int searchfor = 12;   9.    10.         int i;   11.         boolean foundIt = false;   12.    13.         for (i = 0; i < arrayOfInts.length; i++) {   14.             if (arrayOfInts[i] == searchfor) {   15.                 foundIt = true;   16.                 break;   17.             }   18.         }   19.    20.         if (foundIt) {   21.             System.out.println("Found " + searchfor + " at index " + i);   22.         } else {   23.             System.out.println(searchfor + " not in the array");   24.         }   25.     }   26. }   This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the statement after the for loop. This program's output is:
output:  Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled breakterminates an outer statement. The following program, BreakWithLabelDemo, is similar to the previous program, but uses nestedfor loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):
view plainprint?
1. class BreakWithLabelDemo {   2.     public static void main(String[] args) {   3.    4.         int[][] arrayOfInts = {    5.             { 32, 87, 3, 589 },   6.             { 12, 1076, 2000, 8 },   7.             { 622, 127, 77, 955 }   8.         };   9.         int searchfor = 12;   10.    11.         int i;   12.         int j = 0;   13.         boolean foundIt = false;  
14.    15.     search:   16.         for (i = 0; i < arrayOfInts.length; i++) {   17.             for (j = 0; j < arrayOfInts[i].length;   18.                  j++) {   19.                 if (arrayOfInts[i][j] == searchfor) {   20.                     foundIt = true;   21.                     break search;   22.                 }   23.             }   24.         }   25.    26.         if (foundIt) {   27.             System.out.println("Found " + searchfor + " at " + i + ", " + j);   28.         } else {   29.             System.out.println(searchfor + " not in the array");   30.         }   31.     }   32. }   This is the output of the program.  Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.  
 The continue Statement:
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.
view plainprint?
1. class ContinueDemo {   2.     public static void main(String[] args) {   3.    4.         String searchMe = "peter piper picked a " + "peck of pickled peppers";   5.         int max = searchMe.length();   6.         int numPs = 0;   7.    8.         for (int i = 0; i < max; i++) {   9.             // interested only in p's   10.             if (searchMe.charAt(i) != 'p')   11.                 continue;   12.    13.             // process p's   14.             numPs++;   15.         }   16.         System.out.println("Found " + numPs + " p's in the string.");   17.     }   18. }   Here is the output of this program: Found 9 p's in the string.
 To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9. A labeled continue statement skips the current iteration of an outer loop marked with the given label. The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string. Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched. The following program,ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.
view plainprint?
1. class ContinueWithLabelDemo {   2.     public static void main(String[] args) {   3.    4.         String searchMe = "Look for a substring in me";   5.         String substring = "sub";   6.         boolean foundIt = false;   7.    8.         int max = searchMe.length() -    9.                   substring.length();   10.    11.     test:   12.         for (int i = 0; i <= max; i++) {   13.             int n = substring.length();   14.             int j = i;   15.             int k = 0;   16.             while (n-- != 0) {   17.                 if (searchMe.charAt(j++) != substring.charAt(k++)) {   18.                     continue test;   19.                 }   20.             }   21.             foundIt = true;   22.                 break test;   23.         }   24.         System.out.println(foundIt ? "Found it" : "Didn't find it");   25.     }   26. }   Here is the output from this program.  Found it  
The return Statement:
The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value.
return;
 
Summary of Control Flow Statements:
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. The while and do-while statements continually execute a block of statements while a particular condition is true. The difference between dowhile and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. The for statement provides a compact way to iterate over a range of values. It has two forms, one of which was designed for looping through collections and arrays. Array in Java Posted by Dinesh Rajput
In this tutorial we will discuss about the array in java and what its need. Suppose a class contain 50 students, and we want to store their roll numbers, we need 50 separate variables for storing the roll numbers, as shown here:
view plainprint?
1. int rno;   2. int rno1;   3. int rno2;   4. .   5. .   6. .   7. int rno49  
Now to store roll numbers into these variables, we need another 50 students. Imagine writing 100 statements just to store the roll numbers of students. On other hand, if we have a single variable which can represent all these 50 variables, it would be very useful to us. Such a variable is called an 'array'.  
An array represents a group of elements of same data type. It can store a group of elements. So we can store group of int values or group of float values or group of strings in the array. But we can not store some int values and some float values in the array.
Array: Array is the most important thing in any programming language. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the values in memory at the fixed size. Multiple types of arrays are used in any programming language such as:  one - dimensional,  two - dimensional or can say multi - dimensional.  
In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed elements in an array.
Array is index based, first element of the array is stored at 0 index.
 
Advantage of Array
Code Optimization: It makes the code optimized, we can retrive or sort the data easily. Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Declaring Array Variables: To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
view plainprint?
1. dataType[] arrayVar;   // preferred way.   2.    3. or   4.    5. dataType arrayVar[];  //  works but not preferred way.   Note: The style dataType[] arrayVar is preferred. The style dataType arrayVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example: The following code snippets are examples of this syntax:
view plainprint?
1. int[] myList;         // preferred way.   2.    3. or   4.    5. int myList[];         //  works but not preferred way.  
Creating Arrays:
You can create an array by using the new operator with the following syntax:
view plainprint?
1. arrayVar = new dataType[arraySize];   The above statement does two things:
 It creates an array using new dataType[arraySize];
 It assigns the reference of the newly created array to the variable arrayVar. Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below: view plainprint?
1. dataType[] arrayVar = new dataType[arraySize];   Alternatively you can create arrays as follows:
view plainprint?
1. dataType[] arrayVar = {value0, value1, ..., valuek};  
Example: Following statement declares an array variable, myList, creates an array of 5 elements of double type, and assigns its reference to myList.:
view plainprint?
1. int[] myList = new int[5];  
In java arrays are objects. All methods of an Object can be invoked on an array. Arrays are stored in heap memory.  
Though you view the array as cells of values, internally they are cells of variables. A java array is a group
of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the 'components' of a java array. All the components must be of same type and that is called as ‘component type’ of that java array.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
view plainprint?
1. public class TestArray {   2.    3.    public static void main(String[] args) {   4.       double[] myList = {1.9, 2.9, 3.4, 3.5};   5.    6.       // Print all the array elements   7.       for (int i = 0; i < myList.length; i++) {   8.          System.out.println(myList[i] + " ");   9.       }   10.       // Summing all elements   11.       double total = 0;   12.       for (int i = 0; i < myList.length; i++) {   13.          total += myList[i];   14.       }   15.       System.out.println("Total is " + total);   16.       // Finding the largest element   17.       double max = myList[0];   18.       for (int i = 1; i < myList.length; i++) {   19.          if (myList[i] > max) max = myList[i];   20.       }   21.       System.out.println("Max is " + max);   22.    }   23. }  
This would produce following result:
output: 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5
The foreach Loops:
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.  Example:
 The following code displays all the elements in the array myList:
view plainprint?
1. public class TestArray {   2.    3.    public static void main(String[] args) {   4.       double[] myList = {1.9, 2.9, 3.4, 3.5};   5.    6.       // Print all the array elements   7.       for (double element: myList) {   8.          System.out.println(element);   9.       }   10.    }   11. }   This would produce following result:
output: 1.9 2.9 3.4 3.5
Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:
view plainprint?
1. public static void printArray(int[] array) {   2.   for (int i = 0; i < array.length; i++) {   3.     System.out.print(array[i] + " ");   4.   }   5. }   You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:
view plainprint?
1. printArray(new int[]{3, 1, 2, 6, 4, 2});   Returning an Array from a Method:  A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:
view plainprint?
1. public static int[] reverse(int[] list) {   2.   int[] result = new int[list.length];   3.    4.   for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {   5.     result[j] = list[i];   6.   }   7.   return result;   8. }  
The Arrays Class:  The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
SN Methods with Description
1
public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2
public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
3
public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
4
public static void sort(Object[] a) Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
Multidimensional array: In such case, data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array in java:
view plainprint?
1. dataType[][] arrayRefVar; (or)   2. dataType [][]arrayRefVar; (or)   3. dataType arrayRefVar[][]; (or)   4. dataType []arrayRefVar[];    Example to initantiate Multidimensional Array in java
view plainprint?
1. int[][] arr=new int[3][3];//3 row and 3 column   Example to initialize Multidimensional Array in java
view plainprint?
1. arr[0][0]=1;   2. arr[0][1]=2;   3. arr[0][2]=3;  
4. arr[1][0]=4;   5. arr[1][1]=5;   6. arr[1][2]=6;   7. arr[2][0]=7;   8. arr[2][1]=8;   9. arr[2][2]=9;   Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
view plainprint?
1. class B{   2. public static void main(String args[]){   3.    4. //declaring and initializing 2D array   5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};   6.    7. //printing 2D array   8. for(int i=0;i<3;i++){   9.  for(int j=0;j<3;j++){   10.    System.out.print(arr[i][j]+" ");   11.  }   12.  System.out.println();   13. }   14. }   15. }  
output:    1 2 3    2 4 5    4 4 5
String Class in Java
Posted by Dinesh Rajput
A string in literal terms is a series of characters. Hey, did you say characters, isn’t it a primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an array of characters.
Java String: String is one of the widely used java classes. It is special in java as it has some special characteristics than a usual java class. Lets explore java String in this article and this page aims to serve you as a single point reference for all your queries on Java String.
Though you might be knowing most of the things, this will help you to recall them and I am sure you will find one or two new things. I recommend you to take your time and read through this completely as java String is a basic building block of your java programs.
Immutable Java String:
Java String is a immutable object. For an immutable object you cannot modify any of its attribute’s values. Once you have created a java String object it cannot be modified to some other object or a different String. References to a java String instance is mutable. There are multiple ways to make an object immutable. Simple and straight forward way is to make all the attributes of that class as final. Java String has all attributes marked as final except hash field. Java String is final. I am not able to nail down the exact reason behind it. But my guess is, implementers of String didn’t want anybody else to mess with String type and they wanted de-facto definition for all the behaviors of String.
We all know java String is immutable but do we know why java String is immutable? Main reason behind it is for better performance. Creating a copy of existing java String is easier as there is no need to create a new instance but can be easily created by pointing to already existing String. This saves valuable primary memory. Using String as a key for Hashtableguarantees that there will be no need for re hashing because of object change. Using java String in multithreaded environment is safe by itself and we need not take any precautionary measures.
Java String Instantiation In continuation with above discussion of immutability of java String we shall see how that property is used for instantiating a Sting instance. JVM maintains a memory pool for String. When you create a String, first this memory pool is scanned. If the instance already exists then this new instance is mapped to the already existing instance. If not, a new java String instance is created in the memory pool.
This approach of creating a java String instance is in sync with the immutable property. When you use ‘new’ to instantiate a String, you will force JVM to store this new instance is fresh memory location thus bypassing the memory map scan. Inside a String class what you have got is a char array which holds the characters in the String you create.
The Java platform provides the String class to create and manipulate strings. Creating Strings:
The most direct way to create a string is to write:
view plainprint?
1. String greeting = "Hello world!";  
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!''.
As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:
view plainprint?
1. public class StringDemo{   2.    3.    public static void main(String args[]){   4.       char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};  
5.       String helloString = new String(helloArray);     6.       System.out.println( helloString );   7.    }   8. }   This would produce following result:
output: hello
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then you should use String Buffer & String Builder Classes.
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.
After the following two lines of code have been executed, length equals 17:
view plainprint?
1. public class StringDemo {   2.    3.    public static void main(String args[]) {   4.       String palindrome = "Dot saw I was Tod";   5.       int len = palindrome.length();   6.       System.out.println( "String Length is : " + len );   7.    }   8. }  
This would produce following result:
output: String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
view plainprint?
1. string1.concat(string2);   This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:
view plainprint?
1. "My name is ".concat("Dinesh");   Strings are more commonly concatenated with the + operator, as in:
view plainprint?
1. "Hello," + " world" + "!"   which results in:
"Hello, world!"
Let us look at the following example:
view plainprint?
1. public class StringDemo {   2.    3.    public static void main(String args[]) {   4.       String string1 = "saw I was ";   5.       System.out.println("Dot " + string1 + "Tod");   6.    }   7. }   This would produce following result:
output: Dot saw I was Tod Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of:
view plainprint?
1. System.out.printf("The value of the float variable is " +   2.                   "%f, while the value of the integer " +   3.                   "variable is %d, and the string " +   4.                   "is %s", floatVar, intVar, stringVar);   you can write:
view plainprint?
1. String fs;   2. fs = String.format("The value of the float variable is " +   3.                    "%f, while the value of the integer " +   4.                    "variable is %d, and the string " +   5.                    "is %s", floatVar, intVar, stringVar);   6. System.out.println(fs);    String Methods: Here is the list methods supported by String class:
SN Methods with Description
1
char charAt(int index)  Returns the character at the specified index.
2
int compareTo(Object o)  Compares this String to another Object.
3
int compareTo(String anotherString) Compares two strings lexicographically.
4
int compareToIgnoreCase(String str)  Compares two strings lexicographically, ignoring case differences.
5
String concat(String str) Concatenates the specified string to the end of this string.
6
boolean contentEquals(StringBuffer sb)  Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
7
static String copyValueOf(char[] data)  Returns a String that represents the character sequence in the array specified.
8
static String copyValueOf(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified.
9
boolean endsWith(String suffix)  Tests if this string ends with the specified suffix.
10
boolean equals(Object anObject) Compares this string to the specified object.
11
boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.
12
byte getBytes()  Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
13
byte[] getBytes(String charsetName Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
14
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array.
15
int hashCode() Returns a hash code for this string.
16
int indexOf(int ch)  Returns the index within this string of the first occurrence of the specified character.
17
int indexOf(int ch, int fromIndex)  Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
18
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
19
int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
20
String intern() Returns a canonical representation for the string object.
21
int lastIndexOf(int ch)  Returns the index within this string of the last occurrence of the specified character.
22
int lastIndexOf(int ch, int fromIndex)  Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
23
int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring.
24
int lastIndexOf(String str, int fromIndex)  Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
25
int length()  Returns the length of this string.
26 boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
27
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)  Tests if two string regions are equal.
28
boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal.
29
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.
31
String replaceFirst(String regex, String replacement)  Replaces the first substring of this string that matches the given regular expression with the given replacement.
32
String[] split(String regex)  Splits this string around matches of the given regular expression.
33
String[] split(String regex, int limit)  Splits this string around matches of the given regular expression.
34
boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
35
boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index.
36
CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence.
37
String substring(int beginIndex) Returns a new string that is a substring of this string.
38
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.
39 char[] toCharArray()
Converts this string to a new character array.
40
String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.
41
String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale.
42
String toString() This object (which is already a string!) is itself returned.
43
String toUpperCase()  Converts all of the characters in this String to upper case using the rules of the default locale.
44
String toUpperCase(Locale locale)  Converts all of the characters in this String to upper case using the rules of the given Locale.
45
String trim()  Returns a copy of the string, with leading and trailing whitespace omitted.
46
static String valueOf(primitive data type x)  Returns the string representation of the passed data type argument.
Objects and Classes in Java
Posted by Dinesh Rajput Introduction to Java Classes:
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming.
A class has the following general syntax:
view plainprint?
1. <class modifiers>class<class name>   2. <extends clause> <implements clause>{  
3.    4. // Dealing with Classes (Class body)   5. <field declarations (Static and Non-Static)>   6. <method declarations (Static and Non-Static)>   7. <Inner class declarations>   8. <nested interface declarations>   9. <constructor declarations>   10. <Static initializer blocks>   11. }  
Below is an example showing the Objects and Classes of the Cuboid class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().
view plainprint?
1. public class Cuboid {   2.    3.  int length;   4.  int breadth;   5.  int height;   6.  public int getVolume() {   7.   return (length * breadth * height);   8.  }   9. }  
Java is an Object Oriented Language. As a language that has the Object Oriented feature Java supports the following fundamental concepts:
 Polymorphism  Inheritance  Encapsulation  Abstraction  Classes  Objects  Instance  Method  Message Parsing
In this chapter we will look into the concepts Classes and Objects.
Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans, Bricks etc. All these objects have a state and behavior.
 If we consider a dog then its state is - name, breed, color, and the behavior is - barking, wagging, running
If you compare the software object with a real world object, they have very similar characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods.
So in software development methods operate on the internal state of an object and the object-to-object communication is done via methods.
Syntax for the Object :  
class_name object_name = new class_name();
view plainprint?
1. public class Dog{   2.    String breed;   3.    int age;   4.    String color;   5.    6.    void barking(){   7.    }   8.       9.    void hungry(){   10.    }   11.       12.    void sleeping(){   13.    }   14. }  
A class can contain any of the following variable types.
 Local variables . variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.  Instance variables . Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.  Class variables . Class variables are variables declared with in a class, outside any method, with the static keyword. A class can have any number of methods to access the value of various kind of methods. In the above example, barking(), hungry() and sleeping() are methods.
Note: Method is not but is special type of function which define in the class.
Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.
 Constructors:
When discussing about classes one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.
Each time a new object is created at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.
Example of a constructor is given below:
view plainprint?
1. public class Shepherd{   2.    public Shepherd(){   3.    }   4.    5.    public Shepherd(String name){   6.       // This constructor has one parameter, name.   7.    }   8. }  
Note: Java also supports Singleton Classes where you would be able to create only one instance of a class.  Creating an Object: As mentioned previously a class provides the blueprints for objects. So basically an object is created from a class. In java the new key word is used to create new objects.  There are three steps when creating an object from a class:
 Declaration . A variable declaration with a variable name with an object type.  Instantiation . The 'new' key word is used to create the object.  Initialization . The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Example of creating an object is given below: view plainprint?
1. public class Shepherd{   2.    3.    public Shepherd(String name){   4.       // This constructor has one parameter, name.   5.       System.out.println("Passed Name is :" + name );    6.    }   7.    public static void main(String []args){   8.       // Following statement would create an object myShepherd   9.       Shepherd myShepherd = new Shepherd( "tommy" );   10.       Shepherd urShepherd = new Shepherd( "jimmy" );   11.    }   12. }  
If we compile and run the above program then it would produce following result:
output: Passed Name is :tommy Passed Name is :jimmy    
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows:
view plainprint?
1. /* First create an object */   2. ObjectReference = new Constructor();   3.    4. /* Now call a variable as follows */   5. ObjectReference.variableName;   6.    7. /* Now you can call a class method as follows */   8. ObjectReference.MethodName();  
Example:
This example explains how to access instance variables and methods of a class:
view plainprint?
1. public class Shepherd{   2.       3.    int shepAge;  
4.    5.    public Shepherd(String name){   6.       // This constructor has one parameter, name.   7.       System.out.println("Passed Name is :" + name );    8.    }   9.    public void setAge( int age ){   10.        shepAge= age;   11.    }   12.    13.    public int getAge( ){   14.        System.out.println("Shepherd's age is :" + shepAge);    15.        return shepAge;   16.    }   17.    public static void main(String []args){   18.       /* Object creation */   19.       Shepherd myShepherd = new Shepherd( "tommy" );   20.    21.       /* Call class method to set Shepherd's age */   22.       myShepherd.setAge( 2 );   23.    24.       /* Call another class method to get Shepherd's age */   25.       myShepherd.getAge( );   26.    27.       /* You can access instance variable as follows as well */   28.       System.out.println("Variable Value :" + myShepherd.shepAge );    29.    }   30. }   If we compile and run the above program then it would produce following result:
output: Passed Name is :tommy Shepherd's age is :2 Variable Value :2
Source file declaration rules: As the last part of this section lets us now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.
 There can be only one public class per source file.  A source file can have multiple non public classes.  The public class name should be the name of the source file as well which should be appended by .java at the end. For example : The class name is . public class Employee{} Then the source file should be as Employee.java.  If the class is defined inside a package, then the package statement should be the first statement in the source file.  If import statements are present then they must be written between the package statement and the class declaration. If there are no package statements then the import statement should be the first line in the source file.  Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file. Classes have several access levels and there are different types of classes; abstract classes, final classes etc. I will be explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.
Java Package: In simple it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.
Import statements: In java if a fully qualified name, which includes the package and the class name, is given then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class. For example following line would ask compiler to load all the classes available in directory java_installation/java/io : view plainprint?
1. import java.io.*;   Basic Modifier Types in Java Posted by Dinesh Rajput
Access modifiers specifies who can access them. There are four access modifiers used in java. They are public, private, protected, no modifier (declaring without an access modifier). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.
I) Class level access modifiers (java classes only) Only two access modifiers is allowed, public and no modifier
 If a class is ‘public’, then it CAN be accessed from ANYWHERE.  If a class has ‘no modifier’, then it CAN ONLY be accessed from ‘same package’.
II) Member level access modifiers (java variables and java methods) All the four public, private, protected and no modifier is allowed.  public and no modifier – the same way as used in class level.  private – members CAN ONLY access.  protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access. For better understanding, member level access is formulated as a table:   Same Class Same Package Subclass Other packages
Access Modifiers
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N
First row {public Y Y Y Y} should be interpreted as:
 Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same class’.  Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same package’.  Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘subclass’.  Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’. Second row {protected Y Y Y N} should be interpreted as:  Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same class’.  Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same package’.  Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘subclass’.  N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’. similarly interpret the access modifiers table for the third (no access modifier) and fourth (private access modifier) records.
Methods in Java
Posted by Dinesh Rajput
A Java method is a collection of statements that are grouped together to perform an operation. When you call theSystem.out.println method, for example, the system actually executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.
Creating a Method:
In general, a method has the following syntax:
view plainprint?
1. modifier returnValueType methodName(list of parameters) {   2.   // Method body;   3. }  
A method definition consists of a method header and a method body. Here are all the parts of a method:
 Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.  Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.  Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.  Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.  Method Body: The method body contains a collection of statements that define what the method does.  
Note: In certain other languages, methods are referred to as procedures and functions. A method with a nonvoid return value type is called a function; a method with a void return value type is called a procedure.
Example:
Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:
view plainprint?
1. /** Return the max between two numbers */   2. public static int max(int num1, int num2) {   3.    int result;   4.    if (num1 > num2)   5.       result = num1;   6.    else   7.       result = num2;   8.  
9.    return result;    10. }    Calling a Method:
In creating a method, you give a definition of what the method is to do. To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.
When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached.
If the method returns a value, a call to the method is usually treated as a value. For example:
view plainprint?
1. int larger = max(30, 40);  
If the method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement:
view plainprint?
1. System.out.println("Welcome to Java!");  
Example:
Following is the example to demonstrate how to define a method and how to call it:
view plainprint?
1. public class TestMax {   2.    /** Main method */   3.    public static void main(String[] args) {   4.       int i = 5;   5.       int j = 2;   6.       int k = max(i, j);   7.       System.out.println("The maximum between " + i +   8.                     " and " + j + " is " + k);   9.    }   10.    11.    /** Return the max between two numbers */   12.    public static int max(int num1, int num2) {   13.       int result;   14.       if (num1 > num2)   15.          result = num1;   16.       else   17.          result = num2;   18.    19.       return result;    20.    }   21. }  
This would produce following result:
output: The maximum between 5 and 2 is 5
This program contains the main method and the max method. The main method is just like any other method except that it is invoked by the JVM.
The main method's header is always the same, like the one in this example, with the modifiers public and static, return value type void, method name main, and a parameter of the String[] type. String[] indicates that the parameter is an array of String.
The void Keyword:
This section shows how to declare and invoke a void method. Following example gives a program that declares a method namedprintGrade and invokes it to print the grade for a given score.
Example:
view plainprint?
1. public class TestVoidMethod {   2.    3.    public static void main(String[] args) {   4.       printGrade(78.5);   5.    }   6.    7.    public static void printGrade(double score) {   8.       if (score >= 90.0) {   9.          System.out.println('A');   10.       }   11.       else if (score >= 80.0) {   12.          System.out.println('B');   13.       }   14.       else if (score >= 70.0) {   15.          System.out.println('C');   16.       }   17.       else if (score >= 60.0) {   18.          System.out.println('D');   19.       }   20.       else {   21.          System.out.println('F');   22.       }   23.    }   24. }  
This would produce following result:
output: C
Here the printGrade method is a void method. It does not return any value. A call to a void method must be a statement. So, it is invoked as a statement in line 3 in the main method. This statement is like any Java statement terminated with a semicolon.
 Passing Parameters by Values:
When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method specification. This is known as parameter order association.
For example, the following method prints a message n times:
view plainprint?
1. public static void nPrintln(String message, int n) {   2.   for (int i = 0; i < n; i++)   3.     System.out.println(message);   4. }  
Here, you can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello", 3) statement passes the actual string parameter, "Hello", to the parameter, message; passes 3 to n; and prints "Hello" three times. However, the statement nPrintln(3, "Hello") would be wrong. When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. For simplicity, Java programmers often say passing an argument x to a parameter y, which actually means passing the value of x to y.  
Example:  
Following is a program that demonstrates the effect of passing by value. The program creates a method for swapping two variables. The swap method is invoked by passing two arguments. Interestingly, the values of the arguments are not changed after the method is invoked.
view plainprint?
1. public class TestPassByValue {   2.    3.    public static void main(String[] args) {   4.       int num1 = 1;   5.       int num2 = 2;   6.    7.       System.out.println("Before swap method, num1 is " +   8.                           num1 + " and num2 is " + num2);   9.    10.       // Invoke the swap method   11.       swap(num1, num2);   12.       System.out.println("After swap method, num1 is " +   13.                          num1 + " and num2 is " + num2);   14.    }   15.    /** Method to swap two variables */   16.    public static void swap(int n1, int n2) {   17.       System.out.println("\tInside the swap method");   18.       System.out.println("\t\tBefore swapping n1 is " + n1   19.                            + " n2 is " + n2);   20.       // Swap n1 with n2   21.       int temp = n1;   22.       n1 = n2;   23.       n2 = temp;  
24.    25.       System.out.println("\t\tAfter swapping n1 is " + n1   26.                            + " n2 is " + n2);   27.    }   28. }   This would produce following result:  
output: Before swap method, num1 is 1 and num2 is 2 Inside the swap method Before swapping n1 is 1 n2 is 2 After swapping n1 is 2 n2 is 1 After swap method, num1 is 1 and num2 is 2
Overloading Methods:  The max method that was used earlier works only with the int data type. But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another method with the same name but different parameters, as shown in the following code:
view plainprint?
1. public static double max(double num1, double num2) {   2.   if (num1 > num2)   3.     return num1;   4.   else   5.     return num2;   6. }   If you call max with int parameters, the max method that expects int parameters will be invoked; if you call max with double parameters, the max method that expects double parameters will be invoked. This is referred to as method overloading; that is, two methods have the same name but different parameter lists within one class. The Java compiler determines which method is used based on the method signature. Overloading methods can make programs clearer and more readable. Methods that perform closely related tasks should be given the same name. Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. Sometimes there are two or more possible matches for an invocation of a method due to similar method signature, so the compiler cannot determine the most specific match. This is referred to as ambiguous invocation.   The Scope of Variables:    The scope of a variable is the part of the program where the variable can be referenced. A variable defined inside a method is referred to as a local variable.
The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
A parameter is actually a local variable. The scope of a method parameter covers the entire method.
A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable as shown below:
 
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
Using Command-Line Arguments:
Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy.they are stored as strings in the String array passed to main( ).
Example:
The following program displays all of the command-line arguments that it is called with:
view plainprint?
1. public class CommandLine {   2.    3.    public static void main(String args[]){    4.       for(int i=0; i<args.length; i++){   5.          System.out.println("args[" + i + "]: " +   6.                                            args[i]);   7.       }   8.    }   9. }  
Try executing this program, as shown here: java CommandLine this is a command line 200 -100
This would produce following result:
output: args[0]: this args[1]: is
args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100
The Constructors:
A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used. Example:
Here is a simple example that uses a constructor:
view plainprint?
1. // A simple constructor.   2. class MyClass {   3.    int x;   4.       5.    // Following is the constructor   6.    MyClass() {   7.       x = 10;   8.    }   9. }   You would call constructor to initialize objects as follows:
view plainprint?
1. public class ConsDemo {   2.    3.    public static void main(String args[]) {   4.       MyClass t1 = new MyClass();   5.       MyClass t2 = new MyClass();   6.       System.out.println(t1.x + " " + t2.x);   7.    }   8. }  
Most often you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method:just declare them inside the parentheses after the constructor's name.
Here is a simple example that uses a constructor:
view plainprint?
1. // A simple constructor.   2. class MyClass {   3.    int x;   4.       5.    // Following is the constructor   6.    MyClass(int i ) {   7.       x = i;   8.    }   9. }   You would call constructor to initialize objects as follows:
view plainprint?
1. public class ConsDemo {   2.    3.    public static void main(String args[]) {   4.       MyClass t1 = new MyClass( 10 );   5.       MyClass t2 = new MyClass( 20 );   6.       System.out.println(t1.x + " " + t2.x);   7.    }   8. }  
This would produce following result:
output: 10 20
Variable Arguments(var-args):
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows:
view plainprint?
1. typeName... parameterName   In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it. Example:
view plainprint?
1. public class VarargsDemo {   2.    3.    public static void main(String args[]) {   4.       // Call method with variable args     5.    printMax(34, 3, 3, 2, 56.5);   6.       printMax(new double[]{1, 2, 3});   7.    }   8.    9.    public static void printMax( double... numbers) {   10.    if (numbers.length == 0) {   11.       System.out.println("No argument passed");   12.       return;   13.    }   14.  
15.    double result = numbers[0];   16.    17.    for (int i = 1; i <  numbers.length; i++)   18.       if (numbers[i] >  result)   19.       result = numbers[i];   20.       System.out.println("The max value is " + result);   21.    }   22. }  
This would produce following result:
output: The max value is 56.5 The max value is 3.0
Constructors in Java
Posted by Dinesh Rajput
A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a Cuboid class containing 2 constructors. (one default and one parameterized constructor).
view plainprint?
1. public class Cuboid {   2.    3.  int length;   4.  int breadth;   5.  int height;   6.  public int getVolume() {   7.   return (length * breadth * height);   8.  }   9.  Cuboid () {   10.   length = 10;   11.   breadth = 10;   12.   height = 10;   13.  }   14.  Cuboid (int l, int b, int h) {   15.   length = l;  
16.   breadth = b;   17.   height = h;   18.  }   19.  public static void main(String[] args) {   20.   Cuboid cubeObj1, cubeObj2;   21.   cubeObj1 = new Cuboid ();   22.   cubeObj2 = new Cuboid (10, 20, 30);   23.   System.out.println("Volume of Cuboid 1 is : " + cubeObj1.getVolume());   24.   System.out.println("Volume of Cuboid 1 is : " + cubeObj2.getVolume());   25.  }   26. }  
output: Volume of Cuboid 1 is : 1000 Volume of Cuboid 1 is : 6000
Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.
Java Overloaded Constructors:  
Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context
view plainprint?
1. public class Cuboid2 {   2.    3.  int length;   4.  int breadth;   5.  int height;   6.  public int getVolume() {   7.   return (length * breadth * height);   8.  }   9.  Cuboid2 () {   10.   this(10, 10);   11.   System.out.println("Finished with Default Constructor");  
12.  }   13.  Cuboid2 (int l, int b) {   14.   this(l, b, 10);   15.   System.out.println("Finished with Parameterized Constructor having 2 params");   16.  }   17.  Cuboid2 (int l, int b, int h) {   18.   length = l;   19.   breadth = b;   20.   height = h;   21.   System.out.println("Finished with Parameterized Constructor having 3 params");   22.  }   23.  public static void main(String[] args) {   24.   Cuboid2 cubeObj1, cubeObj2;   25.   cubeObj1 = new Cuboid2 ();   26.   cubeObj2 = new Cuboid2 (10, 20, 30);   27.   System.out.println("Volume of Cuboid2 1 is : " + cubeObj1.getVolume());   28.   System.out.println("Volume of Cuboid2 2 is : " + cubeObj2.getVolume());   29.  }   30. }  
output: Finished with Parameterized Constructor having 3 params Finished with Parameterized Constructor having 2 params Finished with Default Constructor Finished with Parameterized Constructor having 3 params Volume of Cube1 is : 1000 Volume of Cube2 is : 6000
Constructor Chaining:
Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class. The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor. The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.
view plainprint?
1. class Cube {   2.    3.  int length;   4.  int breadth;   5.  int height;   6.  public int getVolume() {   7.   return (length * breadth * height);  
8.  }   9.  Cube() {   10.   this(10, 10);   11.   System.out.println("Finished with Default Constructor of Cube");   12.  }   13.  Cube(int l, int b) {   14.   this(l, b, 10);   15.   System.out.println("Finished with Parameterized Constructor having   16.          2 params of Cube");   17.  }   18.  Cube(int l, int b, int h) {   19.   length = l;   20.   breadth = b;   21.   height = h;   22.   System.out.println("Finished with Parameterized Constructor having   23.          3 params of Cube");   24.  }   25. }   26.    27. public class SpecialCube extends Cube {   28.    29.  int weight;   30.  SpecialCube() {   31.   super();   32.   weight = 10;   33.  }   34.  SpecialCube(int l, int b) {   35.   this(l, b, 10);   36.   System.out.println("Finished with Parameterized Constructor having   37.          2 params of SpecialCube");   38.  }   39.  SpecialCube(int l, int b, int h) {   40.   super(l, b, h);   41.   weight = 20;   42.   System.out.println("Finished with Parameterized Constructor having   43.          3 params of SpecialCube");   44.  }   45.  public static void main(String[] args) {   46.   SpecialCube specialObj1 = new SpecialCube();   47.   SpecialCube specialObj2 = new SpecialCube(10, 20);   48.   System.out.println("Volume of SpecialCube1 is : "   49.     + specialObj1.getVolume());   50.   System.out.println("Weight of SpecialCube1 is : "   51.     + specialObj1.weight);   52.   System.out.println("Volume of SpecialCube2 is : "   53.     + specialObj2.getVolume());   54.   System.out.println("Weight of SpecialCube2 is : "   55.     + specialObj2.weight);   56.  }   57. }  
Output:
Finished with Parameterized Constructor having 3 params of SpecialCube Finished with Parameterized Constructor having 2 params of SpecialCube Volume of SpecialCube1 is : 1000 Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000 Weight of SpecialCube2 is : 20
The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors. if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.
Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.
Below is an example of a class demonstrating constructor chaining using explicit super() call. view plainprint?
1. class Cube {   2.    3.  int length;   4.  int breadth;   5.  int height;   6.  public int getVolume() {   7.   return (length * breadth * height);   8.  }   9.  Cube(int l, int b, int h) {   10.   length = l;   11.   breadth = b;   12.   height = h;   13.   System.out.println("Finished with Parameterized Constructor having   14.         3 params of Cube");   15.  }   16. }   17.    18. public class SpecialCube1 extends Cube {   19.    20.  int weight;   21.  SpecialCube1() {   22.   super(10, 20, 30); //Will Give a Compilation Error without this line   23.   weight = 10;   24.  }   25.  public static void main(String[] args) {   26.   SpecialCube1 specialObj1 = new SpecialCube1();   27.   System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume());   28.  }   29. }  
Output
Finished with Parameterized Constructor having 3 params of Cube Volume of SpecialCube1 is : 6000

String In Switch-Java 7 New Concept Posted by Dinesh Rajput
In this article we will discuss String in a switch statement; a new feature of Java 7. So for explaining this topic we take a short look at switch, string and some switch cases.
Introduction
In this article we will discuss String in a switch statement; a new feature of Java 7. So for explaining this topic we take a short look at switch, string and some switch cases.
Strings In Java
String are widely used in Java, they are a sequence of characters (sometimes called a character array). In Java, strings are objects.
Java provides the String class to create and manipulate strings.
How to Create a String
The general way to create a string is:
view plainprint?
1. String welcome="welcome to Java world";   Let's see an example to display the simple string "Welcome".
view plainprint?
1. public class StringEx   2. {   3.   public static void main(String args[])   4.   {   5.     char[] WelcomeArray = { 'W', 'e', 'l', 'c', 'o', 'm', 'e'};   6.     String WelcomeString = new String(WelcomeArray);    7.     System.out.println( WelcomeString );   8.   }      9. }   Output: Welcome
Switch case in Java
Switch statements reduce the workload, since without a switch we use if and else many times instead of the switch. Let's see a sample of if and else without a switch:
view plainprint?
1. if (x == 0) doSomework0();  
2. else if (x == 1) doSomework1();   3. else if (x == 2) doSomework2();   4. else if (x == 3) doSomework3();   5. else if (x == 4) doSomework4();   6. else doSomeworkElse();   Java has a shorthand for these types of multiple if statements, the switch-case statement. Here's how you'd write the above using a switch-case:
view plainprint?
1. switch (x)   2. {   3. case 0:    4. doSomework0();   5. break;   6. case 1:    7. doSomework1();   8. break;   9. case 2:    10. doSomework2();   11. break;   12. case 3:    13. doSomework3();   14. break;   15. case 4:    16. doSomework4();   17. break;   18. default:    19. doSomeworkElse();   20. }   In this example x must be a variable. x is compared to each case value. In case 0 the x must be compared with x==0 if it is then subsequent code will execute, similarly x will work according to other cases. If no cases are matched then the default action is triggered.  Purpose of switch
The if statement only evaluates a boolean value (only two possible values True and False). The switch statement will execute on many expressions based on an integer (including char) or enum value.  Switch keywords  switch
The Switch statement is followed by an expression in parenthesis, that is followed by the cases, all enclosed in braces. The Switch statement works using cases dependent on the value of expressions.  Case The case contain a colon and an integer constant.  default
If no case value matches the switch expression value then execution falls to the default clause. This is the equivalent of the last "else" for a series of if statements.
break
The break statement causes execution to exit to the statement after the end of the switch. If there is no break then execution flows thru into the next case. Flowing directly into the next case is nearly always an error.  Example
Let's see an example of how switch cases work!
view plainprint?
1. import java.io.*;   2. public class SwitchEx   3.   {   4.     public static void main(String args[]) throws Exception   5.       {   6.         int choice;   7.         // we make a month chart to test switch cases   8.         System.out.println("Enter 1 for January.");   9.         System.out.println("Enter 2 for Febrary");   10.         System.out.println("Enter 3 for March.");   11.         System.out.println("Enter 4 for April.");   12.         System.out.println("Enter 5 for May.");   13.         System.out.println("Enter 6 for June.");   14.         System.out.println("Enter 7 for July.");   15.         System.out.println("Enter 8 for August.");   16.         System.out.println("Enter 9 for September.");   17.         System.out.println("Enter 10 for October.");   18.         System.out.println("Enter 11 for November.");   19.         System.out.println("Enter 12 for December.");   20.         System.out.print("\n Whats your choice : ");   21.         BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ;   22.         try   23.           {   24.             choice=Integer.parseInt(in.readLine());   25.             switch(choice)   26.               {    27.                 case 1: System.out.println("January");   28.                 break;   29.                 case 2: System.out.println("Febrary");   30.                 break;   31.                 case 3: System.out.println("March");   32.                 break;   33.                 case 4: System.out.println("April");   34.                 break;   35.                 case 5: System.out.println("May");   36.                 break;   37.                 case 6: System.out.println("June");   38.                 break;   39.                 case 7: System.out.println("July");   40.                 break;   41.                 case 8: System.out.println("August");   42.                 break;   43.                 case 9: System.out.println("September");   44.                 break;   45.                 case 10: System.out.println("October");  
46.                 break;   47.                 case 11: System.out.println("November");   48.                 break;   49.                 case 12: System.out.println("December");   50.                 break;   51.                 default: System.out.println("Wrong entry!");   52.                 break;   53.                 }   54.            }   55.         catch(NumberFormatException ey)   56.           {   57.             System.out.println(ey.getMessage() + " enter only numeric value.");   58.             System.exit(0);   59.           }   60.       }   61.   }    Output:  
String in switch: Java 7 new feature
Switch statements work either with primitive types (e.g byte, short, long, int, etc) or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type.
The method of working on strings is crude. Java 7 improves the program by enhancing the Switch statement, that takes a String type as an argument.
 Let's see a previous example using a String in a switch this time. In this example a string is invoked in the switch statement which can't be end in prior versions of Java. So it might be helpful for reducing if-else statements.
view plainprint?
1. public class StringSwitchEx   2.   {   3.     public static int getMonthNumber(String month)   4.       {   5.         int monthNumber = 0;   6.         if (month == null)   7.           {   8.             return monthNumber;   9.           }   10.         switch (month.toLowerCase())   11.           {   12.             case "january":   13.             monthNumber = 1;   14.             break;   15.             case "february":   16.             monthNumber = 2;   17.             break;   18.             case "march":   19.             monthNumber = 3;   20.             break;   21.             case "april":   22.             monthNumber = 4;   23.             break;   24.             case "may":   25.             monthNumber = 5;   26.             break;   27.             case "june":   28.             monthNumber = 6;   29.             break;   30.             case "july":   31.             monthNumber = 7;   32.             break;   33.             case "august":   34.             monthNumber = 8;   35.             break;   36.             case "september":   37.             monthNumber = 9;   38.             break;   39.             case "october":   40.             monthNumber = 10;   41.             break;   42.             case "november":   43.             monthNumber = 11;   44.             break;   45.             case "december":   46.             monthNumber = 12;   47.             break;   48.             default:    49.             monthNumber = 0;   50.             break;   51.           }   52.         return monthNumber;   53.       }  
54.     public static void main(String[] args)   55.       {   56.         String month = "June";   57.         int returnedMonthNumber =StringSwitchEx.getMonthNumber(month);   58.         if (returnedMonthNumber == 0)   59.           {   60.             System.out.println("Invalid month");   61.           }   62.         else   63.           {   64.             System.out.print("The selected month no is : ");   65.             System.out.print(returnedMonthNumber);   66.           }   67.       }   68.   }   output:
Java Inheritance
Posted by Dinesh Rajput
In this section, you will learn about the inheritance with an example and its description.
 Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example,Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

                                    A hierarchy of bicycle classes.
 The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:
view plainprint?
1. class MountainBike extends Bicycle {   2.    3.     // new fields and methods defining    4.     // a mountain bike would go here   5.    6. }  
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.
IS-A Relationship: IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.
view plainprint?
1. public class Bicycle {  
2. }   3.    4. class MountainBike extends Bicycle {   5.    6.     // new fields and methods defining    7.     // a mountain bike would go here   8.    9. }   10.    11. public class RoadBike extends Bicycle {   12.    13.     // new fields and methods defining    14.     // a RoadBike would go here   15. }   16.    17. public class TandemBike extends Bicycle {   18.    19.     // new fields and methods defining    20.     // a TandemBike bike would go here   21. }  
Now based on the above example, In Object Oriented terms following are true:
 Bicycle is the superclass of MountainBike class.  Bicycle  is the superclass of RoadBike class.  RoadBike and MountainBike are sub classes of Bicycle class.  HondaShineBike is the subclass of both RoadBike and Bicycle  classes. Now if we consider the IS-A relationship we can say:
 MountainBike IS-A Bicycle  RoadBike IS-A Bicycle  HondaShineBike IS-A RoadBike  Hence : HondaShineBike IS-A Bicycle as well With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. Example: view plainprint?
1. public class Dog extends Mammal{   2.    3.    public static void main(String args[]){   4.    5.       Bicycle bicycle = new Bicycle();   6.       RoadBike roadBike = new RoadBike();   7.       HondaShine myBike = new HondaShine();   8.    9.       System.out.println(roadBike instanceof Bicycle);   10.       System.out.println(myBike instanceof RoadBike);   11.       System.out.println(myBike instanceof Bicycle);   12.    }   13. }  
This would produce following result:
Output: true true true
Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes. Example:
view plainprint?
1. public interface Bicycle{   2.    3. }   4.    5. public class RoadBike implements Bicycle{   6.    7. }   8.    9. public class HondaShine extends RoadBike{   10.    11. }    The instanceof Keyword:
Let us use the instanceof operator to check determine whether RoadBike is actually a Bicycle, and HondaShine is actually anBicycle
view plainprint?
1. public interface Bicycle{   2.    3. }   4.    5. public class RoadBike implements Bicycle{   6.    7. }   8.    9. public class HondaShine extends RoadBike{   10.    public static void main(String args[]){   11.    12.       RoadBike roadBike = new RoadBike();   13.       HondaShine myBike = new HondaShine();   14.    15.       System.out.println(roadBike instanceof Bicycle);   16.       System.out.println(myBike instanceof RoadBike);   17.       System.out.println(myBike instanceof Bicycle);   18.    }   19. }  
This would produce following result:
output: true true true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HASA certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
view plainprint?
1. public class Vehicle{}   2. public class Speed{}   3. public class Van extends Vehicle{   4.  private Speed sp;   5. }    This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.
In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve this, the Vanclass hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
Note: A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:
view plainprint?
1. public class HondaShine extends RoadBike, Bicycle{   2.    3. }  
Type of Inheritances: 1. Simple Inheritance When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance.
view plainprint?
1. class A {   2.   int x;   3.   int y;   4.   int get(int p, int q){   5.     x=p;  
6.     y=q;    7.     return(0);   8.   }   9.   void Show(){   10.    System.out.println(x);   11.   }   12. }   13.    14. class B extends A{   15.   public static void main(String args[]){   16.   A a = new A();   17.   a.get(5,6);   18.   a.Show();   19.   }   20.   void display(){   21.   System.out.println("B");   22.   }   23. }    2. Multilevel Inheritance It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can go up to any number of level.
view plainprint?
1. class A {   2.   int x;   3.   int y;   4.   int get(int p, int q){   5.   x=p; y=q; return(0);   6.   }   7.   void Show(){   8.   System.out.println(x);   9.   }   10. }   11. class B extends A{   12.   void Showb(){   13.   System.out.println("B");   14.   }   15. }   16.    17. class C extends B{   18.   void display(){   19.   System.out.println("C");   20.   }   21.   public static void main(String args[]){   22.   A a = new A();   23.   a.get(5,6);   24.   a.Show();   25.   }   26. }    3. Multiple Inheritance Note: Java does not support multiple Inheritance.
The mechanism of inheriting the features of more than one base class into a single class is known as
multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.  super keyword
The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions.
view plainprint?
1. class A{   2.   int a;   3.   float b;   4.   void Show(){   5.   System.out.println("b in super class:  " + b);   6.   }   7.    8. }   9.    10. class B extends A{   11.   int a;    12.   float b;   13.   B( int p, float q){   14.   a = p;   15.   super.b = q;   16.   }   17.   void Show(){   18.   super.Show();   19.   System.out.println("b in super class:  " + super.b);   20.   System.out.println("a in sub class:  " + a);   21.   }   22.    23.   public static void main(String[] args){   24.   B subobj = new B(1, 5);   25.   subobj.Show();   26.   }   27. }  
Output: C:\>java B b in super class: 5.0 b in super class: 5.0 a in sub class: 1
 Use of super to call super class constructor: The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command.
super(param-list);  
Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list. The following program illustrates the use of the super keyword to call a super class constructor.
view plainprint?
1. class A{   2.   int a;   3.   int b;   4.   int c;   5.   A(int p, int q, int r){   6.   a=p;   7.   b=q;   8.   c=r;   9.   }   10. }   11.      12.   class B extends A{   13.   int d;   14.   B(int l, int m, int n, int o){   15.   super(l,m,n);   16.   d=o;   17.   }   18.   void Show(){   19.   System.out.println("a = " + a);   20.   System.out.println("b = " + b);   21.   System.out.println("c = " + c);   22.   System.out.println("d = " + d);   23.   }   24.    25.   public static void main(String args[]){   26.   B b = new B(4,3,8,7);   27.   b.Show();   28.   }   29.   }  
Output: C:\>java B a = 4 b = 3 c = 8 d = 7
What is not possible using java class Inheritance? 1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed. 2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass. 3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass. 4. A subclass can extend only one superclass Overriding and Hiding Methods in Java Posted by Dinesh Rajput Instance Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations.  
Class Methods
If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclasshides the one in the superclass.
The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method:
view plainprint?
1. public class Animal {   2.     public static void testClassMethod() {   3.         System.out.println("The class" + " method in Animal.");   4.     }   5.     public void testInstanceMethod() {   6.         System.out.println("The instance " + " method in Animal.");  
7.     }   8. }  
The second class, a subclass of Animal, is called Cat:
view plainprint?
1. public class Cat extends Animal {   2.     public static void testClassMethod() {   3.         System.out.println("The class method" + " in Cat.");   4.     }   5.     public void testInstanceMethod() {   6.         System.out.println("The instance method" + " in Cat.");   7.     }   8.    9.     public static void main(String[] args) {   10.         Cat myCat = new Cat();   11.         Animal myAnimal = myCat;   12.         Animal.testClassMethod();   13.         myAnimal.testInstanceMethod();   14.     }   15. }  
The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance.
The output from this program is as follows:
output: The class method in Animal. The instance method in Cat.
As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.
Advantages method overriding:
 Method Overriding is used to provide specific implementation of a method that is already provided by its super class.  Method Overriding is used for Runtime Polymorphism
Rules for method overriding:  The argument list should be exactly the same as that of the overridden method.  The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.  The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.  Instance methods can be overridden only if they are inherited by the subclass.  A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.  If a method cannot be inherited then it cannot be overridden.  A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.  A subclass in a different package can only override the non-final methods declared public or protected.  An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.  Constructors cannot be overridden.
Modifiers The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.
Summary The following table summarizes what happens when you define a method with the same signature as a method in a superclass. Defining a Method with the Same Signature as a Superclass's Method
Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.  
Difference between method Overloading and Method Overriding. There are three basic differences between the method overloading and method overriding. They are as follows:
Method Overloading Method Overriding
1) Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2) method overlaoding is performed within a class.
Method overriding occurs in two classes that have IS-A relationship.
3) In case of method overloading parameter must be different.
In case of method overriding parameter must be same.
Polymorphism in Java
Posted by Dinesh Rajput
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
Polymorphism can be demonstrated with a minor modification to the Bicycle class. For example, a printDescription method could be added to the class that displays all the data currently stored in an instance.
view plainprint?
1. public void printDescription(){   2.     System.out.println("\nBike is " + "in gear " + this.gear   3.         + " with a cadence of " + this.cadence +   4.         " and travelling at a speed of " + this.speed + ". ");   5. }  
To demonstrate polymorphic features in the Java language, extend the Bicycle class with a MountainBike and a RoadBikeclass. For MountainBike, add a field for suspension, which is a String value that indicates if the bike has a front shock absorber, Front. Or, the bike has a front and back shock absorber, Dual. Here is the updated class:
view plainprint?
1. public class MountainBike extends Bicycle {   2.     private String suspension;   3.    4.     public MountainBike(   5.                int startCadence,  
6.                int startSpeed,   7.                int startGear,   8.                String suspensionType){   9.         super(startCadence,   10.               startSpeed,   11.               startGear);   12.         this.setSuspension(suspensionType);   13.     }   14.    15.     public String getSuspension(){   16.       return this.suspension;   17.     }   18.    19.     public void setSuspension(String suspensionType) {   20.         this.suspension = suspensionType;   21.     }   22.    23.     public void printDescription() {   24.         super.printDescription();   25.         System.out.println("The " + "MountainBike has a" +   26.             getSuspension() + " suspension.");   27.     }   28. }    
Note the overridden printDescription method. In addition to the information provided before, additional data about the suspension is included to the output.
Next, create the RoadBike class. Because road or racing bikes have skinny tires, add an attribute to track the tire width. Here is the RoadBike class:
view plainprint?
1. public class RoadBike extends Bicycle{   2.     // In millimeters (mm)   3.     private int tireWidth;   4.    5.     public RoadBike(int startCadence,   6.                     int startSpeed,   7.                     int startGear,   8.                     int newTireWidth){   9.         super(startCadence,   10.               startSpeed,   11.               startGear);   12.         this.setTireWidth(newTireWidth);   13.     }   14.    15.     public int getTireWidth(){   16.       return this.tireWidth;   17.     }   18.    19.     public void setTireWidth(int newTireWidth){   20.         this.tireWidth = newTireWidth;   21.     }   22.    23.     public void printDescription(){   24.         super.printDescription();   25.         System.out.println("The RoadBike" + " has " + getTireWidth() +   26.             " MM tires.");   27.     }   28. }  
 Note that once again, the printDescription method has been overridden. This time, information about the tire width is displayed.
To summarize, there are three classes: Bicycle, MountainBike, and RoadBike. The two subclasses override theprintDescription method and print unique information.
Here is a test program that creates three Bicycle variables. Each variable is assigned to one of the three bicycle classes. Each variable is then printed.
view plainprint?
1. public class TestBikes {   2.   public static void main(String[] args){   3.     Bicycle bike01, bike02, bike03;   4.    5.     bike01 = new Bicycle(20, 10, 1);   6.     bike02 = new MountainBike(20, 10, 5, "Dual");   7.     bike03 = new RoadBike(40, 20, 8, 23);   8.    9.     bike01.printDescription();   10.     bike02.printDescription();   11.     bike03.printDescription();   12.   }   13. }  
The following is the output from the test program:
output: Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10.  
Bike is in gear 5 with a cadence of 20 and travelling at a speed of 10.  The MountainBike has a Dual suspension.
Bike is in gear 8 with a cadence of 40 and travelling at a speed of 20.  The RoadBike has 23 MM tires.
Types of Polymorphism in Java: There are following two type polymorphism in java.
1. Run Time Polymorphism(Method overriding) 2. Compile Time Polymorphism(Method overloading) Abstraction in Java Posted by Dinesh Rajput
Abstraction can be defined as the process of hiding the unwanted details and exposing only the essential features of a particular object or concept. The concept of abstraction is used by classes and lists of attributes are defined in them like cost, size and weight, and methods that operate on their attributes. Abstraction is also achieved through composition.
For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.  
What is abstract class in Java?
Use the abstract keyword to declare a class abstract. An abstract class is something which is incomplete and you can not create instance of abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended. By the way Java has concept of abstract classes, abstract method but a variable can not be abstract in Java.  Abstract Class Examples in Java - Example 1:
view plainprint?
1. abstract class Shape{   2.     abstract void draw();   3. }   4.    5. class Rectangle extends Shape{   6.    void draw(){   7.      System.out.println("Drawing Rectangle");   8.    }   9. }   10.    11. class Traingle extends Shape{   12.    void draw(){   13.      System.out.println("Drawing Traingle");   14.    }   15. }   16.    17. class AbstractDemo{   18.    public static void main(String args[]){     19.        Shape s1 = new Rectangle();   20.        s1.draw();   21.        s1 = new Traingle();   22.        s1.draw();   23.     }   24. }  
Output: Drawing Rectangle Drawing Traingle.
Example 2:
A Car has Engine, wheels and many other parts. When we write all the properties of the Car, Engine, and wheel in a single class, it would look this way:
view plainprint?
1. public class Car {   2.      3.     int price;   4.     String name;   5.     String color;   6.    7.     int engineCapacity;   8.     int engineHorsePower;   9.        10.     String wheelName;   11.     int wheelPrice;   12.        13.     void move(){   14.     //move forward     15.     }   16.    17.     void rotate(){   18.       //Wheels method   19.     }   20.        21.     void internalCombustion(){   22.       //Engine Method   23.     }   24.        25. }  
In the above example, the attributes of wheel and engine are added to the Car type. As per the programming, this will not create any kind of issues. But when it comes to maintenance of the application, this becomes more complex.  Abstraction has three advantages:
1. By using abstraction, we can separate the things that can be grouped to another type. 2. Frequently changing properties and methods can be grouped to a separate type so that the main type need not under go changes. This adds strength to the OOAD principle -"Code should be open for Extension but closed for Modification". 3. Simplifies the representation of the domain models. Applying the abstraction with composition,  the above example can be modified as given below:
view plainprint?
1. public class Car {   2.      3.     Engine engine = new Engine();   4.     Wheel wheel = new Wheel();   5.        6.     int price;   7.     String name;  
8.     String color;   9.         10.        11.     void move(){   12.     //move forward     13.     }   14.   }   view plainprint?
1. public class Engine {   2.   int engineCapacity;   3.   int engineHorsePower;   4.      5.      6.   void internalCombustion(){   7.     //Engine Method   8.   }   9.      10. }   view plainprint?
1. public class Wheel {   2.   String wheelName;   3.   int wheelPrice;   4.      5.   void rotate(){   6.     //Wheels method   7.   }   8.      9. }  
You can see that the attributes and methods related to the Engine and Wheel are moved to the respective classes.
Engine and Wheel are referred from the Car type. When ever an instance of Car is created, both Engine and Wheel will be available for the Car and when there are changes to these Types(Engine and Wheel), changes will only be confined to these classes and will not affect the Car class.
Abstract Method : Abstract methods are those which need to be implemented in subclass / child class. Abstract methods are only defined insuperclass / parent class but with no body.
 Syntax of Abstract Method:
view plainprint?
1. abstract class clsName   2. {   3. // Variable declaration   4.    5. // Constructor   6.    7. // Method   8. abstract rtype mthName(params);   9. }  
clsName is a valid identifier in java. It is a class name. abstract is a keyword to define that method an abstract method. rtype is return type of a method. mthName is a method name and valid java identifier.
Example of an Abstract Method:
view plainprint?
1. abstract class Shape   2. {   3. public static float pi = 3.142;   4. protected float height;   5. protected float width;   6.    7. abstract float area();   8. }   9.    10. class Square extends Shape   11. {   12. Square(float h, float w)   13. {   14. height = h;   15. width = w;   16. }   17.    18. float area()   19. {   20. return height * width;   21. }   22. }   23.    24. class Rectangle extends Shape   25. {   26. Rectangle(float h, float w)   27. {   28. height = h;   29. width = w;   30. }   31.    32. float area()   33. {   34. return height * width;   35. }  
36. }   37.    38. class Circle extends Shape   39. {   40. float radius;   41.    42. Circle(float r)   43. {   44. radius = r;   45. }   46.    47. float area()   48. {   49. return Shape.pi * radius *radius;   50. }   51. }   52.    53. class AbstractMethodDemo   54. {   55. public static void main(String args[])   56. {   57. Square sObj = new Square(5,5);   58. Rectangle rObj = new Rectangle(5,7);   59. Circle cObj = new Circle(2);   60.    61. System.out.println("Area of square : " + sObj.area());   62. System.out.println("Area of rectangle : " + rObj.area());   63. System.out.println("Area of circle : " + cObj.area());   64. }   65. }  
Output: Area of square : 25 Area of rectangle : 35 Area of circle : 12.57
Declaring a method as abstract has two results:
 The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.  Any child class must either override the abstract method or declare itself abstract. A child class that inherits an abstract method must override it. If they do not, they must be abstract,and any of their children must override it. Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.
Encapsulation in Java
Posted by Dinesh Rajput
This tutorial describe concept of Encapsulation. It is one of OOPs concept.
Encapsulation is a way of wrapping up data and methods into a single unit. Encapsulation puts the data safe from the outside world by binding the data and codes into single unit This is best way to protect the data from outside the world.
Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. this can be better explained with a simple example of encapsulation in Java.  
Advantage of Encapsulation in Java and OOPS
Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:
1. Encapsulated Code is more flexible and easy to change with new requirements.
2. Encapsulation in Java makes unit testing easy.
3. Encapsulation in Java allows you to control who can access what.
4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment.
5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other part of code.
Example of Encapsulation  :
Example 1:
view plainprint?
1. public class Person{   2. private String name;   3. private int age;   4. private double height;   5. private double weight;  
6.    7. public void setName(String name){   8. this.name=name;   9. }   10.    11. public String getName(){   12. return name;   13. }   14. public void setAge(int age){   15. this.age=age;   16. }   17. public int getAge(){   18. return age;   19. }   20. public void setHeight(double height){   21. this.height=height;   22. }   23. public double getHeight(){   24. return name;   25. }   26. public void setWeight(double weight){   27. this.weight=weight;   28. }   29. public double getWeight(){   30. return weight;   31. }  
As you can see in the above class all of its properties are private-meaning that they cannot be accessed from outside the class- and the only way to interact with class properties is through its public methods.  
Example 2: I have create a class Car which has two methods:
1. move(). 2. internalCombustion() The move method depends on internalCombustion() method. But an Employee needs only move method and need not be aware of internalCombustion behavior. So, the internalCombustion behavior can be declared private so that it can be only visible to the members inside the class.
 
Summary:
Encapsulation is a primary fundamental principle in Object oriented programming. It is used to enforce the security to restrict the visibility of the members to other components. Interfaces in Java Posted by Dinesh Rajput
An interface is a collection of methods that have no implementation - they are just created, but have no functionality. An interface is a bit like a class, except you can only declare methods and variables in the interface. You cannot actually implement the methods.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
Declaring an interface: While Java provides interfaces for you to use, you can also create your own.  An interface is declared with the interface keyword.
 Syntax:
view plainprint?
1. interface nameOfInterface{   2. //methods for interface here;   3. }  
To use a interface in your class , append the keyword “implements” after your class name followed by the interface name
view plainprint?
1. public class JavaInterfaceExample implements IntExample  
Java Interface Example :
view plainprint?
1. interface IntExample{   2.    3. public void sayHello();   4. }   5. }   6.    7. public class JavaInterfaceExample implements IntExample{   8. public void sayHello(){   9. System.out.println("Hello Visitor !");   10. }   11. public static void main(String args[]){   12.    13. JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();   14. javaInterfaceExample.sayHello();   15. }   16. }  
Output: Hello Visitor !
Points to note:
 The class which implements the interface needs to provide functionality for the methods declared in the interface  All methods in an interface are implicitly public and abstract  An interface cannot be instantiated  An interface reference can point to objects of its implementing classes  An interface can extend from one or many interfaces. A class can extend only one class but implement any number of interfaces
Example:
view plainprint?
1. interface RidableAnimal extends Animal, Vehicle    Class vs Interface: An interface is similar to a class in the following ways:
 An interface can contain any number of methods.  An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.  The bytecode of an interface appears in a .class file.  Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. However, an interface is different from a class in several ways, including:
 You cannot instantiate an interface.  An interface does not contain any constructors.  All of the methods in an interface are abstract.  An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.  An interface is not extended by a class; it is implemented by a class.  An interface can extend multiple interfaces.
Rules for Implementing Interfaces: When overriding methods defined in interfaces there are several rules to be followed:
 Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.  The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.  An implementation class itself can be abstract and if so interface methods need not be implemented. When implementation interfaces there are several rules:
 A class can implement more than one interface at a time.  A class can extend only one class, but implement many interface.  An interface can extend another interface, similarly to the way that a class can extend another class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
view plainprint?
1. //Filename: Sports.java   2. public interface Sports   3. {   4.    public void setHomeTeam(String name);   5.    public void setVisitingTeam(String name);   6. }   7.    8. //Filename: Football.java   9. public interface Football extends Sports   10. {   11.    public void homeTeamScored(int points);   12.    public void visitingTeamScored(int points);   13.    public void endOfQuarter(int quarter);   14. }   15.    16. //Filename: Hockey.java   17. public interface Hockey extends Sports   18. {   19.    public void homeGoalScored();   20.    public void visitingGoalScored();   21.    public void endOfPeriod(int period);   22.    public void overtimePeriod(int ot);   23. }  
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
view plainprint?
1. public interface Hockey extends Sports, Event    Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, theMouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as:
view plainprint?
1. package java.util;   2. public interface EventListener   3. {}  
An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces:

Packages in Java
Posted by Dinesh Rajput
A package is a group of similar types of classs, interfaces and sub-packages. Package can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. In this page, we will have the detailed learning of creating user-defined packages.  
Advantage of Package:
 Package is used to categorize the classes and interfaces so that they can be easily maintained.  Package provids access protection.  Package removes naming collision. Some of the existing packages in Java are:  java.lang - bundles the fundamental classes  java.io - classes for input , output functions are bundled in this package Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes, interfaces, enumerations, annotations are related. Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classed.
 
Creating a package: When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.  
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.
Example: Let us look at an example that creates a package called animals. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes, interfaces. Put an interface in the package animals:
view plainprint?
1. /* File name : Animal.java */   2. package animals;   3.    4. interface Animal {   5.    public void eat();   6.    public void travel();   7. }  
Now put an implementation in the same package animals:
view plainprint?
1. package animals;   2.    3. /* File name : MammalInt.java */   4. public class MammalInt implements Animal{   5.    6.    public void eat(){   7.       System.out.println("Mammal eats");   8.    }   9.    10.    public void travel(){   11.       System.out.println("Mammal travels");   12.    }    13.    14.    public int noOfLegs(){   15.       return 0;   16.    }   17.    18.    public static void main(String args[]){   19.       MammalInt m = new MammalInt();   20.       m.eat();   21.       m.travel();   22.    }   23. }  
 Now you compile these two files and put them in a sub-directory called animals and try to run as follows:
$ mkdir animals $ cp Animal.class MammalInt.class animals $ java animals/MammalInt Mammal eats Mammal travels
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*; 2. import package.classname; 3. fully qualified name. If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
Example of package that import the packagename.*
view plainprint?
1. //save by A.java   2.    3. package pack;   4. public class A{   5.   public void msg(){System.out.println("Hello");}   6. }   view plainprint?
1. //save by B.java   2.    3. package mypack;   4. import pack.*;   5.    6. class B{   7.   public static void main(String args[]){   8.    A obj = new A();   9.    obj.msg();   10.   }   11. }  
Output: Hello
 Note: If you import package.classname then only declared class of this package will be accessible but not subpackages.
Example of package by import package.classname
view plainprint?
1. //save by A.java   2.    3. package pack;   4. public class A{   5.   public void msg(){System.out.println("Hello");}   6. }  
view plainprint?
1. //save by B.java   2.    3. package mypack;   4. import pack.A;   5.    6. class B{   7.   public static void main(String args[]){   8.    A obj = new A();   9.    obj.msg();   10.   }   11. }  
Output: Hello
Note: If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
Example of package by import fully qualified name
view plainprint?
1. //save by A.java   2.    3. package pack;   4. public class A{   5.   public void msg(){System.out.println("Hello");}   6. }  
view plainprint?
1. //save by B.java   2.    3. package mypack;   4. class B{  
5.   public static void main(String args[]){   6.    pack.A obj = new pack.A();//using fully qualified name   7.    obj.msg();   8.   }   9. }  
Output: Hello
Note: Sequence of the program must be package then import then class.  
Subpackage Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
view plainprint?
1. // File Name: Dell.java   2.    3. package com.apple.computers;   4. public class Dell{   5.          6. }   7. class Ups{   8.          9. }  
Now compile this file as follows using -d option:
 $javac -d . Dell.java
This would put compiled files as follows:
.\com\apple\computers\Dell.class .\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
view plainprint?
1. import com.apple.computers.*;  
Note: If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.  
Set CLASSPATH System Variable: To display the current CLASSPATH variable, use the following commands in Windows and Unix (Bourne shell):
 In Windows -> C:\> set CLASSPATH  In Unix -> % echo $CLASSPATH To delete the current contents of the CLASSPATH variable, use :  In Windows -> C:\> set CLASSPATH=  In Unix -> % unset CLASSPATH; export CLASSPATH To set the CLASSPATH variable:   In Windows -> set CLASSPATH=C:\users\jack\java\classes  In Unix -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH static keyword in Java Posted by Dinesh Rajput
The static is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise the static keyword indicates the following :  
  The static keyword is applicable to an inner class (a class defined within another class), method or field.   In java language, a static keyword is used with a class (inner) needed to be instantiated, even this may be referenced by some other class indicating as if it - were a top−level class in the class hierarchy.  A static keyword can also be used with a  field of a class, such a field exists across all the instances of that particular class.  The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class.
The static can be:
1. variable (also known as class variable) 2. method (also known as class method) 3. block static variable  It is a variable which belongs to the class and not to object(instance)  Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables  A single copy to be shared by all instances of the class  A static variable can be accessed directly by the class name and doesn’t need any object Syntax : <class-name>.<variable-name> Advantage of static variable: Understanding problem without static variable-
view plainprint?
1. class Employee{   2.      int empId;   3.      String empName;   4.      String compName="DAV JavaServices Ltd.";   5. }  
Suppose there are 3000 employees in our company, now all instance data members will get memory each time when object is created.All employees have its unique empId and empName so instance data member is good. Here, company refers to the common property of all objects. If we make it static,this field will get memory only once.
Note:static field is shared by all objects.
Example of static variable:
view plainprint?
1. //Program of static variable   2.    3. class Employee{   4.    int empId;   5.    String empName;   6.    static String compName = "DAV JavaServices Ltd.";   7.       8.    Employee(int empId, String empName){   9.       this.empId = empId;   10.       this.empName= empName;   11.    }   12.  void display (){   13.    14.    System.out.println(empId+" "+empName+" "+compName );   15.   }   16.    17.  public static void main(String args[]){   18.      Employee employee1 = new Employee(111,"Dinesh");  
19.      Employee employee2 = new Employee(222,"Sweety");   20.     21.     employee1.display();   22.     employee2.display();   23.  }   24. }  
Output:  111 Dinesh DAV JavaServices Ltd. 222 Sweety DAV JavaServices Ltd.  
static method  It is a method which belongs to the class and not to the object(instance)  A static method can access only static data. It can not access non-static data (instance variables)  A static method can call only other static methods and can not call a non-static method from it.  A static method can be accessed directly by the class name and doesn’t need any object  Syntax : <class-name>.<method-name>  A static method cannot refer to “this” or “super” keywords in anyway 
 
Example of static method: view plainprint?
1. //Program of changing the common property of all objects(static field).   2.    3. class Employee{   4.      int empId;   5.      String empName;   6.      static String compName = "DAV JavaServices Ltd.";   7.         8.      static void change(){   9.         compName = "DOJ Ltd";   10.      }   11.    12.      Student(int empId, String empName){   13.         this.empId = empId;   14.         this.empName = empName;   15.      }   16.    17.      void display (){   18.    19.      System.out.println(rollno+" "+name+" "+college);   20.      }   21.    22.     public static void main(String args[]){   23.         Employee.change();   24.    25.        Employee employee1 = new Employee(111,"Dinesh");   26.        Employee employee2 = new Employee(222,"Sweety");   27.        Employee employee3 = new Employee(333,"Anamika");   28.    29.        employee1.display();   30.        employee2.display();   31.        employee3.display();   32.     }   33. }  
Output: 111 Dinesh DOJ Ltd. 222 Sweety DOJ Ltd. 333 Anamika DOJ Ltd.
view plainprint?
1. //Program of accessing non-static data member directly from static method main   2.    3. class A{   4.  int a=40;//non static   5.     6.  public static void main(String args[]){   7.   System.out.println(a);   8.  }   9. }      
Output: Compile Time Error
Que)why main method is static? Ans) because object is not required to call static method if it were non-static method, jvm creates object first then call main()method that will lead the problem of extra memory allocation.
static block:
 Is used to initialize the static data member.  It is executed before main method at the time of classloading.  A static block helps to initialize the static data members, just like constructors help to initialize instance members Example of static block
view plainprint?
1. /Program of static block   2.    3. class A{   4.    5.   static{   6.       System.out.println("static block is invoked");   7.    }   8.    9.   public static void main(String args[]){   10.    System.out.println("Hello main");   11.   }   12. }  
Output: static block is invoked Hello main  
Can we execute a program without main() method? -- Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
view plainprint?
1. //Program of executing a program without main() method   2.    3. class A{   4.   static{   5.   System.out.println("static block is invoked");   6.   System.exit(0);   7.   }  
8. }  
Output:
static block is invoked (if not JDK7)  
final keyword in Java
Posted by Dinesh Rajput
The final is a keyword. This is similar to const keyword in other languages. This keyword may not be used as identifiers i.e. you cannot declare a variable or class with this name in your Java program.
The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:
1. variable 2. method 3. class
The final keyword can be applied with the variables, that have no value it is called blank final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1. final variable: A final variable can only once assigned a value. This value cannot be changed latter. If final variable used in class then it must assigned a value in class constructor. Attempting to change the value of final variable/field will generate error.  
Unlike the constant value, the value of a final variable is not necessarily known at compile time. Final variable comes in mostly two important situations: to prevent accidental changes to method parameters, and with variables accessed by anonymous classes.
The syntax of declaring a final type variable is:
view plainprint?
1. public final double radius = 126.45;   2. public final int PI = 3.145;  
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because finalvariable once assigned a value can never be changed.
view plainprint?
1. class Bike{   2.   final int speedlimit=90;//final variable   3.      4.   void run(){   5.    speedlimit=400;   6.   }   7.    8.   public static void main(String args[]){   9.   Bike obj=new  Bike();   10.   obj.run();   11.   }   12. }    
Output:Compile Time Error
2. final method: A final method cannot be overridden by subclasses and not be hidden. This technology prevents unexpected behavior from a subclass for altering a method that may be crucial to the function of the class.
Note: private and static methods are always implicitly final in Java, since they cannot be overridden.
The syntax of declaring a final type method is:
view plainprint?
1. public class MyFinalClass {   2.    3.   public final void myFinalMethod()   4.    {    5.     //code here   6.   }   7. }      
Example of final method:
view plainprint?
1. class Bike{   2.   final void run()   3.    {   4.     System.out.println("running");   5.    }   6. }   7.       8. class Honda extends Bike{   9.    void run()   10.     {   11.        System.out.println("running safely below 100kmph");   12.     }   13.       14.    public static void main(String args[]){   15.      Honda honda = new Honda();   16.      honda.run();  
17.    }   18. }      
Output:Compile Time Error
3. final class: A final class cannot be extended. A final class implicitly has all the methods declared as final, but not necessarily the data members.
The syntax of declaring a final type method is:
view plainprint?
1. public final class MyFinalClass {   2.    3. //code here   4.    5. }    
Example of final class:
view plainprint?
1. final class Bike{}   2.     3.  class Honda extends Bike{   4.    void run(){   5.    System.out.println("running safely below 100kmph");   6.    }   7.       8.    public static void main(String args[]){   9.       Honda honda= new Honda();   10.       honda.run();   11.    }   12. }    
Output:Compile Time Error
Is final method inherited? Yes, final method is inherited but you cannot override it. For Example:
view plainprint?
1. class Bike{   2.   final void run(){   3.     System.out.println("running...");}   4.   }  
5. class Honda extends Bike{   6.       7.    public static void main(String args[]){   8.     new Honda().run();   9.    }   10. }    
Output:running...
What is blank final variable? A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor.
view plainprint?
1. class Employee{   2. int empId;   3. String empName;   4. final String PAN_CARD_NUMBER;   5. ...   6. }    Can we initialize blank final variable? Yes, but only in constructor. For example:
view plainprint?
1. class Employee{   2. int empId;   3. String empName;   4. final String PAN_CARD_NUMBER;   5. Employee(){   6.   PAN_CARD_NUMBER = "CSA122ASS";   7.   System.out.println(PAN_CARD_NUMBER);   8.   }   9.    10.   public Static void main(String args[]){   11.     new Employee();   12.  }   13. }    
Output:CSA122ASS
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
view plainprint?
1. class A{   2.   static final int data;//static blank final variable   3.      4.   static{    5.    data=50;   6.   }   7.    8.   public Static void main(String args[]){   9.     System.out.println(A.data);   10.  }   11. }    What is final parameter? If you declare any parameter as final, you cannot change the value of it.
view plainprint?
1. class Bike{   2.   int cube(final int n){   3.    n=n+2;//can't be changed as n is final   4.    n*n*n;   5.   }   6.    7.    8.   public Static void main(String args[]){   9.     Bike b=new Bike();   10.     b.cube(5);   11.  }   12. }    
Output:Compile Time Error
 A java variable can be declared using the keyword final. Then the final variable can be assigned only once.  A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialize it.  Java classes declared as final cannot be extended. Restricting inheritance!  Methods declared as final cannot be overridden. In methods private is equal to final, but in variables it is not.  final parameters – values of the parameters cannot be changed after initialization. Do a small java exercise to find out the implications of final parameters in method overriding.  Java local classes can only reference local variables and parameters that are declared as final.  A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.
this keyword in Java
Posted by Dinesh Rajput
There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object. Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Usage of this keyword Here is given the 6 usage of this keyword.
1. this keyword can be used to refer current class instance variable. 2. this() can be used to invoke current class constructor. 3. this keyword can be used to invoke current class method (implicitly) 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this keyword can also be used to return the current class instance. Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this view plainprint?
1. public class Point {   2.     public int x ;   3.     public int y ;   4.            5.     //constructor   6.     public Point(int x, int y) {   7.         x = x;   8.         y = y;   9.     }   10.    void display(){   11.       System.out.println(x+" :: "+y);   12.    }   13.    public static void main(String args[]){  
14.     Point s1 = new Point (111,222);   15.     Point s2 = new Point (333,444);   16.     s1.display();   17.     s2.display();   18.     }   19. }  
output: 0 :: 0 0 :: 0
In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable.  
but it could have been written like this:
view plainprint?
1. public class Point {   2.     public int x = 0;   3.     public int y = 0;   4.            5.     //constructor   6.     public Point(int x, int y) {   7.         this.x = x;   8.         this.y = y;   9.     }   10.    void display(){   11.       System.out.println(x+" :: "+y);   12.    }   13.    public static void main(String args[]){   14.     Point s1 = new Point (111,222);   15.     Point s2 = new Point (333,444);   16.     s1.display();   17.     s2.display();   18.     }   19. }  
output: 111 :: 222 333 :: 444
 
Using this with a Constructor
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.
view plainprint?
1. public class Rectangle {   2.     private int x, y;   3.     private int width, height;   4.            5.     public Rectangle() {   6.         this(0, 0, 0, 0);   7.     }   8.     public Rectangle(int width, int height) {   9.         this(0, 0, width, height);   10.     }   11.     public Rectangle(int x, int y, int width, int height) {   12.         this.x = x;   13.         this.y = y;   14.         this.width = width;   15.         this.height = height;   16.     }   17.     ...   18. }   This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the
type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.  Where to use this() constructor call? The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of thiskeyword.
view plainprint?
1. class Employee{   2.     int id;   3.     String name;   4.     String city;   5.        6.     Employee(int id,String name){   7.     this.id = id;   8.     this.name = name;   9.     }   10.     Employee(int id,String name,String city){   11.     this(id,name);//now no need to initialize id and name   12.     this.city=city;   13.     }   14.     void display(){   15.      System.out.println(id+" "+name+" "+city);   16.     }   17.        18.     public static void main(String args[]){   19.     Employee e1 = new Employee(222,"Dinesh");   20.     Employee e2 = new Employee(555,"Anamika","Noida");   21.     e1.display();   22.     e2.display();   23.    }   24. }  
Output: 222 Dinesh null 555 Anamika Noida
Note: Call to this() must be the first statement.
view plainprint?
1. class Employee{   2.     int id;   3.     String name;   4.     Employee(){   5.      System.out.println("default constructor is invoked");   6.     }   7.        8.     Employee(int id,String name){   9.     id = id;   10.     name = name;   11.     this ();//must be the first statement   12.     }  
13.     void display(){   14.      System.out.println(id+" "+name);   15.    }   16.        17.     public static void main(String args[]){   18.     Employee e1 = new Employee(222,"Dinesh");   19.     Employee e2 = new Employee(555,"Anamika");   20.     e1.display();   21.     e2.display();   22.    }   23. }   Output: Compile Time Error
super keyword in Java
Posted by Dinesh Rajput
The super is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise the super keyword indicates the following :  
1. The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used. 2. The super keyword as a standalone statement is used to call the constructor of the superclass in the base class. If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keywordsuper. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass: view plainprint?
1. public class Superclass {   2.    3.     public void printMethod() {   4.         System.out.println("Printed in Superclass.");   5.     }   6. }  
Here is a subclass, called Subclass, that overrides printMethod():
view plainprint?
1. public class Subclass extends Superclass {   2.    3.     // overrides printMethod in Superclass   4.     public void printMethod() {   5.         super.printMethod();   6.         System.out.println("Printed in Subclass");   7.     }   8.     public static void main(String[] args) {   9.         Subclass s = new Subclass();   10.         s.printMethod();       11.     }  
12. }  
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
Output: Printed in Superclass. Printed in Subclass
super is used to invoke parent class constructor The super keyword can also be used to invoke the parent class constructor as given below:
view plainprint?
1. class Vehicle{   2.   Vehicle(){   3.     System.out.println("Vehicle is created");   4.    }   5. }   6.    7. class Bike extends Vehicle{   8.   Bike(){   9.    super();//will invoke parent class constructor   10.    System.out.println("Bike is created");   11.   }   12.   public static void main(String args[]){   13.    Bike b=new Bike();   14.          15. }   16. }  
Output: Vehicle is created Bike is created
Note:super() is added in each class constructor automatically by compiler.
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will providesuper() as the first statement of the constructor.
 
Another example of super keyword where super() is provided by the compiler implicitly.
view plainprint?
1. class Vehicle{   2.   Vehicle(){   3.    System.out.println("Vehicle is created");   4.   }   5. }   6.    7. class Bike extends Vehicle{   8.   int speed;   9.   Bike(int speed){   10.     this.speed=speed;   11.     System.out.println(speed);   12.   }   13.   public static void main(String args[]){   14.    Bike b=new Bike(10);   15.          16. }   17. }  
Output: Vehicle is created 10  
Instance initializer block in Java Posted by Dinesh Rajput
Apart from methods and constructors, Initialization Blocks are the third place in a Java Program where operations can be performed. Initialization Blocks come in two flavors:
1. Static Initialization Blocks: Runs first when the class is first loaded. Declared by using the keyword “Static” 2. Instance Initialization Blocks: Runs every time when the instance of the class is created. Code Snippet:
view plainprint?
1. class InitDemo   2. {   3.     static int y;   4.     int x;   5.     //Static Initialization Block   6.     static   7.     {   8.        y=10;   9.     }   10.    // Instance Initialization Block   11.    {   12.       x=20;   13.    }   14. }   Instance initialization block code runs right after the call to super() in a constructor, in other words, after all super constructors have run. The order in which initialization blocks appear in a class matters. If a class has more than one they all run in the order they appear in the class file.
Some rules to remember:
 Initialization blocks execute in the order they appear.  Static Initialization blocks run once when the class is first loaded.  Instance Initialization blocks run every time a class instance is created.  Instance Initialization blocks run after the constructor’s call to super().
Instance initializer block: Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.  Why use instance initializer block? Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc.
view plainprint?
1. //Program of instance initializer block that initializes values to the instance variable   2.    3. class Car{   4.     int speed;   5.        6.     Car(){   7.         System.out.println("speed is "+speed);   8.       }   9.     10.     {   11.          speed = 120;   12.     }   13.         14.     public static void main(String args[]){   15.         Car c1=new Car();   16.         Car c2=new Car();   17.     }       18. }  
Output: speed is 120 speed is 120
There are three places in java where you can perform operations:
1. method 2. constructor 3. block
Flow of invoked of instance initializer block & constructor view plainprint?
1. class Car{   2.     int speed;   3.        4.     Car(){   5.         System.out.println("constructor is invoked");   6.       }   7.     8.     {   9.          System.out.println("instance initializer block invoked");   10.          speed = 120;   11.     }   12.         13.     public static void main(String args[]){   14.         Car c1=new Car();   15.         Car c2=new Car();   16.     }       17. }  
Output: instance initializer block invoked constructor is invoked instance initializer block invoked constructor is invoked
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the costructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by the figure given below  
Rules for instance initializer block : There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is created. 2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call). 3. The instance initializer block comes in the order in which they appear.
Exception Handling and Checked and Unchecked Exception Posted by Dinesh Rajput Exceptions in Java - What are Java Exceptions? A Java Exception is an abnormal condition that arises during the execution of a program and also called a run-time error. An exception in Java signals the unusual or catastrophic situations that can arise. Examples of Java Exceptions are:
 Incorrect user input such as division by zero  File that needs to be opened not found  Network connection problem Types of Java Exceptions Like anything else in this world, Exceptions can also be categorized! Based on whether or not you are required to handle the exception, there are two types of exceptions: 1. Checked Exceptions 2. Unchecked Exceptions. Checked Exceptions: These are the type of exceptions for which the compiler checks to ensure that your code is prepared for handling such exceptions. These are the exceptions that you can expect to occur frequently and you must handle them in your code. The conditions that generate such exceptions are generally outside the control of your program and they can occur in a correct program. But you can anticipate them and thus you must write code to deal with them. Programmatically, checked exceptions are the instances of the Exception class or one of its subclasses, excluding RuntimeException subtree.
List of checked exception  ClassNotFoundException Class not found.
 CloneNotSupportedException Attempt to clone an object that does not implement theCloneable interface.
 IllegalAccessException Access to a class is denied.
 InstantiationException Attempt to create an object of an abstract class or interface.
 InterruptedException One thread has been interrupted by another thread.
 NoSuchFieldException A requested field does not exist.
 NoSuchMethodException A requested method does not exist. Unchecked Exceptions: The compiler does not check for such type of exceptions. Unchecked Exceptions comprise of run time exceptions (of type RuntimeException or its subclasses) and errors (of type Error or its subclasses). Runtime Exceptions occur due to program bugs and include exceptions such as division by zero and invalid array indexing. You can not recover from an unchecked exception and you are not required to handle such type of exceptions either, but still you can do so if you want. ArithmeticException class is an example of unchecked exception. Errors are the exceptions that are not expected to be caught under normal circumstances by your program. They are used by the Java
run time environment to indicate errors related to run time environment itself. Stack Overflow is an example of error.
List of unchecked exception  ArithmeticException Arithmetic error, such as divide-by-zero.
 ArrayIndexOutOfBoundsException Array index is out-of-bounds.
 ArrayStoreException Assignment to an array element of an incompatible type.
 ClassCastException Invalid cast.
 IllegalArgumentException Illegal argument used to invoke a method.
 IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
 IllegalStateException Environment or application is in incorrect state.
 IllegalThreadStateException Requested operation not compatible with current thread state.
 IndexOutOfBoundsException Some type of index is out-of-bounds.
 NegativeArraySizeException Array created with a negative size.
 NullPointerException Invalid use of a null reference.
 NumberFormatException Invalid conversion of a string to a numeric format.
 SecurityException Attempt to violate security.
 StringIndexOutOfBounds Attempt to index outside the bounds of a string.
 UnsupportedOperationException An unsupported operation was encountered.
 
Common scenarios of Exception Handling where exceptions may occur There are given some scenarios where unchecked exceptions can occur. They are as follows: 1) Scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException.
view plainprint?
1. int a=50/0;//ArithmeticException  
2) Scenario where NullPointerException occurs If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
view plainprint?
1. String s=null;   2. System.out.println(s.length());//NullPointerException   3) Scenario where NumberFormatException occurs The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
view plainprint?
1. String s="abc";   2. int i=Integer.parseInt(s);//NumberFormatException   4) Scenario where ArrayIndexOutOfBoundsException occurs If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
view plainprint?
1. int a[]=new int[5];   2. a[10]=50; //ArrayIndexOutOfBoundsException  
Exceptions Methods: Following is the list of important methods available in the Throwable class.  
SN Methods with Description
1
public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2
public Throwable getCause() Returns the cause of the exception as represented by a Throwable object.
3
public String toString() Returns the name of the class concatenated with the result of getMessage()
4
public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.
5
public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6
public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.  
try & catch block and Handling Exceptions Posted by Dinesh Rajput
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catchlooks like the following:
view plainprint?
1. try   2. {   3.    //Protected code   4. }catch(ExceptionName e1)   5. {   6.    //Catch block   7. }    Exception Handling in Java
It is a powerful feature provided in Java. It is a mechanism to handle run-time errors, so that the normal flow of the program is maintained.
Exception handling consists of the following five keywords:
1. Try 2. Catch 3. Finally 4. Throw 5. Throws try block Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by eithercatch or finally block. Syntax of try with catch block view plainprint?
1. try{   2. ...   3. }catch(Exception_class_Name reference){}  
Syntax of try with finally block
view plainprint?
1. try{   2. ...   3. }finally{}   catch block Catch block is used to handle the Exception. It must be used after the try block.  Code without exception handling:
view plainprint?
1. class App{   2.   public static void main(String args[]){   3.       int index = 10/0;   4.      5.       System.out.println("another code here");   6.     }   7.  }  
As displayed in the above example, rest of the code is not executed i.e. another code here statement is not printed. Let's see what happens behind the scene:
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
 Prints out exception description.  Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.  Code with exception handling:
view plainprint?
1. class App{   2.   public static void main(String args[]){   3.       try{   4.           int index = 10/0;   5.       }catch(ArithmeticException e){   6.             System.out.println(e);   7.       }   8.       System.out.println("another code here");   9.     }   10.  }  
Now, as displayed in the above example, rest of the code is executed i.e. another code here. statement is printed.  Multiple catch block Handling Posted by Dinesh Rajput
So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.  A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following
view plainprint?
1. try   2. {   3.    //Protected code   4. }catch(ExceptionType1 e1)   5. {   6.    //Catch block   7. }catch(ExceptionType2 e2)   8. {   9.    //Catch block   10. }catch(ExceptionType3 e3)  
11. {   12.    //Catch block   13. }   The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Lets see an example given below which shows the implementation of multiple catch blocks for a single try block.
view plainprint?
1. public class MultiCatchBlock   2. {   3.    public static void main (String args[])   4.    {   5.       int array[] = {20,10,30};   6.       int num1 = 15,num2 = 0;   7.       int res = 0;   8.    9.   try   10.   {   11.      res = num1/num2;   12.      System.out.println("The result is" +res);   13.    14.     for(int ct =2;ct >=0; ct--)   15.     {   16.       System.out.println("The value of array are" +array[ct]);   17.     }   18.   }   19.   catch (ArrayIndexOutOfBoundsException e)   20.   {   21.      System.out.println("Error?. Array is out of Bounds");   22.   }   23.    24.   catch (ArithmeticException e)    25.   {    26.      System.out.println ("Can't be divided by Zero");    27.   }   28.    29.  }   30. }   31.    
Output of the program:
 In this example we have used two catch clause catching the exceptionArrayIndexOutOfBoundsException and ArithmeticException in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time  the first catch block is skipped and the second catch block handles the error.
1. Rule: At a time only one Exception is occurred and at a time only one catch block is executed. 2. Rule: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception . view plainprint?
1. public class MultiCatchBlock   2. {   3.    public static void main (String args[])   4.    {   5.       int array[] = {20,10,30};   6.       int num1 = 15,num2 = 0;   7.       int res = 0;   8.    9.   try   10.   {   11.      res = num1/num2;   12.      System.out.println("The result is" +res);   13.    14.     for(int ct =2;ct >=0; ct--)   15.     {   16.       System.out.println("The value of array are" +array[ct]);   17.     }   18.   }   19.   catch (Exception e)   20.   {   21.      System.out.println("Common Exception completed");   22.   }   23.   catch (ArrayIndexOutOfBoundsException e)   24.   {   25.      System.out.println("Error?. Array is out of Bounds");   26.   }   27.    28.   catch (ArithmeticException e)    29.   {    30.      System.out.println ("Can't be divided by Zero");    31.   }   32.    33.  }   34. }   35.    
Output: Compile-time error
 
Nested try catch block Handling Posted by Dinesh Rajput
In Java we can have nested try and catch blocks. It means that, a try statement can be inside the block of another try. If an inner try statement does not have a matching catch statement for a particular exception, the control is transferred to the next try statement?s catch handlers that are expected for a matching catch statement. This continues until one of the catch statements succeeds, or until all of the nested try statements are done in. If no one catch statements match, then the Java run-time system will handle the exception.  
Why use nested try block? Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested, one within another. In java, this can be done usingnested try blocks. A try statement can be inside the block of another try. In a nested try block, every time a try block is entered the context of that exception is pushed on the stack.
The following code snippet explains the syntax of a nested try…catch block.  
Syntax:
view plainprint?
1. ....   2. try   3. {   4.     statement 1;   5.     statement 2;   6.     try   7.     {   8.         statement 1;   9.         statement 2;   10.     }   11.     catch(Exception e)   12.     {   13.     }   14. }   15. catch(Exception e)   16. {  
17. }   18. ....  
When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try block are inspected until all nested try statements are exhausted. If no matching blocks are found, the Java Runtime Environment handles the execution.
Lets have an example that uses the nested try-catch blocks.
view plainprint?
1. import java.io.*;   2. public class NestedTryCatchBlock{   3.   public static void main (String args[])throws IOException  {   4.   int num=2,res=0;   5.      6.   try{   7.   FileInputStream fis=null;   8.   fis = new FileInputStream (new File (args[0]));   9.   try{   10.   res=num/0;   11.   System.out.println("The result is"+res);   12.   }   13.   catch(ArithmeticException e){   14.   System.out.println("divided by Zero");   15.   }   16.   }   17.   catch (FileNotFoundException e){   18.   System.out.println("File not found!");   19.   }   20.   catch(ArrayIndexOutOfBoundsException e){   21.   System.out.println("Array index is Out of bound! Argument required");   22.   }   23.   catch(Exception e){   24.   System.out.println("Error.."+e);   25.   }   26. }   27. }  
Output of the program:  
In this given example we have implemented nested try-catch blocks concept where an inner try block is kept with in an outer try block, that's catch handler will handle the arithmetic exception. But before that an ArrayIndexOutOfBoundsException will be raised, if a file name is not passed as an argument while running the program.  
finally block in Java
Posted by Dinesh Rajput The finally Keyword: The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
view plainprint?
1. try   2. {   3.    //Protected code   4. }catch(ExceptionType1 e1)   5. {   6.    //Catch block   7. }catch(ExceptionType2 e2)   8. {   9.    //Catch block   10. }catch(ExceptionType3 e3)   11. {   12.    //Catch block   13. }finally   14. {   15.    //The finally block always executes.   16. }  
 
Note: Before terminating the program, JVM executes finally block(if any).
Note: finally must be followed by try or catch block.
Why use finally block? Sometimes there may be cleanup codes, which are required to be executed. However, when an execution occurs, the program halts abruptly and the clean up code never gets executed. To close a file before terminating a program, that has encountered an exception during execution, Java provides the finally block. The finally gets executed at runtime regardless of what happens in the try/catch block. A finally block ensures that all cleanup work is taken care of when an exception occurs. It is used in conjunction with a try block. The finally block contains statements that either return resources to the system or print messages.
case 1: Program in case exception does not occur
view plainprint?
1. public class FinallyBlock{   2.    3.    public static void main(String args[]){   4.       int a[] = new int[]{2,3,5};   5.       try{   6.          System.out.println("Access element three :" + a[2]);   7.       }catch(ArrayIndexOutOfBoundsException e){   8.          System.out.println("Exception thrown  :" + e);   9.       }   10.       finally{   11.          a[0] = 6;   12.          System.out.println("First element value: " +a[0]);   13.          System.out.println("The finally statement is executed");   14.       }   15.    }   16. }   This would produce following result:  
case 2 Program in case exception occurred and handled
view plainprint?
1. public class FinallyBlock{   2.    3.    public static void main(String args[]){   4.       int a[] = new int[]{2,3,5};   5.       try{   6.          System.out.println("Access element three :" + a[3]);   7.       }catch(ArrayIndexOutOfBoundsException e){   8.          System.out.println("Exception thrown  :" + e);   9.       }   10.       finally{   11.          a[0] = 6;   12.          System.out.println("First element value: " +a[0]);   13.          System.out.println("The finally statement is executed");   14.       }   15.    }   16. }   This would produce following result:
 
case 3 Program in case exception occurred but not handled
view plainprint?
1. public class FinallyBlock{   2.    3.    public static void main(String args[]){   4.       int a[] = new int[]{2,3,5};   5.       try{   6.          System.out.println("Access element three :" + a[2]/0);   7.       }catch(ArrayIndexOutOfBoundsException e){   8.          System.out.println("Exception thrown  :" + e);   9.       }   10.       finally{   11.          a[0] = 6;   12.          System.out.println("First element value: " +a[0]);   13.          System.out.println("The finally statement is executed");   14.       }   15.    }   16. }  
This would produce following result:  
Note the following:
 A catch clause cannot exist without a try statement.  It is not compulsory to have finally clauses when ever a try/catch block is present.  The try block cannot be present without either catch clause or finally clause.  Any code cannot be present in between the try, catch, finally blocks.  For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).  difference between throw and throws in java Posted by Dinesh Rajput throw keyword: The throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
In this example, we have created the validateStudent() method that takes integer value as a parameter. If the age is less than 5, we are throwing the ArithmeticException otherwise print a message welcome to school.
view plainprint?
1. class AgeValidator{   2.    3.    static void validateStudent(int age){   4.      if(age<5)   5.       throw new ArithmeticException("age to play more");   6.      else   7.       System.out.println("welcome to school");   8.    }   9.       10.    public static void main(String args[]){   11.       validateStudent(4);   12.       System.out.println("rest of the code...");   13.   }   14. }  
output here:  
Difference between throw and throws keywords: throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.
Throws: this is to be used when you are not using the try catch statement in your code but you
know that this particular class is capable of throwing so and so exception(only checked exceptions). In this you do not use try catch block but write using the throw clause at appropriate point in you code and the exception is thrown to caller of the method and is handled by it.
1)throw is used to explicitly throw an exception. throws is used to declare an exception.
2)checked exception can not be propagated without throws.
checked exception can be propagated with throws.
3)throw is followed by an instance. throws is followed by class.
4)throw is used within the method. throws is used with the method signature.
5)You cannot throw multiple exception
You can declare multiple exception e.g. public void method()throws IOException,SQLException.
throws keyword in Java
Posted by Dinesh Rajput
The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such asNullPointerException, it is programmers fault that he is not performing check up before the code being used.
Syntax of throws keyword:
view plainprint?
1. void method_name() throws exception_class_name{   2.  ...    3. }    Which exception should we declare? checked exception only, because:
1. unchecked Exception: under your control so correct your code. 2. error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.
Program which describes that checked exceptions can be propagated by throws keyword. view plainprint?
1. import java.io.IOException;   2. class Simple{   3.   void m()throws IOException{   4.     throw new IOException("device error");//checked exception   5.   }   6.   void n()throws IOException{   7.     m();   8.   }   9.   void p(){   10.    try{   11.     n();   12.    }catch(Exception e){System.out.println("exception handled");}   13.   }   14.   public static void main(String args[]){   15.    Simple obj=new Simple();   16.    obj.p();   17.    System.out.println("normal flow...");   18.   }   19. }   Output: exception handled normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch. 2. Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception In case you handle the exception, the code will be executed fine whether exception occurs during the program or not. view plainprint?
1. import java.io.*;   2. class M{   3.  void method()throws IOException{   4.   throw new IOException("device error");   5.  }   6. }   7.    8.    9. class Test{   10.    public static void main(String args[]){   11.     try{   12.      Test t=new Test();   13.      t.method();   14.     }catch(Exception e){System.out.println("exception handled");}      15.    16.     System.out.println("normal flow...");   17.   }   18. }  
Output: exception handled normal flow...
Case2: You declare the exception
 In case you declare the exception, if exception does not occur, the code will be executed fine.  In case you declare the exception if exception occurs, an exception will be thrown at runtime because throws does not handle the exception.  A)Program if exception does not occur view plainprint?
1. import java.io.*;   2. class M{   3.  void method()throws IOException{   4.   System.out.println("device operation performed");   5.  }   6. }   7.    8.    9. class Test{   10.    public static void main(String args[])throws IOException{//declare exception   11.     Test t=new Test();   12.     t.method();      13.    14.     System.out.println("normal flow...");   15.   }   16. }  
Output: device operation performed normal flow...
B)Program if exception occurs
view plainprint?
1. import java.io.*;   2. class M{   3.  void method()throws IOException{   4.   throw new IOException("device error");   5.  }   6. }   7.    8.    9. class Test{   10.    public static void main(String args[])throws IOException{//declare exception   11.     Test t=new Test();   12.     t.method();      13.    14.     System.out.println("normal flow...");  
15.   }   16. }  
Output: Runtime Exception
Exception propagation in Java Posted by Dinesh Rajput
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.
Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).
view plainprint?
1. class ExceptionPropagation{   2.   void m(){   3.     int data = 10/0;   4.   }   5.   void n(){   6.     m();   7.   }   8.   void p(){   9.    try{   10.     n();   11.    }catch(Exception e){   12.       System.out.println("exception handled");   13.    }   14.   }   15.   public static void main(String args[]){   16.    ExceptionPropagation obj = new ExceptionPropagation();   17.    obj.p();   18.    System.out.println("normal flow...");   19.   }   20. }  
output here:
 In the following figure show the stack presentation of the exception propagation flow.  
In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.
Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).
view plainprint?
1. class ExceptionPropagation{   2.   void m(){   3.     throw new java.io.IOException("device error");//checked exception   4.   }   5.   void n(){   6.     m();   7.   }   8.   void p(){   9.    try{   10.     n();   11.    }catch(Exception e){   12.     System.out.println("exception handeled");   13.    }   14.   }   15.   public static void main(String args[]){   16.    ExceptionPropagation obj = new ExceptionPropagation();   17.    obj.p();   18.    System.out.println("normal flow");   19.   }   20. }  
In the above Program which describes that checked exceptions are not propagated.
 
Handle exceptions in overriding methods in Java Posted by Dinesh Rajput
There are few things to remember when overriding a method with exception handling. If super class method does not declare any exception, then sub class overridden method cannot declare checked exception but it can declare unchecked exceptions.
Example of Subclass overridden Method declaring Checked Exception
view plainprint?
1. import java.io.*;   2. class Super   3. {   4.  void show() {    5.    System.out.println("parent class");    6.    }   7. }   8.    9. public class Sub extends Super    10. {   11.  void show() throws IOException  //Compile time error      12.   {    13.     System.out.println("parent class");    14.   }    15.    16.  public static void main( String[] args )   17.  {   18.   Super s=new Sub();   19.   s.show();   20.  }     21. }  
As the method show() doesn't throws any exception while in Super class, hence its overriden version can also not throw any checked exception.
 
Example of Subclass overriden Method declaring Unchecked Exception:
view plainprint?
1. import java.io.*;   2. class Super   3. {   4.  void show(){    5.    System.out.println("parent class");   6.   }   7. }   8.    9. public class Sub extends Super    10. {   11.  void show() throws ArrayIndexOutOfBoundsException      //Correct   12.    {    13.     System.out.println("child class");    14.    }   15.    16.  public static void main(String[] args)   17.  {   18.   Super s=new Sub();   19.   s.show();   20.  }     21. }  
Because ArrayIndexOutOfBoundsException is an unchecked exception hence, overridden show() method can throw it.  
More about Overridden Methods and Exceptions:
If Super class method throws an exception, then Subclass overridden method can throw the same exception or no exception, but must not throw parent exception of the exception thrown by Super class method.
 It means, if Super class method throws object of NullPointerException class, then Subclass method can either throw same exception, or can throw no exception, but it can never throw object of Exception class (parent of NullPointerException class).
Example of Subclass overridden method with same Exception
view plainprint?
1. import java.io.*;   2. class Super   3. {   4.  void show() throws Exception    5.   {     6.     System.out.println("parent class");    7.   }   8. }   9.    10. public class Sub extends Super {   11.  void show() throws Exception  //Correct        12.    {    13.     System.out.println("child class");   14.    }    15.    16.  public static void main(String[] args)   17.  {   18.   try {   19.    Super s=new Sub();   20.    s.show();   21.    }   22.   catch(Exception e){}   23.  }     24. }    
Example of Subclass overriden method with no Exception:
view plainprint?
1. import java.io.*;   2. class Super   3. {   4.  void show() throws Exception    5.   {    
6.     System.out.println("parent class");    7.   }   8. }   9.    10. public class Sub extends Super {   11.  void show()               //Correct        12.    {   13.      System.out.println("child class");    14.    }    15.    16.  public static void main(String[] args)   17.  {   18.   try {   19.    Super s=new Sub();   20.    s.show();   21.    }   22.   catch(Exception e){}   23.  }     24. }    
Example of Subclass overriden method with parent Exception:
view plainprint?
1. import java.io.*;   2. class Super   3. {   4.  void show() throws ArithmeticException    5.   {     6.    System.out.println("parent class");   7.   }   8. }   9.    10. public class Sub extends Super {   11.  void show() throws Exception           //Cmpile time Error        12.    {    13.       System.out.println("child class");   14.    }    15.    16.  public static void main(String[] args)   17.  {   18.   try {   19.    Super s=new Sub();   20.    s.show();   21.    }   22.   catch(Exception e){}   23.  }     24. }  
 
User defined Exception in Java Posted by Dinesh Rajput
You can also create your own exception sub class simply by extending java Exception class. You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch.
view plainprint?
1. class InvalidAgeException extends Exception{   2.  InvalidAgeException(String s){   3.   super(s);   4.  }   5.  public String toString()   6.  {   7.   return "Candidate is less than 18 year is not allowed to vote.";   8.  }   9. }  
view plainprint?
1. class ValidateCandidate{   2.    3.    static void validate(int age) throws InvalidAgeException{   4.      if(age < 18)   5.          throw new InvalidAgeException("invalid candidate");   6.      else   7.          System.out.println("welcome to vote");   8.    }   9.       10.    public static void main(String args[]){   11.       try{   12.         validate(13);   13.       }catch(Exception ex){   14.          System.out.println("Exception occured: "+ex);   15.       }   16.    17.       System.out.println("rest of the code...");   18.   }   19. }  
output here:
 
Points to Remember
1. Extend the Exception class to create your own exception class. 2. You don't have to implement anything inside it, no methods are required. 3. You can have a Constructor if you want. 4. You can override the toString() function, to display customized message.
Multiple Exceptions In Java 7 New Concept Posted by Dinesh Rajput Introduction
In this article we will discuss multiple exceptions in Java 7. Its a new feature released by Java 7 to remove redundancy of code since we don't need to write a catch statement again and again. First we discuss exceptions and exception handling and after that multiple exceptions in Java 7.
Exception in Java
In terms of dictionaries, an exception is an abnormal condition. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
In Java, an exception is an event that disrupts the normal flow of a program.
When we execute our program, sometimes an error is generated for some of reasons given below, when this error is generated during execution it is called an exception. The exception can occur:
 When the user has entered incorrect data or we can say invalid data.  When we opened a file that's needed in the program but can't be found.  Sometimes when the network connection is lost during execution of the program.
To understand exceptions in Java, you need to understand the two categories of exceptions; they are:
1. Checked Exception (also called a compile-time exception) 2. Unchecked Exception (also called a run-time exception) Checked Exception
It is also called a compile-time exception since they checked at compile time of the program. For example, ServletException,ClassNotFoundException, NoSuchFieldException etc.
Unchecked Exception
It is also called a run-time exception since they occur during run-time. Such an exception is not checked at compile time, in other words NullPointerException, OutOfMemoryError, etc.
example view plainprint?
1. public class RunTimeExcpn    2.   {    3.     public static void main(String[] args)    4.       {    5.         String str = null;   6.         int len = str.length();   7.       }    8.   }    Output:  
Now the subject arises of how to overcome this problem of exception, for that Java provides am exception handler technique. Now we discuss exception handling in Java.
Exception Handling in Java
It is a powerful feature provided in Java. It is a mechanism to handle run-time errors, so that the normal flow of the program is maintained.
Exception handling consists of the following five keywords:
1. Try
2. Catch 3. Finally 4. Throw 5. Throws Now, we show an example for exception handling: view plainprint?
1. class Demo   2.   {   3.     public static void main(String args[])   4.       {   5.         try   6.           {   7.             int data=50/0;   8.           }   9.         catch(ArithmeticException e)    10.           {   11.             System.out.println(e);   12.           }   13.         System.out.println("remaining code");   14.       }   15.   }    Output:
In this program an arithmetic exception occurs that is sometimes called "divide by null error" problem, for handling this exception we use a "try-catch block". In the try block we write the code where the problem occurs and in the catch block we catch the exception as determined by its type. In this program the arithmetic exception is generated so we use acatch(ArithmeticException e) statement to maintain the flow of the program.  
We are not going into the details of Exception Handling; our topic is "multiple exceptions in Java 7". So for discussing our topic we take a short look at "exception" and "exception handling" in Java.
Multiple Exception in Java 7 new concept
It provides a way of "Handling More Than One Type of Exception". Java 7 made it possible to catch various exceptions in the same catch block that is not possible in prior versions of Java. This is also known as multi-catch.
In prior versions of Java:
view plainprint?
1. catch (IOException ey)  
2.   {   3.     logger.log(ey);   4.     throw ey;   5. catch (SQLException ey)    6.   {   7.     logger.log(ey);   8.     throw ey;   9.   }   10. catch(Exception e)    11.   {   12.     logger.severe(e);   13.   }  
In prior versions of Java 7, it is difficult to create a common method to remove the repeated code because the variable "ey" has various types.
The following example is valid in Java 7 and later, it eliminates the need for repeated code:
view plainprint?
1. catch (IOException | SQLException ey)    2.   {   3.     logger.log(ey);   4.     throw ey;   5.   }   The catch defines the types of exceptions, and each exception type is separated with a vertical bar ( | ).  Advantages of Multiple Exception in Java 7
1. Single-line catching might help in JDBC, formatting date and Java IO in Java. For throwing an exception in IO related code we use IOException, in JDBC code we use SQLException, and for date formatting we use ParseException, that can't be handled in a single catch block prior to Java 7. Catching java.lang.Exception works for all kinds of exceptions but it is not a good practice. With multiple exceptions in Java 7 we catch both exceptions in one catch block. 2. The exception handling changes in Java SE 7 allow you to program more concisely. 3. They also allow you to partially handle an exception and then let it bubble up. 4. Reduce a substantial amount of workload. 5. Remove redundancy of code since we don't need to write a catch statement again and again. Now in following example we show a difference between exception handling in Java 7 and in prior versions of Java.
Exception handling in Java
view plainprint?
1. class ExceptionEx1   2.   {   3.     public static void main(String args[])   4.       {   5.         try  
6.           {   7.             int a[]=new int[5];   8.             a[5]=345/0;   9.           }   10.         catch(ArithmeticException e)   11.           {   12.             System.out.println("work 1 done");   13.           }   14.         catch(ArrayIndexOutOfBoundsException e)   15.           {   16.             System.out.println("work 2 completed");   17.           }   18.         catch(Exception e)   19.           {   20.             System.out.println("Common task completed");   21.           }   22.         System.out.println("remaining part of the code");   23.       }   24.   }   Output:  
Exception handling in Java 7
view plainprint?
1. class ExceptionEx2   2. {   3.    public static void main(String args[])   4.    {   5.     try   6.     {   7.      int a[]=new int[5];   8.      a[5]=345/0;   9.     }   10.     catch(ArithmeticException | ArrayIndexOutOfBoundsException e)   11.     {   12.      System.out.println("work 1 done");   13.     }   14.     catch(Exception e)   15.     {   16.       System.out.println("Common task completed");   17.     }   18.     System.out.println("remaining part of the code");   19.   }   20. }   Output:
 
Different Exception Generate in Array in Java(7) Posted by Dinesh Rajput
In this article we are going to describe the many exceptions that are possibly generated by an array in Java. So now we describe each Exception type in detail one by one. First we give you a little introduction to arrays in Java.
Introduction  
In this article we are going to describe the many exceptions that are possibly generated by an array in Java. So now we describe each Exception type in detail one by one. First we give you a little introduction to arrays in Java.
Array Definition  
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. And it also contains similar types of data. Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, the numbering begins with 0.  
Possible Error Type
1 - NullPointerException : In Java a NullPointerException is a class which also extends RuntimeException. There are the following conditions where the NullPointerException is
generated. They are thrown when an application attempts to use null in a case where an object is required.
 Calling the instance method of a null object.  Accessing or modifying the field of a null object.  Taking the length of null as if it were an array.  Accessing or modifying the slots of null as if it were an array.  Throwing null as if it were a Throwable value. Applications should throw instances of this class to indicate other illegal uses of the null object.
2 - NegativeArraySizeException : This error is thrown when anyone wants create an array with a negative size.NegativeArraySizeException is a class in Java which extends RuntimeException.
3 - ArrayIndexOutOfBoundsException : This type of error is generated when an array has been accessed with an illegal index. In other words when an array is accessed by a negative index or more than the size of the array. In Java it's a separate class and this class extends the IndexOutOfBoundException class.
4 - IndexOutOfBoundsException : This type of exception is thrown by all indexing pattern data types such as an array string and a vector etc., when it is accessed out of the index (range). IndexOutOfBoundException is also a separate class in Java and it extends RuntimeException.
5 - ClassCastException : The ClassCastException is thrown when the following code has attempted to cast an object to a subclass of which it is not an instance. ClassCastException is also a separate class in Java and it extends RuntimeException.
ClassCastException condition: view plainprint?
1. Object x = new Integer(0);   2. System.out.println((String)x);  
6 - ArrayStoreException : This type of exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException. ArrayStoreException is also a separate class in Java and it extends RuntimeException.
For example:
view plainprint?
1. Object x[] = new String[7];   2. x[0] = new Integer(0);   Example:
view plainprint?
1. public class ExceptionInArray {  
2.     3.       public static void main(String[] args) {   4.             int array[] = null;   5.             int arraySize = 4;   6.             int arrayInc = -0;   7.             int output;   8.     9.             for (int i = 0; i < 6; i++) {   10.                   try {   11.                         // Multiple Switch Conditions   12.                         switch (i) {   13.                         case 0:   14.                               output = array[0]; // Generates a NullPointerExcep tion.   15.                               break;   16.                         case 1:   17.                               array = new int[arrayInc]; // Generates a   18.                               // NegativeArraySizeException.   19.                               output = array[arrayInc];   20.                               break;   21.                         case 2:   22.                               array = new int[arraySize]; // Generate the   23.                               // ArrayIndexOutOfBoundsException.   24.                               output = array[arraySize];   25.                               break;   26.                         case 3:   27.                               array = new int[5]; // Generate the   28.                               // IndexOutOfBoundsException.   29.                               output = array[5];   30.                         case 4:   31.                               Object newArray = new Integer(0); // Generate the   32.                               // ClassCastException.   33.                               System.out.println((String) newArray);   34.                         case 5:   35.                               Object X[] = new String[-5]; // Generate the   36.                               // ArrayStoreException.   37.                               X[0] = new Integer(0);   38.                               System.out.println(X);   39.                         }   40.     41.                   } catch (NullPointerException | NegativeArraySizeException | A rrayIndexOutOfBoundsException | ClassCastException | ArrayStoreException ex) {   42.                         System.out.println("\n Exception Generated: "   43.                                     + ex.getMessage());   44.                         ex.printStackTrace();   45.                    }    46.             }   47.       }   48. }   OUTPUT:

   
Inner Nested Classes in Java Posted by Dinesh Rajput
A class declared inside a class is known as nested class. We use nested classes to logically group classes in one place so that it can be more readable and maintainable code. Moreover, it can access all the members of outer class including private members.
Syntax of Nested class
view plainprint?
1. class OuterClass {   2.     ...   3.     class NestedClass {   4.         ...   5.     }   6. }   difference between nested class and inner class? Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply calledstatic nested classes. Non-static nested classes are called inner classes. Inner class is a part of nested class. Non-static nested classes are known as inner classes.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)  Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
1. It is a way of logically grouping classes that are only used in one place. 2. It increases encapsulation. 3. Nested classes can lead to more readable and maintainable code.  Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.  Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.  More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.
Types of Nested class: There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes. 1. non-static nested class(inner class) o a)Member inner class o b)Annomynous inner class o c)Local inner class 2. static nested class
 
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience. Static nested classes are accessed using the enclosing class name:
view plainprint?
1. OuterClass.StaticNestedClass   For example, to create an object for the static nested class, use this syntax:
view plainprint?
1. OuterClass.StaticNestedClass nestedObject =   2. new OuterClass.StaticNestedClass();    Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
view plainprint?
1. class OuterClass {   2.     ...   3.     class InnerClass {   4.         ...   5.     }   6. }   An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea.  
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
view plainprint?
1. OuterClass.InnerClass innerObject = outerObject.new InnerClass();   Additionally, there are two special kinds of inner classes: local classes and anonymous classes. Member inner class Posted by Dinesh Rajput
A class that is declared inside a class but outside a method is known as member inner class. Invocation of Member Inner class
1. From within the class 2. From outside the class Example of member inner class that is invoked inside a class In this example, we are invoking the method of member inner class from the display method of Outer class. view plainprint?
1. class Outer{   2.    private int value = 70;   3.    class Inner{   4.       void show(){   5.           System.out.println("value is "+value );  
6.       }   7.     }   8.     9.    void display(){   10.      Inner in = new Inner();   11.      in.show();   12.    }   13.   public static void main(String args[]){   14.     Outer obj = new Outer();   15.     obj.display();   16.   }   17. }   output:  
See in the directory there are the two following class files after compiling. Outer.class Outer$Inner.class
Internal code generated by the compiler for member inner class: The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.
view plainprint?
1. import java.io.PrintStream;   2.    3. class Outer$Inner   4. {   5.     final Outer this$0;   6.     Outer$Inner()   7.     {   super();   8.         this$0 = Outer.this;   9.     }   10.    11.     void show()   12.     {   13.         System.out.println((new StringBuilder()).append("value is ")   14.                     .append(Outer.access$000(Outer.this)).toString());   15.     }   16.  }    
Example of member inner class that is invoked outside a class
 In this example, we are invoking the show() method of Inner class from outside the outer class i.e. Test class.
//Program of member inner class that is invoked outside a class
view plainprint?
1. class Outer{   2.   private int value = 70;   3.   class Inner{   4.    void show(){System.out.println("value is "+value);}   5.   }   6. }   7.    8. class Test{   9.   public static void main(String args[]){   10.     Outer obj = new Outer();   11.     Outer.Inner in = obj.new Inner();   12.     in.show();   13.   }   14. }    output:  
Rules for Inner Classes: Following properties can be noted about Inner classes:
 The outer class (the class containing the inner class) can instantiate as many number of inner class objects as it wishes, inside it’s code.  If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.  In above case the inner class can be created as follows: view plainprint?
1. <OuterClassName> outerObj = new <OuterClassName>(arguments);   2. outerObj.<InnerClassName> innerObj = outerObj.new <InnerClassName>(arguments);    No inner class objects are automatically instantiated with an outer class object.  If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with an instance of the outer class.  Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a varible with same name then the outer class’s variable can be access like this: view plainprint?
1. <OuterClassName>.this.<variableName>    The outer class can call even the private methods of the inner class
Annonymous inner class in java Posted by Dinesh Rajput
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
The inner class which is declared inside the body of a method is known as the local inner classes. The class declared inside the body of a method without naming it is known as anonymous inner classes.
The anonymous inner classes is very useful in some situation. For example consider a situation where you need to create the instance of an object without creating subclass of a class and also performing additional tasks such as method overloading.
A class that have no name is known as anonymous inner class. Anonymous class can be created by:
1. Class (may be abstract class also). 2. Interface Program of anonymous inner class by abstract class view plainprint?
1. abstract class Employee{   2.     abstract void work();   3. }   4.    5. class Manager{   6.   public static void main(String args[]){   7.      Employee emp = new Employee(){   8.         void work()   9.         {   10.            System.out.println("Manage the team");}   11.         };   12.       emp.work();   13.    }   14. }    Output:
After compiling we will get the following class files.
 Employee.class  Manager$1.class  Manager.class 1. A class is created but its name is decided by the compiler which extends the Employee class and provides the implementation of the work() method. 2. An object of Anonymous class is created that is referred by emp reference variable of Employee type. As you know well that Parent class reference variable can refer the object of Child class. The internal code generated by the compiler for annonymous inner class view plainprint?
1. import java.io.PrintStream;   2. static class Manager$1 extends Employee   3. {   4.    Manager$1(){   5.        6.    }   7.    void work()   8.     {   9.         System.out.println("Manage the team");   10.     }   11. }   Program of anonymous inner class by interface:
view plainprint?
1. interface Employee{   2.     void work();   3. }   4.    5. class Manager{   6.   public static void main(String args[]){   7.      Employee emp = new Employee(){   8.         void work()   9.         {   10.            System.out.println("Manage the team");}   11.         };   12.       emp.work();   13.    }   14. }    Output:
 The internal code generated by the compiler for annonymous inner class
view plainprint?
1. import java.io.PrintStream;   2. static class Manager$1 implements Employee   3. {   4.    Manager$1(){   5.        6.    }   7.    void work()   8.     {   9.         System.out.println("Manage the team");   10.     }   11. }  
Local Inner Classes Example in Java Posted by Dinesh Rajput
If an inner class has been defined within a code block (typically within the body of a method), then such an inner class is called a local inner class. A local inner class is not a member of the enclosing class and hence it can not have any access specifier. A local inner class will have access to all the members of the enclosing class and it'll have access to the local final variables in the scope it's defined.
Program of local inner class:
view plainprint?
1. class LocalInner{   2.    private String message = "dineshonjava.com";//instance variable   3.    void display(){   4.       class Local{   5.         void msg(){   6.           System.out.println(message);   7.         }   8.       }   9.      Local loc = new Local();   10.      loc.msg();   11.    }   12.    public static void main(String args[]){   13.       LocalInner obj = new LocalInner();   14.       obj.display();   15.    }   16. }   output:

After compiling we will get the following class files
1. LocalInner$1Local.class 2. LocalInner.class Internal code generated by the compiler for local inner class: In such case, compiler creates a class named LocalInner$1Local.class that have the reference of the outer class. view plainprint?
1. import java.io.PrintStream;   2. class LocalInner$1Local   3. {   4.     final LocalInner this$0;   5.    6.     LocalInner$1Local()   7.     {      8.         super();   9.         this$0 = LocalInner.this;   10.     }   11.     void msg()   12.     {   13.         System.out.println(LocalInner.access$000(LocalInner.this));   14.     }   15. }  
Rule: Local variable can't be private, public or protected.  Rules for Local Inner class 1) Local inner class cannot be invoked from outside the method. 2) Local inner class cannot access non-final local variable. Program of accessing non-final local variable in local inner class
view plainprint?
1. class LocalInner{   2.    private String message = "dineshonjava.com";//instance variable   3.    void display(){   4.      int data = 20;//local variable must be final   5.       class Local{   6.         void msg(){   7.           System.out.println(message+" : "+data);//compile time error   8.         }   9.       }  
10.      Local loc = new Local();   11.      loc.msg();   12.    }   13.    public static void main(String args[]){   14.       LocalInner obj = new LocalInner();   15.       obj.display();   16.    }   17. }  
Output: Compile Time Error  
Program of accessing final local variable in local inner class:
view plainprint?
1. class LocalInner{   2.    private String message = "dineshonjava.com";//instance variable   3.    void display(){   4.      final int data = 20;//local variable must be final   5.       class Local{   6.         void msg(){   7.           System.out.println(message+" : "+data);   8.         }   9.       }   10.      Local loc = new Local();   11.      loc.msg();   12.    }   13.    public static void main(String args[]){   14.       LocalInner obj = new LocalInner();   15.       obj.display();   16.    }   17. }   Output:  
A local inner class is defined within a method, and the usual scope rules apply to it. It is only accessible within that method, therefore access restrictions (public, protected, package) do not apply. However,
because objects (and their methods) created from this class may persist after the method returns, a local inner class may not refer to parameters or non-final local variables of the method. static nested classes in java Posted by Dinesh Rajput
A nested class that is declared static is called a static nested class. Memory to the objects of any static nested classes are allocated independently of any particular outer class object. A static nested class use the instance variables or methods defined in its enclosing class only through an object reference. A static nested class interacts with the instance members of its outer class or any other class just like a top-level class.
Given below is the syntax of the Static nested class that defines static nested class having keyword static in the outer class.
view plainprint?
1. class OuterClass {   2.   ....   3.   static class StaticNestedClass {   4.     ....   5.   }   6.   class InnerClass {   7.   ....    8.     }   9.   }   Static nested classes can be accessed by using the enclosing class name:
view plainprint?
1. uterClass.StaticNestedClass   If we want to make an object of the static nested class then we have to write down the following code:
view plainprint?
1. OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();    Static nested class facts:
 is defined as a static member of the parent class  accepts all accessibility modifiers  it is NOT linked to an outer instance (it can live independently)  has direct access to static members of the parent class regardless of the access modifiers declared in the parent class  has direct access to all members of an instance of the parent class regardless of the access modifiers declared in the parent class Program of static nested class that have instance method
view plainprint?
1. class StaticNested{   2.    static String message = "Dinesh on Java";   3.    4.   static class Inner{   5.      void display()   6.      {   7.         System.out.println("message is "+message);   8.      }   9.   }   10.     11.   public static void main(String args[]){   12.       StaticNested.Inner obj = new StaticNested.Inner();   13.       obj.display();   14.   }   15. }    output:  
In this example, you need to create the instance of static nested class because it has instance method display(). But you don't need to create the object of StaticNested outer class because nested class is static and static properties, methods or classes can be accessed without object.
There are following class files are generated after the compilation of the program.
1. StaticNested$Inner.class 2. StaticNested.class Internal code generated by the compiler for static nested class view plainprint?
1. import java.io.PrintStream;   2.    3. static class StaticNested$Inner   4. {   5.     StaticNested$Inner(){   6.       7.     }   8.    9.    void display(){   10.       System.out.println((new StringBuilder()).append("message is ")   11.       .append(StaticNested.message).toString());   12.    }   13.        14. }  
Program of static nested class that have static method
view plainprint?
1. class StaticNested{   2.    static String message = "Dinesh on Java";   3.    4.   static class Inner{   5.      static void display()   6.      {   7.         System.out.println("message is "+message);   8.      }   9.   }   10.     11.   public static void main(String args[]){   12.       StaticNested.Inner.display();//no need to create the instance of static ne sted class   13.   }   14. }   output:  
The advantage of a static nested class is that it doesn't need an object of the containing class to work. This can help you to reduce the number of objects your application creates at runtime.
Nested Interface in Java
Posted by Dinesh Rajput
A nested interface is just a regular interface defined inside another class or interface. They are actually defined inside the body of the parent class, not only in the same file. The feature is useful for grouping related interfaces and for encapsulating interfaces in the classes where they are used.
Nested interfaces facts:
 when declared inside another interface they can only be public  when declared inside classes they can accept any access modifiers  they are implicitly static  they can be implemented by any class (package level, nested or inner) as long as the access modifiers permit visibility  as with regular package level interfaces variables defined inside are considered to be constants (static public) regardless of whether the modifiers are specified  like the package level interfaces they can declare nested classes and interfaces While declaring nested interfaces in classes is useful and can help maintain a clean design, other constructs like classes nested in interfaces and interfaces nested in interfaces are of little benefit and
seem outright weird and even dangerous.
Syntax of nested interface which is declared within the interface view plainprint?
1. interface interface_name{   2.  ...   3.  interface nested_interface_name{   4.   ...   5.  }   6. }    Syntax of nested interface which is declared within the class
view plainprint?
1. class class_name{   2.  ...   3.  interface nested_interface_name{   4.   ...   5.  }   6. }    Example of nested interface which is declared within the interface
view plainprint?
1. interface Designable{   2.    void design();   3.    interface Message{   4.        void dispaly();   5.   }   6. }   7.    8. class NestedDemo implements Designable.Message{   9.    public void dispaly(){   10.      System.out.println("Hello nested interface at Dinesh on Java");   11.    }   12.    13.   public static void main(String args[]){   14.      Designable.Message message = new NestedDemo();//upcasting here   15.      message.dispaly();   16.   }   17. }    output:
 
As you can see in the above example, we are accessing the Message interface by its outer interface Designable because it cannot be accessed directly. It is just like Almira inside the room, we cannot access the Almira directly because we must enter the room first. In collection framework, sun micro-system has provided a nested interface Entry. Entry is the sub interface of Map i.e. accessed by Map.Entry.
After compiling we get the following class files
1. NestedDemo.class 2. Designable$Message.class 3. Designable.class
Internal code generated by the java compiler for nested interface Message The java compiler internally creates public and static interface as displayed below: view plainprint?
1. public static interface Designable$Message   2.   {   3.     public abstract void dispaly();   4.   }    Example of nested interface which is declared within the class Let's see how can we define an interface inside the class and how can we access it.
view plainprint?
1. class Design{   2.     interface Message{   3.        void dispaly();   4.   }   5. }   6.    7. class NestedDemo implements Design.Message{   8.    public void dispaly(){   9.      System.out.println("Hello nested interface at Dinesh on Java");   10.    }   11.    12.   public static void main(String args[]){   13.      Design.Message message = new NestedDemo();//upcasting here   14.      message.dispaly();   15.   }   16. }  
 output:  
After compiling we get the following class files
1. NestedDemo.class 2. Design$Message.class 3. Design.class
define a class inside the interface If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we define a class within the interface: view plainprint?
1. interface INT{   2.   class Demo{}   3. }  
Multithreading in Java
Posted by Dinesh Rajput
In this article you can learn the basic steps of creating a thread; this article provides two ways for creating your own thread in Java.
Multithreading is a process of executing multiple threads simultaneously. A program can be divided into a number of small processes. Each small process can be addressed as a single thread (a lightweight process). Multithreaded programs contain two or more threads that can run concurrently. This means that a single program can perform two or more tasks simultaneously. For example, one thread is writing content on a file at the same time another thread is performing spelling check.
Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes. Multithreading is mostly used in games, animation etc.
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
 Process-based Multitasking(Multiprocessing)  Thread-based Multitasking(Multithreading) In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread.  
1)Process-based Multitasking (Multiprocessing)
 Each process have its own address in memory i.e. each process allocates separate memory area.  Process is heavyweight.  Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
2)Thread-based Multitasking (Multithreading)  Threads share the same address space.  Thread is lightweight.  Cost of communication between the thread is low.  Note:At least one process is required for each thread. Advantages of multithreading over multiprocessing :   Reduces the computation time.  Improves performance of an application.  Threads share the same address space so it saves the memory.  Context switching between threads is usually less expensive than between processes.  Cost of communication between threads is relatively low.
Life Cycle of A Thread
Posted by Dinesh Rajput
When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states.
A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non-runnable andterminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows:
1. New 2. Runnable(Ready) 3. Running 4. Non-Runnable (Blocked, Sleeping, Waiting) 5. Terminated(Dead)
 
States of thread- A thread has one of the following States.
New-A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
1-Runnable- After invocation of start() method on new thread, the thread becomes runnable.After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. 2-Running-A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 3-Blocked- This is the state when a thread is waiting for a lock to access an object. 4-Waiting-Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
5-Timed waiting- A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. 6-Not Runnable- after Runnable states these three states are assumed to be in a not Runnable state. These three states are waiting, Timed_waiting(sleeping) and Terminated. 7-Terminated- In this state the thread is dead.  Creating a thread in Java Posted by Dinesh Rajput
In Java, an object of the Thread class can represent a thread. Thread can be implemented through any one of two ways:
1. Extending the java.lang.Thread Class 2. Implementing the java.lang.Runnable Interface
Extending the java.lang.Thread Class
For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:
1. Extend the java.lang.Thread Class. 2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. 3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. 4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. By extend the Thread class of java.lang package. Syntax........... view plainprint?
1. class MyThread extends Thread   2. {   3. -----------------;   4. -----------------;   5. }   Override the run( ) Method-The run( ) method has to be Overridden by writing codes required for the thread. The thread behaves as per this code segment.
view plainprint?
1. public void run()   2. {   3. ----------------;   4. ----------------;   5. }   Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)  Thread(Runnable r)  Thread(Runnable r,String name) Commonly used methods of Thread class:  public void run(): is used to perform action for a thread.  public void start(): starts the execution of the thread.JVM calls the run() method on the thread.  public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.  public void join(): waits for a thread to die.  public void join(long miliseconds): waits for a thread to die for the specified miliseconds.  public int getPriority(): returns the priority of the thread.  public int setPriority(int priority): changes the priority of the thread.  public String getName(): returns the name of the thread.  public void setName(String name): changes the name of the thread.  public Thread currentThread(): returns the reference of currently executing thread.  public int getId(): returns the id of the thread.  public Thread.State getState(): returns the state of the thread.  public boolean isAlive(): tests if the thread is alive.  public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.  public void suspend(): is used to suspend the thread(depricated).  public void resume(): is used to resume the suspended thread(depricated).  public void stop(): is used to stop the thread(depricated).  public boolean isDaemon(): tests if the thread is a daemon thread.  public void setDaemon(boolean b): marks the thread as daemon or user thread.  public void interrupt(): interrupts the thread.  public boolean isInterrupted(): tests if the thread has been interrupted.  public static boolean interrupted(): tests if the current thread has been interrupted. Extending Thread class Example
This is a way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread. view plainprint?
1. class MyThread extends Thread   2. {   3.    public void run()   4.    {   5.      System.out.println("Concurrent thread started running..");   6.    }   7. }   8.    9. class MyThreadDemo   10. {   11.    public static void main( String args[] )   12.    {  
13.      MyThread mt = new  MyThread();   14.      mt.start();   15.    }   16. }   In this case also, as we must override the run() and then use the start() method to start and run the thread. Also, when you createMyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class object acts as Thread class object. output:
What if we call run() method directly without using start() method ? In above program if we directly call run() method, without using start() method,
view plainprint?
1. public static void main( String args[] )   2. {   3.    MyThread mt = new MyThread();   4.    mt.run();   5. }   Doing so, the thread won't be allocated a new call stack, and it will start running in the current call stack, that is the call stack of the main thread. Hence Multithreading won't be there.
Can we Start a thread twice ? No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.
view plainprint?
1. public static void main( String args[] )   2. {   3.    MyThread mt = new MyThread();   4.    mt.start();   5.    mt.start();     //Exception thrown   6. }   When a thread is in running state, and you try to start it again, or any method try to invoke that thread again using start() method, exception is thrown.  Implementing the Runnable Interface: The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form,
view plainprint?
1. public void run()    run() method introduces a concurrent thread into your program. This thread will end when run() returns.  You must specify the code for your thread inside run() method.  run() method can call other methods, can use other classes and declare variables just like any other normal method. view plainprint?
1. class MyThread implements Runnable   2. {   3.    public void run()   4.    {   5.      System.out.println("concurrent thread started running..");   6.    }   7. }   8.    9. class MyThreadDemo   10. {   11.     public static void main( String args[] )   12.     {   13.       MyThread mt = new MyThread();   14.       Thread t = new Thread(mt);   15.       t.start();   16.    }   17. }   To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program.  
Thread Scheduling in Java
Posted by Dinesh Rajput
Features :
 The JVM schedules using a preemptive , priority based scheduling algorithm.  All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM.  In case two threads have the same priority a FIFO ordering is followed.
A different thread is invoked to run in case one of the following events occur:
1.The currently running thread exits the Runnable state ie either blocks or terminates. 2. A thread with a higher priority than the thread currently running enters the Runnable state. The lower priority thread is preempted and the higher priority thread is scheduled to run.
Time Slicing is dependent on the implementation.
A thread can voluntarily yield control through the yield() method. Whenever a thread yields control of the CPU another thread of the same priority is scheduled to run. A thread voluntarily yielding control of the CPU is called Cooperative Multitasking.
Thread Priorities JVM selects to run a Runnable thread with the highest priority.
 All Java threads have a priority in the range 1-10.  Top priority is 10, lowest priority is 1.Normal  priority ie. priority by default is 5.  Thread.MIN_PRIORITY - minimum thread priority  Thread.MAX_PRIORITY - maximum thread priority  Thread.NORM_PRIORITY - maximum thread priority
Whenever a new Java thread is created it has the same priority as the thread which created it. Thread priority can be changed by the setpriority() method.
Java Based Round-Robin Scheduler (An example) view plainprint?
1. public class Scheduler extends Thread   2.    3. {   4. public Scheduler(){   5. timeSlice = DEFAULT_TIME_SLICE;   6. queue = new Circularlist();   7. }   8.    9. public Scheduler(int quantum){  
10. timeSlice = quantum;   11. queue = new Circularlist();   12. }   13.    14. public addThread(Thread t) {   15. t.setPriority(2);   16. queue.additem(t);   17. }   18.    19. private void schedulerSleep() {   20. try{   21. Thread.sleep(timeSlice );   22. } catch (InterruptedException e){};   23. }   24. public void run(){   25. Thread current;   26.    27. This.setpriority(6);   28. While (true) {   29. // get the next thread   30. current = (Thread)qeue.getnext();   31. if ( (current != null) && (current.isAlive()) ){   32. current.setPriority(4);   33. schedulerSleep();   34. current.setPriority(2)   35. }   36. }   37. }   38.    39. private CircularList queue;   40. private int timeSlice;   41. private static final int DEFAULT_TIME_SLICE = 1000;   42. }   43. public class TesScheduler   44. {   45. public static void main()String args[]) {   46. Thread.currentThread().setpriority(Thread.Max_Priority);   47. Schedular CPUSchedular = new Scheduler ();   48. CPUSchedular.start()   49. TestThread t1 = new TestThread("Thread 1");   50. t1.start()   51. CpuSchedular.addThread(t1);   52. TestThread t2 = new TestThread("Thread 2");   53. t2.start()   54. CpuSchedular.addThread(t2);   55. TestThread t3 = new TestThread("Thread 1");   56. t3.start()   57. CpuSchedular.addThread(t3);   58. }   59. }  
Sleeping a thread using sleep() method Posted by Dinesh Rajput
The Thread.sleep() method effectively "pauses" the current thread for a given period of time. We used it in our very first threading example to make threads display a message periodically, sleeping between messages. From the outset, it's important to be aware of the following:
 it is always the current thread that is put to sleep;  the thread might not sleep for the required time (or even at all);  the sleep duration will be subject to some system-specific granularity, typically 1ms;  while sleeping, the thread still owns synchronization locks it has acquired;  the sleep can be interrupted (sometimes useful for implementing a cancellation function);  calling sleep() with certain values can have some subtle, global effects on the OS (see below), and vice versa, other threads and processes running on the system can have subtle effects on the observed sleep duration. Syntax of sleep() method: The Thread class provides two methods for sleeping a thread: 1. public static void sleep(long miliseconds)throws InterruptedException 2. public static void sleep(long miliseconds, int nanos)throws InterruptedException
view plainprint?
1. class MultiThreadDemo extends Thread{   2.   public void run(){   3.   for(int i=1;i<5;i++){   4.      try{   5.          Thread.sleep(500);   6.      }catch(InterruptedException e){   7.          System.out.println(e);   8.     }   9.     System.out.println("Dinesh on Java Thread Application "+i);   10.   }   11.  }   12.  public static void main(String args[]){   13.   MultiThreadDemo t1 = new MultiThreadDemo();   14.   MultiThreadDemo t2 = new MultiThreadDemo();   15.     16.   t1.start();   17.   t2.start();   18.  }   19. }   Output:
As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.  
Java Thread Join using join() method Posted by Dinesh Rajput
In this part of tutorial we will learn how to use the join method in the Thread. Then We will create an example of Thread with the use of join method.
 Java Join method join the next thread at the end of the current thread  After current thread stops execution then next thread executes. Syntax: view plainprint?
1. public void join() throws InterruptedException   2. public void join(long miliseconds) throws InterruptedException  
view plainprint?
1. class JoinDemo extends Thread{   2.  public void run(){   3.   for(int i=1;i<=5;i++){   4.    try{   5.     Thread.sleep(500);   6.    }catch(Exception e){   7.      System.out.println(e);   8.    }   9.    System.out.println("Dinesh on Java "+i);   10.    }   11.   }   12. public static void main(String args[]){   13.  JoinDemo t1 = new JoinDemo();   14.  JoinDemo t2 = new JoinDemo();   15.  JoinDemo t3 = new JoinDemo();   16.  t1.start();   17.  try{   18.   t1.join();   19.  }catch(Exception e){   20.    System.out.println(e);   21.  }   22.    23.  t2.start();   24.  t3.start();   25.  }   26. }   As you can see in the above example,when t1 completes its task then t2 and t3 starts executing. output:
 
view plainprint?
1. //Example of join(long miliseconds) method   2. class JoinDemo extends Thread{   3.  public void run(){   4.   for(int i=1;i<=5;i++){   5.    try{   6.     Thread.sleep(500);   7.    }catch(Exception e){   8.      System.out.println(e);   9.    }   10.    System.out.println("Dinesh on Java "+i);   11.    }   12.   }   13. public static void main(String args[]){   14.  JoinDemo t1 = new JoinDemo();   15.  JoinDemo t2 = new JoinDemo();   16.  JoinDemo t3 = new JoinDemo();   17.  t1.start();   18.  try{   19.   t1.join(1500);   20.  }catch(Exception e){   21.    System.out.println(e);   22.  }   23.    24.  t2.start();   25.  t3.start();   26.  }   27. }   In the above example,when t1 is completes its task for 1500 milliseconds(3 times) then t2 and t3 starts executing. output:

Naming a thread: The Thread class provides methods to change and get the name of a thread. Using getName(), setName(String) and getId() method:
view plainprint?
1. public String getName()//is used to return the name of a thread.   2. public void setName(String name)//is used to change the name of a thread.   3. public long getId()//is used to return the id of a thread.  
view plainprint?
1. class JoinDemo extends Thread{   2.  public void run(){   3.   for(int i=1;i<=5;i++){   4.    try{   5.     Thread.sleep(500);   6.    }catch(Exception e){   7.      System.out.println(e);   8.    }   9.    System.out.println("Running thread is "+Thread.currentThread().getName()+" : "+i);   10.    }   11.   }   12. public static void main(String args[]){   13.  JoinDemo t1 = new JoinDemo();   14.  JoinDemo t2 = new JoinDemo();   15.  JoinDemo t3 = new JoinDemo();   16.  t1.setName("Dinesh on Java");   17.  System.out.println("id of t1:"+t1.getId());   18.  System.out.println("id of t2:"+t2.getId());   19.  System.out.println("id of t3:"+t3.getId());   20.  t1.start();   21.  try{   22.   t1.join(1500);   23.  }catch(Exception e){   24.    System.out.println(e);  
25.  }   26.    27.  t2.start();   28.  t3.start();   29.  }   30. }   The currentThread() method: The currentThread() method returns a reference to the currently executing thread object. output:  
Priority of a Thread
Posted by Dinesh Rajput
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread gets the ready-to-run state according to their priorities. The thread scheduler provides the CPU time to thread of highest priority during ready-to-run state.  3 constants defined in Thread class:
1. public static int MIN_PRIORITY 2. public static int NORM_PRIORITY 3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
When a Java thread is created, it inherits its priority from the thread that created it. At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution. In Java runtime system, preemptive scheduling algorithm is applied. If at the execution time a thread with a higher priority and all other threads are runnable then the runtime system
chooses the new higher priority thread for execution. On the other hand, if two threads of the same priority are waiting to be executed by the CPU then the round-robin algorithm is applied in which the scheduler chooses one of them to run according to their round of time-slice. Thread Scheduler In the implementation of threading scheduler usually applies one of the two following strategies:
Preemptive scheduling ? If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.
Time-Sliced (Round-Robin) Scheduling ? A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.
Example of priority of a Thread: view plainprint?
1. class ThreadPriorityDemo extends Thread{   2.  public void run(){   3.      System.out.println("Running thread is "+Thread.currentThread().getName());   4.      System.out.println("Running thread priority is "+Thread.currentThread().get Priority());   5.   }   6. public static void main(String args[]){   7.    ThreadPriorityDemo t1 = new ThreadPriorityDemo();   8.    ThreadPriorityDemo t2 = new ThreadPriorityDemo();   9.    ThreadPriorityDemo t3 = new ThreadPriorityDemo();   10.    t1.setPriority(Thread.MIN_PRIORITY);   11.    t2.setPriority(Thread.MAX_PRIORITY);   12.    t3.setPriority(Thread.NORM_PRIORITY);   13.    t1.setName("Dinesh on Java");   14.    t2.setName("DAV JavaServices");   15.    t3.setName("dineshonjava.com");   16.    t1.start();   17.    t2.start();   18.    t3.start();   19.  }   20. }    Output:
 
In the above output of program we are observing that the output of same program is vary, its means that the outputs are depends on the OS. JVM can not guaranteed about the scheduling of threads.
Daemon Thread
Posted by Dinesh Rajput
In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.  
In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
Points to remember for Daemon Thread: It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
 Its life depends on user threads.  It is a low priority thread.  User thread is generally meant to run our program code. JVM doesn’t terminate unless all the user thread terminate. On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. WhenJVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code.
For better understanding consider a well known example of Daemon thread: Java Garbage collector. Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.
Why JVM terminates the daemon thread if there is no user thread remaining? The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
Methods for Daemon thread: The java.lang.Thread class provides two methods related to daemon thread 1. public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread. 2. public boolean isDaemon(): is used to check that current is daemon. Example of Daemon thread: view plainprint?
1. class DeamonThread extends Thread{   2.    public void run(){   3.       System.out.println("Name: "+Thread.currentThread().getName());   4.       System.out.println("Daemon: "+Thread.currentThread().isDaemon());   5.    }   6.    7.   public static void main(String[] args){   8.      DeamonThread t1 = new DeamonThread();   9.      DeamonThread t2 = new DeamonThread();   10.      t1.setName("Dinesh on Java");        11.      t1.setDaemon(true);   12.      13.      t1.start();   14.      t2.start();   15.  }   16. }   output:
 
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.
view plainprint?
1. class DeamonThread extends Thread{   2.    public void run(){   3.       System.out.println("Name: "+Thread.currentThread().getName());   4.       System.out.println("Daemon: "+Thread.currentThread().isDaemon());   5.    }   6.    7.   public static void main(String[] args){   8.      DeamonThread t1 = new DeamonThread();   9.      DeamonThread t2 = new DeamonThread();   10.      t1.setName("Dinesh on Java");   11.      t1.start();        12.      t1.setDaemon(true);   13.      14.      t2.start();   15.  }   16. }    Output:  
What is difference between User and Daemon Thread in Java? Java makes a distinction between a user thread and another type of thread known as a daemon thread. The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread. Threads created by a user thread are user thread. JVM doesn't terminates unless all the user thread terminate.
You can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true) on a Thread object. For example, the clock handler thread, the idle thread, the garbage collector thread, the screen updater thread, and the garbage collector thread are all daemon threads. A new created thread inherits the "daemon-status" of the thread that created it unless you explicitly calling setDaemon on that Thread object to change its status.
Note that the setDaemon() method must be called before the thread's start() method is invoked.Once a thread has started executing (i.e., its start() method has been called) its daemon status cannot be changed. To determine if a thread is a daemon thread, use the accessor method isDaemon().  
The difference between these two types of threads is straightforward: If the Java runtime determines that the only threads running in an application are daemon threads (i.e., there are no user threads in existence) the Java runtime promptly closes down the application, effectively stopping all daemon threads dead in their tracks. In order for an application to continue running, it must always have at least one live user thread. In all other respects the Java runtime treats daemon threads and user threads in exactly the same manner. Synchronization in Java Posted by Dinesh Rajput
In this Java synchronization tutorial we will see what is meaning of Synchronization in Java, Why do we need Synchronization in java, what is java synchronized keyword, example of using java synchronized method and blocks and important points about synchronization in Java.
Synchronization   Synchronization is the capability of control the access of multiple threads to any shared resource. Synchronization is better in case we want only one thread can access the shared resource at a time.
Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.
Why use Synchronization? The synchronization is mainly used to
1. To prevent thread interference. 2. To prevent consistency problem.
If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is read only or immutable object you don't need synchronization despite running multiple threads. Same is true with
what threads are doing with object if all the threads are only reading value then you don't require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time.
1) synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race. 2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don't use synchronized or volatile keyword. 3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock at this point it reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.
Types of Synchronization: There are two types of synchronization 1. Process Synchronization 2. Thread Synchronization
Here, we will discuss only thread synchronization.  Thread Synchronization: There are two types of thread synchronization mutual exclusive and inter-thread communication. 1. Mutual Exclusive o Synchronized method. o Synchronized block. o static synchronization. 2. Cooperation (Inter-thread communication) Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: 1. by synchronized method 2. by synchronized block 3. by static synchronization Understanding the concept of Lock Synchronization is built around an internal entity known as the lock or monitor.Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. From Java 5 the package java.util.concurrent.locks contains several lock implementations. Understanding the problem without Synchronization: In this example, there is no synchronization, so output is inconsistent. Let's see the example:
view plainprint?
1. class First   2. {  
3.    public void display(String msg)   4.    {   5.       System.out.print ("["+msg);   6.       try   7.       {   8.          Thread.sleep(500);    9.       }   10.       catch(InterruptedException e)   11.       {   12.          e.printStackTrace();   13.       }   14.       System.out.println ("]");   15.    }   16. }   17.    18. class Second extends Thread   19. {   20.      String msg;   21.      First fobj;   22.      Second (First fp,String str)   23.      {   24.         fobj = fp;   25.         msg = str;   26.         start();   27.      }   28.      public void run()   29.      {   30.         fobj.display(msg);   31.      }   32. }   33.    34. public class WithoutSyncDemo   35. {   36.     public static void main (String[] args)    37.     {   38.        First fnew = new First();   39.        Second ss  = new Second(fnew, "welcome");   40.        Second ss1 = new Second (fnew,"to");   41.        Second ss2 = new Second(fnew, "dineshonjava.com");   42.     }   43. }   Output:  
In the above program, object fnew of class First is shared by all the three running threads(ss, ss1 and ss2) to call the sharedmethod(void display). Hence the result is unsynchronized and such situation is called Race condition.
 Solution by synchronized method:
1. If you declare any method as synchronized, it is known as synchronized method. 2. Synchronized method is used to lock an object for any shared resource. 3. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the method returns. view plainprint?
1. class First   2. {   3.    public synchronized void display(String msg) //synchronized method   4.    {   5.       System.out.print ("["+msg);   6.       try   7.       {   8.          Thread.sleep(500);    9.       }   10.       catch(InterruptedException e)   11.       {   12.          e.printStackTrace();   13.       }   14.       System.out.println ("]");   15.    }   16. }   17.    18. class Second extends Thread   19. {   20.      String msg;   21.      First fobj;   22.      Second (First fp,String str)   23.      {   24.         fobj = fp;   25.         msg = str;   26.         start();   27.      }   28.      public void run()   29.      {   30.         fobj.display(msg);   31.      }   32. }   33.    34. public class WithoutSyncDemo   35. {   36.     public static void main (String[] args)    37.     {   38.        First fnew = new First();   39.        Second ss  = new Second(fnew, "welcome");   40.        Second ss1 = new Second (fnew,"to");   41.        Second ss2 = new Second(fnew, "dineshonjava.com");   42.     }   43. }   output:
 
Solution by synchronized block:
1. If you declare block of shared lines as synchronized, it is known as synchronized block. 2. Synchronized block is used to lock an object for any shared resource. 3. When a thread invokes a code within synchronized block, it automatically acquires the lock for that object and releases it when the synchronized block executed. view plainprint?
1. class First   2. {   3.    public void display(String msg)    4.    {   5.       System.out.print ("["+msg);   6.       try   7.       {   8.          Thread.sleep(500);    9.       }   10.       catch(InterruptedException e)   11.       {   12.          e.printStackTrace();   13.       }   14.       System.out.println ("]");   15.    }   16. }   17.    18. class Second extends Thread   19. {   20.      String msg;   21.      First fobj;   22.      Second (First fp,String str)   23.      {   24.         fobj = fp;   25.         msg = str;   26.         start();   27.      }   28.      public void run()   29.      {   30.         synchronized(fobj){       //Synchronized block   31.             fobj.display(msg);   32.         }   33.      }   34. }   35.    36. public class WithoutSyncDemo   37. {   38.     public static void main (String[] args)    39.     {   40.        First fnew = new First();  
41.        Second ss  = new Second(fnew, "welcome");   42.        Second ss1 = new Second (fnew,"to");   43.        Second ss2 = new Second(fnew, "dineshonjava.com");   44.     }   45. }   output:
Synchronized Keyword: To synchronize above program, we must synchronize access to the shared display() method, making it available to only one thread at a time. This is done by using keyword synchronized with display() method.
view plainprint?
1. synchronized void display (String msg)    
Synchronized block
Posted by Dinesh Rajput
Synchronized block can be used to perform synchronization on any specific resource of the method. Suppose you have 100 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.   Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized method. Points to remember for Synchronized block
1. Synchronized block is used to lock an object for any shared resource. 2. Scope of synchronized block is smaller than the method.
Syntax to use synchronized block view plainprint?
1. synchronized (object reference expression) {    2.    //code block    3.  }  
 Example of synchronized block: Let's see the simple example of synchronized block.
view plainprint?
1. class First   2. {   3.    public synchronized void display(String msg)    4.    {   5.       System.out.print ("["+msg);   6.       try   7.       {   8.          Thread.sleep(500);    9.       }   10.       catch(InterruptedException e)   11.       {   12.          e.printStackTrace();   13.       }   14.       System.out.println ("]");   15.    }   16. }   17.    18. class Second extends Thread   19. {   20.      String msg;   21.      First fobj;   22.      Second (First fp,String str)   23.      {   24.         fobj = fp;   25.         msg = str;   26.         start();   27.      }   28.      public void run()   29.      {      30.         synchronized(fobj){         //synchronized block   31.             fobj.display(msg);   32.          }   33.      }   34. }   35.    36. public class SyncBlockDemo   37. {   38.     public static void main (String[] args)    39.     {   40.        First fnew = new First();   41.        Second ss  = new Second(fnew, "welcome");   42.        Second ss1 = new Second (fnew,"to");   43.        Second ss2 = new Second(fnew, "dineshonjava.com");   44.     }   45. }    output:
 
Static synchronization & non static synchronization Posted by Dinesh Rajput
A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object. If you make any static method as synchronized, the lock will be on the class not on object.
Why we use Static Synchronized Block/Method?  Suppose there are two objects of a shared class(e.g. Account) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. I want no interference between t1 and t3 or t2 and t4. Static synchronization solves this problem.  
The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class
is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods.
For example
view plainprint?
1. class MyClass  {   2.   ...   3.   public synchronized static someMethod() {   4.     ...   5.   }   6.   ...   7. }   It is the equivalent to the following static synchronized block:
view plainprint?
1. synchronized ( MyClass.class ) {   2. ...   3. }   Example of static synchronization In this example we are applying synchronized keyword on the static method to perform static synchronization.
view plainprint?
1. class Account{   2.    3.  synchronized static void showAccount(String accountName){   4.      System.out.println("My account name is "+accountName+" Holder Name is "+Thr ead.currentThread().getName());   5.      try{   6.        Thread.sleep(500);   7.      }catch(Exception e){}   8.    }   9. }   10.    11. class MyThread1 extends Thread{   12.     public void run(){   13.        Account.showAccount("Dineshonjava.com");   14.   }   15. }   16.    17. class MyThread2 extends Thread{   18.     public void run(){   19.        Account.showAccount("Linkedin.com");   20.     }   21. }   22.    23. class MyThread3 extends Thread{   24.     public void run(){   25.        Account.showAccount("Facebook.com");   26.     }   27. }   28.    29. class MyThread4 extends Thread{   30.     public void run(){  
31.        Account.showAccount("Twitter.com");   32.     }   33. }   34.    35. class StaticSyncDemo{   36.     public static void main(String t[]){   37.        MyThread1 t1 = new MyThread1();   38.        MyThread2 t2 = new MyThread2();   39.        MyThread3 t3 = new MyThread3();   40.        MyThread4 t4 = new MyThread4();   41.        t1.setName("DAV JavaServices");   42.        t2.setName("dinesh.rajput");   43.        t3.setName("dineshonjava");   44.        t4.setName("admin@dineshonjava.com");          45.        t1.start();   46.        t2.start();   47.        t3.start();   48.        t4.start();   49.     }   50. }  
output:  
Synchronized block on a class lock: The block synchronizes on the lock of the object denoted by the reference .class. A static synchronized methodshowAccount(String accountName) in class Account is equivalent to the following declaration:
view plainprint?
1. static void showAccount(String accountName) {   2.     synchronized (Account.class) {       // Synchronized block on class A   3.         // ...   4.     }   5. }  
Deadlock in Java
Posted by Dinesh Rajput
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete.  
Simple Deadlock
One of the main problems with threading is Deadlock, two threads are both suspended waiting for the other one to do something. The most common cause of deadlock is two threads both acquiring the same set of (two or more) locks, but in a different order. Consider this code:
view plainprint?
1. Object A = new Object();   2. Object B = new Object();   3.    4. Thread 1:   5.    6. synchronized(A)   7. {                       // <--- preemption   8.     synchronized(B)   9.     {   //...   10.     }   11. }   12.    13. Thread 2:   14.    15. synchronized(B)   16. {   synchronized(A)   17.     {   //...   18.     }   19. }   Here's the deadlock scenario:
 Thread 1 acquires A, but is then preempted for some reason.  Thread 2 wakes up, acquires B, but can't get A because Thread 1 has it, so is suspended.  Thread 1 wakes up, tries to acquire B, but can't because Thread 2 has it, so is suspended.  Both threads are now suspended forever. They're deadlocked.
Example of Deadlock in java: view plainprint?
1. public class DeadLockExample {   2.   public static void main(String[] args) {   3.     final String resource1 = "dineshonjava.com";   4.     final String resource2 = "tutorial";   5.     // t1 tries to lock resource1 then resource2   6.     Thread t1 = new Thread() {   7.       public void run() {   8.           synchronized (resource1) {   9.            System.out.println("Thread 1: locked resource 1");   10.    11.            try {    12.               Thread.sleep(100);   13.            } catch (Exception e) {}   14.    15.            synchronized (resource2) {   16.             System.out.println("Thread 1: locked resource 2");   17.            }   18.          }   19.       }   20.     };   21.    22.     // t2 tries to lock resource2 then resource1   23.     Thread t2 = new Thread() {   24.       public void run() {   25.         synchronized (resource2) {   26.           System.out.println("Thread 2: locked resource 2");   27.    28.           try {    29.               Thread.sleep(100);   30.           } catch (Exception e) {}   31.    32.           synchronized (resource1) {   33.             System.out.println("Thread 2: locked resource 1");   34.           }   35.         }   36.       }   37.     };   38.    39.        40.     t1.start();   41.     t2.start();   42.   }   43. }   44.            output:
 
Because the program has deadlocked, you need to press CTRL-C to end the program. You can see a full thread and monitor cache dump by pressing CTRL-BREAK on a PC .
Inter-thread communication
Posted by Dinesh Rajput
Inter Thread Communication is one of the distinct facility in multi threading application development of java. Inter thread communication concept is one of the specialized form of inter process communication of operating system. In real world Inter Thread communication based applications of java very fastest applications compared to all the applications in java.
Cooperation(Inter-thread communication) is all about making synchronized threads communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:
 wait()  notify()  notifyAll() 1. wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor and call notify. Causes current thread to release the lock and wait until either another thread invokes the notify() method or thenotifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor.                                         Syntax:  view plainprint?
1. public final void wait() throws InterruptedException   2. public final void wait(long timeout)throws InterruptedException   2. notify() wakes up a thread that called wait() on same object. Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: view plainprint?
1. public final void notify()   3. notifyAll() wakes up all the thread that called wait() on same object. Wakes up all threads that are waiting on this object's monitor.  view plainprint?
1. public final void notifyAll()   Difference between wait() and sleep()
wait() sleep()
called from synchronized block no such requirement
monitor is released monitor is not released
awake when notify() or notifyAll() method is called.
not awake when notify() or notifyAll() method is called
not a static method static method
wait() is generally used on condition sleep() method is simply used to put your thread on sleep.
Thread Pooling
Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition is true appropriate action is taken. This waste CPU time.
Deadlock: Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of resources. In the above picture, Thread 1 is holding a resource R1, and need another resource R2 to finish execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of them can finish and are stuck in a deadlock.
 
Example of Inter thread Communication:
view plainprint?
1. class Customer {   2.    int amount=0;   3.    int flag=0;   4.    public synchronized int withdraw(int amount){   5.  System.out.println(Thread.currentThread().getName()+" is going to withdraw");   6.     7.        if(flag==0){   8.            try{   9.   System.out.println("waiting....");   10.   wait();   11.       }catch(Exception e){}   12.  }   13.  this.amount-=amount;   14.  System.out.println("withdraw completed");   15.  return amount;   16.      }   17.    18.      public synchronized void deposit(int amount){   19.  System.out.println(Thread.currentThread().getName()+" is going to  deposit");   20.  this.amount+=amount;   21.  System.out.println("deposit completed");   22.         notifyAll();   23.         flag=1;   24.     }   25.  }   26.    27. public class SyncThreadDemo {   28.     public static void main(String[] args) {   29.  final Customer c = new Customer();   30.     31.  Thread t1 = new Thread(){   32.   public void run(){  
33.    c.withdraw(5000);   34.    System.out.println("After withdraw amount is "+c.amount);   35.                            36.   }   37.    };   38.     39.  Thread t2 = new Thread(){   40.   public void run(){   41.    c.deposit(9000);   42.    System.out.println("After deposit amount is "+c.amount);   43.   }   44.     };   45.    46.  t1.setName("Dinesh");   47.         t2.setName("Sweety");   48.  t1.start();   49.  t2.start();   50.    51.     }   52. }    Output:  
Thread Control in Java
Posted by Dinesh Rajput
While the suspend( ), resume( ), and stop( ) methods defined by Thread class seem to be a perfectly reasonable and convenient approach to managing the execution of threads, they must not be used for new Java programs and obsolete in newer versions of Java.
The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object can be used to control the execution of a thread.
This example is similar to the program in the previous section. However, the deprecated method calls have been removed. Let us consider the operation of this program.
The NewThread class contains a boolean instance variable named suspendFlag, which is used to control the execution of the thread. It is initialized to false by the constructor.
The run( ) method contains a synchronized statement block that checks suspendFlag. If that variable is true, the wait( ) method is invoked to suspend the execution of the thread. The mysuspend( ) method sets suspendFlag to true. The myresume( )method sets suspendFlag to false and invokes notify( ) to
wake up the thread. Finally, the main( ) method has been modified to invoke the mysuspend( ) and myresume( ) methods.
Example:
view plainprint?
1. // Suspending and resuming a thread for Java 2   2. class NewThread implements Runnable {   3.    String name; // name of thread   4.    Thread t;   5.    boolean suspendFlag;   6.    NewThread(String threadname) {   7.       name = threadname;   8.       t = new Thread(this, name);   9.       System.out.println("New thread: " + t);   10.       suspendFlag = false;   11.       t.start(); // Start the thread   12.    }   13.    // This is the entry point for thread.   14.    public void run() {   15.       try {   16.       for(int i = 15; i > 0; i--) {   17.          System.out.println(name + ": " + i);   18.          Thread.sleep(200);   19.          synchronized(this) {   20.             while(suspendFlag) {   21.                wait();   22.             }   23.           }   24.         }   25.       } catch (InterruptedException e) {   26.          System.out.println(name + " interrupted.");   27.       }   28.       System.out.println(name + " exiting.");   29.    }   30.    void mysuspend() {   31.       suspendFlag = true;   32.    }   33.    synchronized void myresume() {   34.       suspendFlag = false;   35.        notify();   36.    }   37. }   38.    39. public class SuspendResume {   40.    public static void main(String args[]) {   41.       NewThread ob1 = new NewThread("One");   42.       NewThread ob2 = new NewThread("Two");   43.       try {   44.          Thread.sleep(1000);   45.          ob1.mysuspend();   46.          System.out.println("Suspending thread One");   47.          Thread.sleep(1000);   48.          ob1.myresume();   49.          System.out.println("Resuming thread One");   50.          ob2.mysuspend();   51.          System.out.println("Suspending thread Two");   52.          Thread.sleep(1000);  
53.          ob2.myresume();   54.          System.out.println("Resuming thread Two");   55.       } catch (InterruptedException e) {   56.          System.out.println("Main thread Interrupted");   57.       }   58.       // wait for threads to finish   59.       try {   60.          System.out.println("Waiting for threads to finish.");   61.          ob1.t.join();   62.          ob2.t.join();   63.       } catch (InterruptedException e) {   64.          System.out.println("Main thread Interrupted");   65.       }   66.       System.out.println("Main thread exiting.");   67.    }   68. }  
Here is the output produced by the above program:
 
Interrupting Java threads
Posted by Dinesh Rajput
Interrupting a thread means stopping what it is doing before it has completed its task, effectively aborting its current operation. Whether the thread dies, waits for new tasks, or goes on to the next step depends on the application.
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling theinterrupt() method performs normal behavior and doesn't interrupt the thread but sets the interrupt
flag to true. Let's first see the methods provided by the Thread class for thread interruption.
The 3 methods provided by the Thread class for interrupting a thread
 public void interrupt()  public static boolean interrupted()  public boolean isInterrupted() Example of interrupting a thread that stops working view plainprint?
1. class InterruptDemo extends Thread{   2.    public void run(){   3.      try{   4.         Thread.sleep(1000);   5.         System.out.println("task");   6.      }catch(InterruptedException e){   7.          throw new RuntimeException("Thread interrupted..."+e);   8.      }   9.    10. }   11.    12. public static void main(String args[]){   13.    InterruptDemo t1 = new InterruptDemo();   14.    t1.start();   15.    try{   16.        t1.interrupt();   17.    }catch(Exception e){   18.      System.out.println("Exception handled "+e);   19.     }   20.    21.   }   22. }    output:  
Example of interrupting a thread that doesn't stop working
view plainprint?
1. class InterruptDemo extends Thread{   2.    public void run(){   3.      try{  
4.         Thread.sleep(1000);   5.         System.out.println("task");   6.      }catch(InterruptedException e){   7.          System.out.println("Exception handled "+e);   8.      }   9.    10. }   11.    12. public static void main(String args[]){   13.    InterruptDemo t1 = new InterruptDemo();   14.    t1.start();   15.    try{   16.        t1.interrupt();   17.    }catch(Exception e){   18.      System.out.println("Exception handled "+e);   19.     }   20.      System.out.println("thread is running...");   21.   }   22. }   output:
Example of interrupting thread that behaves normally If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that can be used to stop the thread by the java programmer later.
view plainprint?
1. class InterruptThread extends Thread{   2.    3.    public void run(){   4.       for(int i=1;i<=5;i++)   5.          System.out.println(i);   6.       }   7.    8.    public static void main(String args[]){   9.       InterruptThread t1 = new InterruptThread();   10.       t1.start();   11.    12.       t1.interrupt();   13.    14.     }   15. }   output:
 What about isInterrupted and interrupted method? The isInterrupted() method returns the interrupted flag either true or false. The static interrupted() method returns the interrupted flag after that it sets the flag to false if it is true.
view plainprint?
1. class InterruptedDemo extends Thread{   2.    3.    public void run(){   4.       for(int i=1;i<=2;i++){   5.          if(Thread.interrupted()){   6.              System.out.println("code for interrupted thread");   7.           }   8.           else{   9.              System.out.println("code for normal thread");   10.           }   11.    12.        }//end of for loop   13.     }   14.    15.     public static void main(String args[]){   16.    17.        InterruptedDemo t1=new InterruptedDemo();   18.        InterruptedDemo t2=new InterruptedDemo();   19.    20.        t1.start();   21.        t1.interrupt();   22.    23.        t2.start();   24.    25.     }   26. }   output:  
Difference between wait() and sleep() Posted by Dinesh Rajput
There are some difference key notes i conclude after working on wait and sleep, first take a look on sample using wait() andsleep():
Example1: using wait() and sleep():
view plainprint?
1. synchronized(HandObject) {   2.     while(isHandFree() == false) {   3.         /* Hand is still busy on happy coding or something else, please wait */   4.         HandObject.wait();   5.     }   6. }   7.    8. /* Get lock ^^, It is my turn, take a cup beer now */   9. while (beerIsAvailable() == false) {   10.     /* Beer is still coming, not available, Hand still hold glass to get beer,  11.        don't release hand to perform other task */   12.     Thread.sleep(5000);   13. }   14.    15. /* Enjoy my beer now ^^ */   16. drinkBeers();   17.    18. /* I have drink enough, now hand can continue with other task: continue coding * /   19. setHandFreeState(true);   20. HandObject.notifyAll();   Let clarity some key notes:
1. Call on: o wait(): Call on current thread that hold HandObject Object o sleep(): Call on Thread execute task get beer (is class method so affect on current running thread) 2. Synchronized: o wait(): when synchronized multi thread access same Object (HandObject) (When need communication between more than one thread (thread execute coding, thread execute get beer) access on same object HandObject ) o sleep(): when waiting condition to continue execute (Waiting beer available) 3. Hold lock: o wait(): release the lock for other object have chance to execute (HandObject is free, you can do other job) o sleep(): keep lock for at least t times (or until interrupt) (My job still not finish, I'm continue hold lock and waiting some condition to continue) 4. Wake-up condition: o wait(): until call notify(), notifyAll() from object o sleep(): until at least time expire or call interrupt view plainprint?
1. synchronized(LOCK) {   2.     Thread.sleep(1000); // LOCK is held   3. }   4.    5.    6. synchronized(LOCK) {   7.     LOCK.wait(); // LOCK is not held   8. }    
It all eventually makes its way down to the OS’s scheduler, which hands out timeslices to processes and threads.
sleep(n) says “I’m done with my timeslice, and please don’t give me another one for at least n milliseconds.” The OS doesn’t even try to schedule the sleeping thread until requested time has passed.
yield() says “I’m done with my timeslice, but I still have work to do.” The OS is free to immediately give the thread another timeslice, or to give some other thread or process the CPU the yielding thread just gave up.
.wait() says “I’m done with my timeslice. Don’t give me another timeslice until someone calls notify().” As with sleep(), the OS won’t even try to schedule your task unless someone calls notify() (or one of a few other wakeup scenarios occurs).
Threads also lose the remainder of their timeslice when they perform blocking IO and under a few other circumstances. If a thread works through the entire timeslice, the OS forcibly takes control roughly as if yield() had been called, so that other processes can run.
You rarely need yield(), but if you have a compute-heavy app with logical task boundaries, inserting a yield() might improve system responsiveness (at the expense of time — context switches, even just to the OS and back, aren’t free). Measure and test against goals you care about, as always.  Difference between yield and sleep in java Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.
Java Collection Framework
Posted by Dinesh Rajput
Java collections are one of the most commonly used data-structures by all Java professionals. But are you using the right collection class that would best suits your need. Most programmers usually use Vectors, ArrayList, HashMap or the Hashtable. There are many other collection classes available with the JDK that you can use instead of re-inventing logic to suite your needs.
We will be trying to understand the different types of classes and when each Collection class could be used. We wouldn't be looking into the implementation details of any collection, for that please refer the latest Java Collection API docs.
 The Core Collection Framework Interfaces The core collection frameworks are depicted in the following image.  
The main type of collections are:
 Sets  Lists  Queues  Maps Maps are not an integral part of the Collection framework, but they are still considered as Collection because of their capability to store and manipulate data as collection of objects.
Sorted Sets and Sorted Maps are basically a sorted version of Sets and Maps. Hierarchy of Collection Framework Let us see the hierarchy of collection framework.The java.util package contains all the classes and interfaces for Collection framework.

Goals for Java Collections: The collections framework was designed to meet several goals.
 The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are highly efficient.  The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.  Extending and/or adapting a collection had to be easy. Commonly used methods of Collection interface: There are many methods declared in the Collection interface. They are as follows:  1. public boolean add(object element): is used to insert an element in this collection. 2. public boolean addAll(collection c): is used to insert the specified collection elements in the invoking collection. 3. public boolean remove(object element): is used to delete an element from this collection.
4. public boolean removeAll(Collection c): is used to delete all the elements of specified collection from the invoking collection. 5. public boolean retainAll(Collection c): is used to delete all the elements of invoking collection except the specified collection. 6. public int size(): return the total number of elements in the collection. 7. public void clear(): removes the total no of element from the collection. 8. public boolean contains(object element): is used to search an element. 9. public boolean containsAll(collection c): is used to search the specified collection in this collection. 10. public Iterator iterator(): returns an iterator. Iterator interface Iterator interface provides the facility of iterating the elements in forward direction only. Methods of Iterator interface There are only three methods in the Iterator interface. They are: 1. public boolean hasNext() it returns true if iterator has more elements. 2. public object next() it returns the element and moves the cursor pointer to the next element. 3. public void remove() it removes the last elements returned by the iterator. It is rarely used.
What we will learn in Collection Framework ?
 ArrayList class  LinkedList class  ListIterator interface  HashSet class  LinkedHashSet class  TreeSet class  Difference between TreeSet & HashSet  PriorityQueue class  Map interface  HashMap class  How does work HashMap?  Difference between TreeMap vs HashMap  LinkedHashMap class  TreeMap class  Hashtable class  Difference between HashMap and HashTable in Java  Sorting  Comparable interface  Comparator interface
 References http://www.janeve.me/articles/which-java-collection-to-use  
ArrayList Class in Java Collection Framework Posted by Dinesh Rajput
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
ArrayList class
 ArrayList class extends AbstractList class and implements the List interface.  ArrayList supports dynamic array that can grow as needed. ArrayList has three constructors. view plainprint?
1. //constructor builds an empty array list   2. ArrayList()   3. //The following constructor builds an array list that is initialized with the el ements of the collection c.   4. ArrayList( Collection C )   5. /*The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the el ements.  6.   7. The capacity grows automatically as elements are added to an array list.*/   8. ArrayList( int capacity )    ArrayLists are created with an initial size, when this size is exceeded, it gets enlarged automatically.  It can coontain Duplicate elements and maintains the insertion order.  ArrayLists are not synchronized.
 
Methods in the ArrayList Class:
Apart from the methods inherited from its parent classes, ArrayList defines following methods:
SN Methods with Description
1
void add(int index, Object element) Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2
boolean add(Object o)  Appends the specified element to the end of this list.
3
boolean addAll(Collection c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
4
boolean addAll(int index, Collection c)  Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5
void clear()  Removes all of the elements from this list.
6
Object clone()  Returns a shallow copy of this ArrayList.
7
boolean contains(Object o)  Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8
void ensureCapacity(int minCapacity)  Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
9
Object get(int index)  Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
10
int indexOf(Object o)  Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
11
int lastIndexOf(Object o) Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
12
Object remove(int index)  Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13
protected void removeRange(int fromIndex, int toIndex)  Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
14
Object set(int index, Object element)  Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
15
int size()  Returns the number of elements in this list.
16
Object[] toArray()  Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
17 Object[] toArray(Object[] a)  Returns an array containing all of the elements in this list in the correct order; the runtime type of
the returned array is that of the specified array.
18
void trimToSize()  Trims the capacity of this ArrayList instance to be the list's current size.  
Example of ArrayList:
view plainprint?
1. import java.util.*;   2.    3. public class ArrayListDemo {   4.    public static void main(String args[]) {   5.       // create an array list   6.       ArrayList list = new ArrayList();   7.       System.out.println("Initial size of list: " + list.size());   8.    9.       // add elements to the array list   10.       list.add("Dinesh");   11.       list.add("Sweety");   12.       list.add("Adesh");   13.       list.add("Vinesh");   14.       list.add("Mom");   15.       list.add("DAD");   16.          17.       System.out.println("Size of list after additions: " + list.size());   18.    19.       // display the array list   20.       System.out.println("Contents of list: " + list);   21.         22.        System.out.println("Iterating list");   23.        Iterator itr = list.iterator();   24.        while(itr.hasNext()){   25.            System.out.println(itr.next());   26.        }   27.    }   28. }   output:

Two ways to iterate the elements of collection:
1. By Iterator interface. 2. By for-each loop.
Iterating the elements of Collection by for-each loop: view plainprint?
1. import java.util.*;   2.    3. public class ArrayListDemo {   4.    public static void main(String args[]) {   5.       // create an array list   6.       ArrayList list = new ArrayList();   7.          8.       // add elements to the array list   9.       list.add("Dinesh");   10.       list.add("Sweety");   11.       list.add("Adesh");   12.       list.add("Vinesh");   13.       list.add("Mom");   14.       list.add("DAD");   15.       System.out.println("Iterating list using for each loop");   16.       for(Object obj : list){   17.            System.out.println(obj);   18.       }   19.    }   20. }   output:

Storing User-Defined classes: In the above example we are storing only string object in ArrayList collection. But You can store any type of object, including object of class that you create in Collection classes. Example of storing User-Defined object
Employee class
view plainprint?
1. class Employee   2. {   3.     String firstName;   4.     String lastName;   5.     String phone;   6.    7.     public Employee(String firstName,String lastName,String phone)    8.     {   9.         this.firstName = firstName ;   10.         this.lastName = lastName;   11.         this.phone = phone;   12.     }   13.        14.     public String toString()   15.     {   16.         return firstName +" "+lastName +" ("+phone +") ";   17.     }   18. }   Storing Employee class
view plainprint?
1. public class EmployeeListDemo   2. {   3.        4.    public static void main(String[] args)    5.    {   6.        Employee e1 = new Employee("Dinesh", "Rajput","999100091");   7.        Employee e2 = new Employee("Sandeep", "Sharma","998392819");   8.        Employee e3 = new Employee("Vinesh", "Kohli","998131319");   9.           10.       ArrayList al = new ArrayList();    11.       al.add(e1);   12.       al.add(e2);  
13.       al.add(e3);   14.       System.out.println(al);   15.    }   16.        17. }   output:
Example of addAll(Collection c) method:
view plainprint?
1. import java.util.*;   2. class SimpleListDemo{   3.  public static void main(String args[]){   4.     5.   ArrayList al = new ArrayList();   6.   al.add("Dinesh");   7.   al.add("Anamika");   8.   al.add("Sweety");   9.      10.   ArrayList al2 = new ArrayList();   11.   al2.add("Adesh");   12.   al2.add("Vinesh");   13.      14.   al.addAll(al2);     15.    16.   Iterator itr=al.iterator();   17.   while(itr.hasNext()){   18.    System.out.println(itr.next());   19.   }   20.  }   21. }   output:
 Example of removeAll() method:
view plainprint?
1. import java.util.*;   2. class SimpleListDemo{   3.  public static void main(String args[]){   4.     5.   ArrayList al = new ArrayList();   6.   al.add("Dinesh");   7.   al.add("Anamika");   8.   al.add("Sweety");   9.      10.   ArrayList al2 = new ArrayList();   11.   al2.add("Anamika");   12.   al2.add("Vinesh");   13.    14.   al.removeAll(al2);     15.    16.   Iterator itr=al.iterator();   17.   while(itr.hasNext()){   18.    System.out.println(itr.next());   19.   }   20.  }   21. }   output:  
Example of retainAll() method:
view plainprint?
1. import java.util.*;   2. class SimpleListDemo{   3.  public static void main(String args[]){   4.     5.   ArrayList al = new ArrayList();   6.   al.add("Dinesh");   7.   al.add("Anamika");   8.   al.add("Sweety");   9.      10.   ArrayList al2 = new ArrayList();   11.   al2.add("Anamika");   12.   al2.add("Vinesh");   13.   System.out.println("iterating the elements after retaining the elements of al2 ...");  
14.   al.retainAll(al2);     15.    16.   Iterator itr=al.iterator();   17.   while(itr.hasNext()){   18.    System.out.println(itr.next());   19.   }   20.  }   21. }   output:  
LinkedList class in Collection Posted by Dinesh Rajput
 LinkedList class extends AbstractSequentialList and implements List, Deque and Queue interface.  It can be used as List, stack or Queue as it implements all the related interfaces.  It can contain duplicate elements and is not synchronized.  maintains insertion order.  not synchronized.  No random access.  manipulation fast because no shifting needs to be occurred. The LinkedList class supports two constructors:  view plainprint?
1. //The first constructor builds an empty linked list:   2. LinkedList( )   3.    4. //The following constructor builds a linked list that is initialized with the el ements of the collection c.   5. LinkedList(Collection c)    
Methods in LinkedList:  Apart from the methods inherited from its parent classes, LinkedList defines following methods:

SN Methods with Description
1
void add(int index, Object element) Inserts the specified element at the specified position index in this list. ThrowsIndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2
boolean add(Object o)  Appends the specified element to the end of this list.
3
boolean addAll(Collection c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
4
boolean addAll(int index, Collection c)  Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5
void addFirst(Object o) Inserts the given element at the beginning of this list.
6
void addLast(Object o)  Appends the given element to the end of this list.
7
void clear()  Removes all of the elements from this list.
8
Object clone()  Returns a shallow copy of this LinkedList.
9
boolean contains(Object o)  Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
10
Object get(int index)  Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
11
Object getFirst()  Returns the first element in this list. Throws NoSuchElementException if this list is empty.
12
Object getLast()  Returns the last element in this list. Throws NoSuchElementException if this list is empty.
13
int indexOf(Object o)  Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
14
int lastIndexOf(Object o) Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
15
ListIterator listIterator(int index) Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
16
Object remove(int index)  Removes the element at the specified position in this list. Throws NoSuchElementException if this list is empty.
17
boolean remove(Object o)  Removes the first occurrence of the specified element in this list. ThrowsNoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
18
Object removeFirst()  Removes and returns the first element from this list. Throws NoSuchElementException if this list is empty.
19
Object removeLast()  Removes and returns the last element from this list. Throws NoSuchElementException if this list is empty.
20
Object set(int index, Object element)  Replaces the element at the specified position in this list with the specified element. ThrowsIndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
21
int size()  Returns the number of elements in this list.
22
Object[] toArray()  Returns an array containing all of the elements in this list in the correct order. ThrowsNullPointerException if the specified array is null.
23
Object[] toArray(Object[] a)  Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
 Example of LinkedList:
view plainprint?
1. import java.util.*;   2.    3. public class LinkedListDemo {   4.    5.    public static void main(String args[]) {   6.       // create a linked list   7.       LinkedList ll = new LinkedList();   8.       // add elements to the linked list   9.       ll.add("F");   10.       ll.add("B");   11.       ll.add("D");   12.       ll.add("E");   13.       ll.add("C");   14.       ll.addLast("Z");   15.       ll.addFirst("A");   16.       ll.add(1, "A2");   17.       System.out.println("Original contents of ll: " + ll);   18.    19.       // remove elements from the linked list   20.       ll.remove("F");   21.       ll.remove(2);   22.       System.out.println("Contents of ll after deletion: "   23.        + ll);   24.          25.       // remove first and last elements   26.       ll.removeFirst();   27.       ll.removeLast();   28.       System.out.println("ll after deleting first and last: "   29.        + ll);   30.    31.       // get and set a value   32.       Object val = ll.get(2);   33.       ll.set(2, (String) val + " Changed");   34.       System.out.println("ll after change: " + ll);   35.    }   36. }    output:
 
ListIterator interface in collection Posted by Dinesh Rajput
An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). Accessing a Collection To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection.
 Using Iterator interface  Using ListIterator interface  Using for-each loop Accessing elements using Iterator: Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator. The Methods Declared by Iterator:
SN Methods with Description
1
boolean hasNext( ) Returns true if there are more elements. Otherwise, returns false.
2
Object next( ) Returns the next element. Throws NoSuchElementException if there is not a next element.
3
void remove( ) Removes the current element. Throws IllegalStateException if an attempt is made to callremove( ) that is not preceded by a call to next( ).
view plainprint?
1. import java.util.*;   2. class TestIterator   3. {   4.  public static void main(String[] args)   5.  {   6.   ArrayList ar = new ArrayList();   7.   ar.add("dinesh");   8.   ar.add("anamika");   9.   ar.add("adesh");   10.   ar.add("vinesh");   11.    12.  Iterator it = ar.iterator();     //Declaring Iterator   13.   while(it.hasNext())   14.   {     15.    System.out.print(it.next()+" ");   16.   }   17.  }   18. }   output:
Accessing element using ListIterator: ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.
view plainprint?
1. import java.util.*;   2. class TestIterator   3. {   4.  public static void main(String[] args)   5.  {   6.   ArrayList ar = new ArrayList();   7.   ar.add("dinesh");   8.   ar.add("anamika");   9.   ar.add("adesh");   10.   ar.add("vinesh");   11.    12.    ListIterator litr = ar.listIterator();  
13.    while(litr.hasNext())                 //In forward direction   14.    {   15.      System.out.print(litr.next()+" ");   16.    }   17.     System.out.println();   18.     while(litr.hasPrevious())             //In backward direction   19.     {   20.       System.out.print(litr.previous()+" ");   21.     }   22.   }   23. }   Output:  
The Methods Declared by ListIterator:
SN Methods with Description
1
void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next( ).
2
boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false.
3
boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false.
4
Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element.
5
int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list.
6
Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
7
int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1.
8
void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
9
void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).
Using for-each loop for-each version of for loop can also be used for traversing each element of a collection. But this can only be used if we don't want to modify the contents of a collection and we don't want any reverse access.  for-each loop can cycle through any collection of object that implements Iterable interface. view plainprint?
1. import java.util.*;   2. class TestIterator   3. {   4.  public static void main(String[] args)   5.  {   6.     ArrayList ar = new ArrayList();   7.     ar.add("dinesh");   8.     ar.add("anamika");   9.     ar.add("adesh");   10.     ar.add("vinesh");   11.    12.      for(Object str : ls)   13.      {   14.        System.out.print(str+" ");   15.      }   16.   }   17. }   output:  
HashSet class in collection
Posted by Dinesh Rajput
A HashSet is a collection set that neither allows duplicate elements nor order or position its elements.
This class implements the Set interface and extends AbstractSet. It creates a collection that uses a hash table for storage. Hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as an index at which the data associated with the key is stored. The transformation of key into
its hash code is performed automatically. HashSet is not synchronized. It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.  
Constructor in HashSet: The HashSet class supports four constructors. The first form constructs a default hash set:
view plainprint?
1. HashSet( );   2. //The following constructor form initializes the hash set by using the elements of c.   3. HashSet(Collection c);   4.    5. //The following constructor form initializes the capacity of the hash set to cap acity.   6. //The capacity grows automatically as elements are added to the Hash.   7. HashSet(int capacity);   8.    9. //The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its //arguments:   10. HashSet(int capacity, float fillRatio);   11. /*Here the fill ratio must be between 0.0 and 1.0, and it determines how full th e hash set can be before it is resized upward. Specifically, when the number of element s is greater than the capacity of the hash set multiplied by its fill ratio, the hash s et is expanded*/  
 Methods in HashSet: Apart from the methods inherited from its parent classes, HashSet defines following methods:
SN Methods with Description
1
boolean add(Object o)  Adds the specified element to this set if it is not already present.
2
void clear()  Removes all of the elements from this set.
3
Object clone()  Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
4
boolean contains(Object o) Returns true if this set contains the specified element
5
boolean isEmpty()  Returns true if this set contains no elements.
6
Iterator iterator()  Returns an iterator over the elements in this set.
7
boolean remove(Object o)  Removes the specified element from this set if it is present.
8
int size()  Returns the number of elements in this set (its cardinality).
Example: The following program illustrates several of the methods supported by HashSet:
view plainprint?
1. import java.util.*;   2. public class HashSetDemo {   3.    4.    public static void main(String args[]) {   5.       // create a hash set   6.       HashSet hs = new HashSet();   7.       // add elements to the hash set   8.       hs.add("B");   9.       hs.add("A");   10.       hs.add("D");   11.       hs.add("E");   12.       hs.add("C");  
13.       hs.add("F");   14.       System.out.println(hs);   15.    }   16. }   Output:  
Example Duplicate Value adding to HashSet: The following program illustrates several of the methods supported by HashSet:
view plainprint?
1. import java.util.*;   2. public class HashSetDemo {   3.    4.    public static void main(String args[]) {   5.       // create a hash set   6.       HashSet hs = new HashSet();   7.       // add elements to the hash set   8.       hs.add("B");   9.       hs.add("A");   10.       hs.add("B");   11.       hs.add("E");   12.       hs.add("F");   13.       hs.add("F");   14.       System.out.println(hs);   15.    }   16. }   Output:  
Adding User Define Object to the HashSet: To understand the duplication with objects see the below example.
The Person class has the attributes as age and name. and the class has getter/setter methods of its attributes, and the equalsand hashCode method has been overridden in order to check the equality of attributes.
view plainprint?
1. import java.util.HashSet;   2.     3. public class HashSetExample {   4.     public static void main(String[] args) {   5.         HashSet<Person> set = new HashSet<Person>();   6.         set.add(new Person(27, "DINESH"));   7.         set.add(new Person(27, "DINESH"));   8.         set.add(new Person(24, "SWEETY"));   9.         set.add(new Person(24, "ANAMIKA"));   10.         set.add(new Person(24, "ANAMIKA"));   11.         System.out.println("The size of set of person is : " + set.size());   12.         System.out.println("The elements of set of person is : " + set);   13.     }   14. }   15.     16. class Person {   17.     int age;   18.     String name;   19.     20.     public Person(int age, String name) {   21.         super();   22.         this.age = age;   23.         this.name = name;   24.     }   25.     26.     public int getAge() {   27.         return age;   28.     }   29.     30.     public void setAge(int age) {   31.         this.age = age;   32.     }   33.     34.     public String getName() {   35.         return name;   36.     }   37.     38.     public void setName(String name) {   39.         this.name = name;   40.     }   41.     42.     @Override   43.     public int hashCode() {   44.         final int prime = 31;   45.         int result = 1;   46.         result = prime * result + age;   47.         result = prime * result + ((name == null) ? 0 : name.hashCode());   48.         return result;   49.     }   50.     51.     @Override   52.     public boolean equals(Object obj) {   53.         if (this == obj)   54.             return true;   55.         if (obj == null)   56.             return false;   57.         if (getClass() != obj.getClass())   58.             return false;   59.         Person other = (Person) obj;   60.         if (age != other.age)   61.             return false;  
62.         if (name == null) {   63.             if (other.name != null)   64.                 return false;   65.         } else if (!name.equals(other.name))   66.             return false;   67.         return true;   68.     }   69.       70.    public String toString(){   71.  return "\n Person {name: "+this.name+" age: "+this.age+"}";   72.    }   73. }    output:  
Please note this HashSet implementation is not synchronized, To get the synchronized set you should use the Collections utility class method as. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet() method. This is best done at creation time, to prevent accidental unsynchronized access to the set:
view plainprint?
1. Set s = Collections.synchronizedSet(new HashSet(...));  
LinkedHashSet Class in Collection Posted by Dinesh Rajput
view plainprint?
1. public class LinkedHashSet<E>   2. extends HashSet<E>   3. implements Set<E>, Cloneable, Serializable  
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs fromHashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering,which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is reinserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)  
This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.
A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as forHashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.  
Note that this implementation is not synchronized. If multiple threads access a linked hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using theCollections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:
view plainprint?
1. Set s = Collections.synchronizedSet(new LinkedHashSet(...));   Constructor Detail: LinkedHashSet() Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75). LinkedHashSet(Collection c) Constructs a new linked hash set with the same elements as the specified collection. Constructs a new linked hash set with the same elements as the specified collection. The linked hash set is created with an initial capacity sufficient to hold the elements in the specified collection and the default load factor (0.75). LinkedHashSet(int initialCapacity) Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75). LinkedHashSet(int initialCapacity, float loadFactor) Constructs a new, empty linked hash set with the specified initial capacity and load factor. Constructs a new, empty linked hash set with the specified initial capacity and load factor. Parameters: initialCapacity - the initial capacity of the linked hash set loadFactor - the load factor of the linked hash set  Example:
view plainprint?
1. import java.util.*;   2.    3. public class LinkedHashSetDemo {   4.    5.    public static void main(String args[]) {   6.       // create a hash set   7.       LinkedHashSet hs = new LinkedHashSet();   8.       // add elements to the hash set   9.       hs.add("B");   10.       hs.add("A");   11.       hs.add("D");   12.       hs.add("E");   13.       hs.add("C");   14.       hs.add("F");   15.       System.out.println(hs);   16.    }   17. }   output:
 Example of LinkedHashSet class with duplicate value:
view plainprint?
1. import java.util.*;   2.    3. public class LinkedHashSetDemo {   4.    5.    public static void main(String args[]) {   6.       // create a hash set   7.       LinkedHashSet hs = new LinkedHashSet();   8.       // add elements to the hash set   9.       hs.add("Dinesh");   10.       hs.add("Anamika");   11.       hs.add("Sweety");   12.       hs.add("Dinesh");   13.       hs.add("Sweety");   14.       hs.add("RAJ");   15.       System.out.println(hs);   16.    }   17. }   output:  
TreeSet Class in Collection
Posted by Dinesh Rajput
view plainprint?
1. public class TreeSet<E>   2. extends AbstractSet<E>   3. implements NavigableSet<E>, Cloneable, Serializable   A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparatorprovided at set creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. This is so because the Set interface is defined in terms of the equals operation, but aTreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.  
Note that this implementation is not synchronized. If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using theCollections.synchronizedSortedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:
view plainprint?
1. SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));   TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.  
The TreeSet class supports four constructors. The first form constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements:
view plainprint?
1. TreeSet( )   2. //The second form builds a tree set that contains the elements of c.  
3. TreeSet(Collection c)   4.    5. //The third form constructs an empty tree set that will be sorted according to t he comparator specified by comp.   6. TreeSet(Comparator comp)   7.    8. //The fourth form builds a tree set that contains the elements of ss:   9. TreeSet(SortedSet ss)   Methods in TreeSet:
SN Methods with Description
1
void add(Object o) Adds the specified element to this set if it is not already present.
2
boolean addAll(Collection c)  Adds all of the elements in the specified collection to this set.
3
void clear()  Removes all of the elements from this set.
4
Object clone() Returns a shallow copy of this TreeSet instance.
5
Comparator comparator() Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering.
6
boolean contains(Object o)  Returns true if this set contains the specified element.
7
Object first()  Returns the first (lowest) element currently in this sorted set.
8
SortedSet headSet(Object toElement) Returns a view of the portion of this set whose elements are strictly less than toElement.
9
boolean isEmpty()  Returns true if this set contains no elements.
10
Iterator iterator()  Returns an iterator over the elements in this set.
11
Object last()  Returns the last (highest) element currently in this sorted set.
12
boolean remove(Object o)  Removes the specified element from this set if it is present.
13
int size()  Returns the number of elements in this set (its cardinality).
14
SortedSet subSet(Object fromElement, Object toElement)  Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
15
SortedSet tailSet(Object fromElement)  Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
Example of TreeSet class: The following program illustrates several of the methods supported by this collection:
view plainprint?
1. import java.util.*;   2.    3. public class TreeSetDemo {   4.    5.    public static void main(String args[]) {   6.       // Create a tree set   7.       TreeSet ts = new TreeSet();   8.       // Add elements to the tree set   9.       ts.add("C");   10.       ts.add("A");   11.       ts.add("B");   12.       ts.add("E");   13.       ts.add("F");   14.       ts.add("D");   15.       System.out.println(ts);   16.    }   17. }   output:  
Example of TreeSet adding duplicate value:
view plainprint?
1. import java.util.*;  
2.    3. public class TreeSetDemo {   4.    5.    public static void main(String args[]) {   6.       // Create a tree set   7.       TreeSet ts = new TreeSet();   8.       // Add elements to the tree set   9.       ts.add("Dinesh");   10.       ts.add("Anamika");   11.       ts.add("Sweety");   12.       ts.add("Anamika");   13.       ts.add("Sweety");   14.       ts.add("Raj");   15.       System.out.println(ts);   16.    }   17. }   output:  
Difference between HashSet and TreeSet in Java Posted by Dinesh Rajput
Several difference between HashSet and TreeSet are similar to what we discussed as difference between TreeMap andHashMap. Anyway Set and Map are two completely different interface so we will revisit those differences here. Probably most important difference between HashSet and TreeSet is the performance. HashSet is faster than TreeSet which means if you need performance use HashSet but HashSet doesn't provide any kind of ordering so if you need ordering then you need to switch toTreeSet which provides sorting of keys. Sorting can be natural order defined by Comparable interface or any particular order defined by Comparator interface in Java. Apart from differences between HashSet and TreeSet there are some common things between them. let's see what is common between HashSet and TreeSet in Java. 1) First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet and should be preferred choice if sorting of element is not required.
2) Second difference between HashSet and TreeSet is that HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throwjava.lang.NullPointerException as shown in below  example :
view plainprint?
1. import java.util.*;   2.    3. public class TreeSetHashSet {   4.    5.    public static void main(String args[]) {   6.       HashSet<String> hashSet = new HashSet<String>();    7.       hashSet.add("dineshonjava");    8.       hashSet.add(null);    9.            10.       TreeSet<String> treeSet = new TreeSet<String>();    11.       treeSet.add("dineshonjava");    12.       treeSet.add(null); //Java.lang.NullPointerException    13.    }   14. }   output:  
3) Another significant difference between HashSet and TreeSet is that , HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java.
4) One more difference between HashSet and TreeSet which is worth remembering is that HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose. if equals() andcompareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, than it will break contract of Set interface and will allow duplicates in Set implementations like TreeSet
5) Now most important difference between HashSet and TreeSet is ordering. HashSet doesn't guaranteed any order while TreeSetmaintains objects in Sorted order defined by either Comparable or Comparator method in Java. What is common in HashSet and TreeSet in Java As I said there are lot of things which are common between HashSet and TreeSet in Java, let’s  have a look :
1)Both HashSet and TreeSet implements java.util.Set interface which means they follow contract of Set interface and doesn't allow any duplicates.
2)Both HashSet and TreeSet are not thread-safe and not synchronized. Though you can make them synchronized by usingCollections.synchronizedSet() method.
3) Third similarity between TreeSet and HashSet is that, Iterator of both classes are fail-fast in nature. They will throwConcurrentModificationException if Iterator is modified once Iterator is created. this is not guaranteed and application code should not rely on this code but Java makes best effort to fail as soon as it detects structural change in underlying Set.
Map interface in Collection
Posted by Dinesh Rajput
The Map interface is not an extension of Collection interface. Instead the interface starts of it’s own interface hierarchy, for maintaining key-value associations. The interface describes a mapping from keys to values, without duplicate keys, by definition.
The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.  
 void clear()  Removes all mappings from this map (optional operation).
 boolean containsKey(Object key)  Returns true if this map contains a mapping for the specified key.
 boolean containsValue(Object value)  Returns true if this map maps one or more keys to the specified value.
 Set entrySet()  Returns a set view of the mappings contained in this map.
 boolean equals(Object o)  Compares the specified object with this map for equality.
 Object get(Object key)  Returns the value to which this map maps the specified key.
 int hashCode()  Returns the hash code value for this map.
 boolean isEmpty()  Returns true if this map contains no key-value mappings.
 Set keySet()  Returns a set view of the keys contained in this map.
 Object put(Object key, Object value)  Associates the specified value with the specified key in this map (optional
operation).
 void putAll(Map t)  Copies all of the mappings from the specified map to this map (optional operation).
 Object remove(Object key)  Removes the mapping for this key from this map if it is present (optional operation).
 int size()  Returns the number of key-value mappings in this map.
 Collection values()  Returns a collection view of the values contained in this map.
The interface methods can be broken down into three sets of operations: altering, querying and providing alternative views  
The alteration operation allows you to add and remove key-value pairs from the map. Both the key and value can be null. However you should not add a Map to itself as a key or value.
Object put(Object key, Object value)  Object remove(Object key)  void putAll(Map t)  void clear()  
The query operations allow you to check on the contents of the map Object get(Object key)  boolean containsKey(Object key)  boolean containsValue(Object value)  int size() boolean isEmpty()  
The set methods allow you to work with the group ofkeys or values as a collection Set keySet()  Collection values()  Set entrySet()  HashMap class in collection framework Posted by Dinesh Rajput
1. HashMap class extends AbstractMap and implements Map interface. 2. It uses a hashtable to store the map. This allows the execution time of get() and put() to remain same. 3. HashMap has four constructor. view plainprint?
1. HashMap()   2. HashMap(Map< ? extends k, ? extends V> m)   3. HashMap(int capacity)   4. HashMap(int capacity, float fillratio)   4. HashMap does not maintain order of its element. Hierarchy of HashMap class:
SN Methods with Description
1
void clear()  Removes all mappings from this map.
2
Object clone()  Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
3
boolean containsKey(Object key)  Returns true if this map contains a mapping for the specified key.
4
boolean containsValue(Object value)  Returns true if this map maps one or more keys to the specified value.
5
Set entrySet()  Returns a collection view of the mappings contained in this map.
6
Object get(Object key)  Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key.
7
boolean isEmpty() Returns true if this map contains no key-value mappings.
8
Set keySet()  Returns a set view of the keys contained in this map.
9
Object put(Object key, Object value) Associates the specified value with the specified key in this map.
10
putAll(Map m)  Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
11
Object remove(Object key)  Removes the mapping for this key from this map if present.
12
int size()  Returns the number of key-value mappings in this map.
13
Collection values()  Returns a collection view of the values contained in this map.
Example of HashMap class:
view plainprint?
1. import java.util.*;   2. class Simple{   3.  public static void main(String args[]){   4.     5.   HashMap hm=new HashMap();   6.    7.   hm.put(100,"Dinesh");   8.   hm.put(101,"Sweety");   9.   hm.put(102,"Nimmo");   10.    11.   Set set=hm.entrySet();   12.   Iterator itr=set.iterator();   13.    14.   while(itr.hasNext()){   15.    Map.Entry m=(Map.Entry)itr.next();   16.    System.out.println(m.getKey()+" "+m.getValue());   17.   }   18.  }   19. }    
Output: 102 Dinesh 100 Sweety 101 Nimmo  
How does java Hashmap work internally Posted by Dinesh Rajput What is Hashing? Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:
Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.
Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.
HashMap is an array of Entry objects: Consider HashMap as just an array of objects.
Have a look what this Object is:
view plainprint?
1. static class Entry<K,V> implements Map.Entry<K,V> {  
2.         final K key;   3.         V value;   4.         Entry<K,V> next;   5.         final int hash;   6. ...    7. }  
Each Entry object represents key-value pair. Field next refers to other Entry object if a bucket has more than 1 Entry.
Sometimes it might happen that hashCodes for 2 different objects are the same. In this case 2 objects will be saved in one bucket and will be presented as LinkedList. The entry point is more recently added object. This object refers to other object with next field and so one. Last entry refers to null. When you create HashMap with default constructor
view plainprint?
1. HashMap hashMap = new HashMap();   Array is gets created with size 16 and default 0.75 load balance.
 
Adding a new key-value pair
1. Calculate hashcode for the key 2. Calculate position hash % (arrayLength-1)) where element should be placed(bucket number) 3. If you try to add a value with a key which has already been saved in HashMap, then value gets overwritten. 4. Otherwise element is added to the bucket. If bucket has already at least one element - a new one is gets added and placed in the first position in the bucket. Its next field refers to the old element. Deletion:
1. Calculate hashcode for the given key 2. Calculate bucket number (hash % (arrayLength-1)) 3. Get a reference to the first Entry object in the bucket and by means of equals method iterate over all entries in the given bucket. Eventually we will find correct Entry. If desired element is not found - return null What put() method actually does: Before going into put() method’s implementation, it is very important to learn that instances of Entry class are stored in an array.HashMap class defines this variable as:
view plainprint?
1. /**  2.      * The table, resized as necessary. Length MUST Always be a power of two.  3.      */   4.     transient Entry[] table;   Now look at code implementation of put() method:
view plainprint?
1. /**  2.   * Associates the specified value with the specified key in this map. If the  3.   * map previously contained a mapping for the key, the old value is  4.   * replaced.  5.   *  6.   * @param key  7.   *            key with which the specified value is to be associated  8.   * @param value  9.   *            value to be associated with the specified key  10.   * @return the previous value associated with <tt>key</tt>, or <tt>null</tt>  11.   *         if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return  12.   *         can also indicate that the map previously associated  13.   *         <tt>null</tt> with <tt>key</tt>.)  14.   */   15.  public V put(K key, V value) {   16.   if (key == null)   17.    return putForNullKey(value);   18.   int hash = hash(key.hashCode());   19.   int i = indexFor(hash, table.length);   20.   for (Entry<k , V> e = table[i]; e != null; e = e.next) {   21.    Object k;   22.    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {   23.     V oldValue = e.value;   24.     e.value = value;   25.     e.recordAccess(this);   26.     return oldValue;   27.    }   28.   }   29.    30.   modCount++;   31.   addEntry(hash, key, value, i);   32.   return null;   33.  }  
Lets note down the steps one by one:
Step1- First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.
 Step2- Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. JDK designers well assumed that there might be some poorly writtenhashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function, and passed the object’s hash code to this hash() function to bring hash value in range of array index size.
Step3- Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.
Step4- Here comes the main part. Now, as we know that two unequal objects can have same hash code value, how two different objects will be stored in same array location [called bucket].
Answer is LinkedList. If you remember, Entry class had an attribute “next”. This attribute always points to next object in chain. This is exactly the behavior of LinkedList.
So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.
If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null.
What if we add the another value object with same key as entered before. Logically, it should replace the old value. How it is done? Well, after determining the index position of Entry object, while iterating over LinkedList on calculated index, HashMap calls equals method on key object for each Entry object. All these Entry objects in LinkedList will have similar hash code but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside Entry object only.
In this way, HashMap ensure the uniqueness of keys.  How get() methods works internally Now we have got the idea, how key-value pairs are stored in HashMap. Next big question is : what happens when an object is passed in get method of HashMap? How the value object is determined?
Answer we already should know that the way key uniqueness is determined in put() method , same logic is applied in get() method also. The moment HashMap identify exact match for the key object passed as argument, it simply returns the value object stored in current Entry object.
If no match is found, get() method returns null.
Let have a look at code:
view plainprint?
1. /**  2.   * Returns the value to which the specified key is mapped, or {@code null}  3.   * if this map contains no mapping for the key.  4.   *  5.   * <p>  6.   * More formally, if this map contains a mapping from a key {@code k} to a  7.   * value {@code v} such that {@code (key==null ? k==null :  8.   * key.equals(k))}, then this method returns {@code v}; otherwise it returns  9.   * {@code null}. (There can be at most one such mapping.)
10.   *  11.   * </p><p>  12.   * A return value of {@code null} does not <i>necessarily</i> indicate that  13.   * the map contains no mapping for the key; it's also possible that the map  14.   * explicitly maps the key to {@code null}. The {@link #containsKey  15.   * containsKey} operation may be used to distinguish these two cases.  16.   *  17.   * @see #put(Object, Object)  18.   */   19.  public V get(Object key) {   20.   if (key == null)   21.    return getForNullKey();   22.   int hash = hash(key.hashCode());   23.   for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.ne xt) {   24.    Object k;   25.    if (e.hash == hash && ((k = e.key) == key || key.equals(k)))   26.     return e.value;   27.   }   28.   return null;   29.  }      
LinkedHashMap class in collection framework Posted by Dinesh Rajput
This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted.
This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.
You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.
The LinkedHashMap class supports five constructors. The first form constructs a default LinkedHashMap:
view plainprint?
1. LinkedHashMap( )   The second form initializes the LinkedHashMap with the elements from m:
view plainprint?
1. LinkedHashMap(Map m)   The third form initializes the capacity:
view plainprint?
1. LinkedHashMap(int capacity)  
The fourth form initializes both capacity and fill ratio. The meaning of capacity and fill ratio are the same as for HashMap:
view plainprint?
1. LinkedHashMap(int capacity, float fillRatio)   The last form allows you to specify whether the elements will be stored in the linked list by insertion order, or by order of last access. If Order is true, then access order is used. If Order is false, then insertion order is used.
view plainprint?
1. LinkedHashMap(int capacity, float fillRatio, boolean Order)   1. A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class. 2. It contains only unique elements. 3. It may have one null key and multiple null values. 4. It is same as HashMap instead maintains insertion order. Hierarchy of LinkedHashMap class:
Apart from the methods inherited from its parent classes, LinkedHashMap defines following methods:
SN Methods with Description
1
void clear()  Removes all mappings from this map.
2
boolean containsKey(Object key)  Returns true if this map maps one or more keys to the specified value.
3
Object get(Object key)  Returns the value to which this map maps the specified key.
4
protected boolean removeEldestEntry(Map.Entry eldest)  Returns true if this map should remove its eldest entry.
Example of LinkedHashMap class:
view plainprint?
1. import java.util.*;   2. class Simple{   3.  public static void main(String args[]){   4.     5.   LinkedHashMap hm=new LinkedHashMap();   6.    7.   hm.put(100,"Dinesh");   8.   hm.put(101,"Sweety");   9.   hm.put(102,"Nimmo");   10.    11.   Set set=hm.entrySet();   12.   Iterator itr=set.iterator();   13.    14.   while(itr.hasNext()){   15.    Map.Entry m=(Map.Entry)itr.next();   16.    System.out.println(m.getKey()+" "+m.getValue());   17.   }   18.  }   19. }  
Output: 100 Dinesh 101 Sweety 103 Nimmo
TreeMap class in collection framework Posted by Dinesh Rajput TreeMap class  A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMapclass.  It contains only unique elements.  It cannot have null key but can have multiple null values.  It is same as HashMap instead maintains ascending order.
The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.  
You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.
The TreeMap class supports four constructors. The first form constructs an empty tree map that will be sorted by using the natural order of its keys:
view plainprint?
1. TreeMap( )   The second form constructs an empty tree-based map that will be sorted by using the Comparator comp:
view plainprint?
1. TreeMap(Comparator comp)   The third form initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys:
view plainprint?
1. TreeMap(Map m)   The fourth form initializes a tree map with the entries from sm, which will be sorted in the same order as sm:
view plainprint?
1. TreeMap(SortedMap sm)   Apart from the methods inherited from its parent classes, TreeMap defines following methods:
SN Methods with Description
1
void clear() Removes all mappings from this TreeMap.
2
Object clone() Returns a shallow copy of this TreeMap instance.
3
Comparator comparator() Returns the comparator used to order this map, or null if this map uses its keys' natural order.
4
boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key.
5
boolean containsValue(Object value)  Returns true if this map maps one or more keys to the specified value.
6
Set entrySet()  Returns a set view of the mappings contained in this map.
7
Object firstKey()  Returns the first (lowest) key currently in this sorted map.
8
Object get(Object key)  Returns the value to which this map maps the specified key.
9
SortedMap headMap(Object toKey)  Returns a view of the portion of this map whose keys are strictly less than toKey.
10
Set keySet() Returns a Set view of the keys contained in this map.
11
Object lastKey()  Returns the last (highest) key currently in this sorted map.
12
Object put(Object key, Object value)  Associates the specified value with the specified key in this map.
13
void putAll(Map map)  Copies all of the mappings from the specified map to this map.
14
Object remove(Object key)  Removes the mapping for this key from this TreeMap if present.
15
int size()  Returns the number of key-value mappings in this map.
16
SortedMap subMap(Object fromKey, Object toKey)  Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
17
SortedMap tailMap(Object fromKey)  Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
18
Collection values()  Returns a collection view of the values contained in this map.
Example:
view plainprint?
1. import java.util.*;   2. class TreeMapDemo   3. {   4.  public static void main(String args[])   5.  {   6.   TreeMap< String,Integer> tm = new TreeMap< String,Integer>();   7.   tm.put("a",new Integer(100));   8.   tm.put("b",new Integer(200));   9.   tm.put("c",new Integer(300));   10.   tm.put("d",new Integer(400));   11.    12.   Set< Map.Entry< String,Integer> > st = tm.entrySet();   13.   for(Map.Entry me:st)     14.   {   15.    System.out.print(me.getKey()+":");   16.    System.out.println(me.getValue());   17.   }   18.  }   19. }  
Output: a 100 b 200 c 300 d 400
Difference between TreeMap vs HashMap Posted by Dinesh Rajput
Both TreeMap & HashMap are two different implementation of the Map interface. Even though this post is titled “TreeMap vsHashMap” I would like to say how they are connected and how much similar they
are.
Both TreeMap & HashMap are not synchronized. To make it synchronized we have to explicitly callCollections.synchronizedMap( mapName ) . Both supports “fail-fast” iterators. Both of them doesn’t support duplicate keys.
HashMap
1. HashMap allows null as both keys and values. 2. HashMap is useful when we need to access the map without considering how they are added to the map (means, unordered lookup of values using their keys). 3. HashMap is synchronized while it is being looked up.  4. HashMap doesn’t allow duplicated entries.
The performance of HashMap is based on two optional parameter which we can specify during the creation of the HashMap. Initial capacity & load factor. Initial capacity is the bucket size assigned to a HashMap during it’s creation. Load factor decides when the HashMap needs to be expanded. If the load factor is 0.75, the size will be increased when the current size of the map crosses 75% of its capacity.
TreeMap
The basic difference between HashMap & TreeMap is that,  1. in a TreeMap the elements are stored in a tree.  2.TreeMap allows us to retrieve the elements in some sorted order defined by the user. So we can say that TreeMap is slower than HashMap. This is the only implementation based on SortedMap interface.
TreeMap allows us to specify an optional Comparator object during its creation. The keys should be compatible with the comparator specified. This comparator decides the order by which the keys need to be sorted.
view plainprint?
1. public interface Comparator   2. {   3.     public int compare (Object object1, Object object2);   4.     public boolean equals (Object object);   5. }  
If we are not specifying the comparator, TreeMap will try to sort the keys in the natural order. Means will consider them as instances of Comparable interface.
view plainprint?
1. public interface Comparable   2. {   3.     public int compareTo (Object objectToCompare);   4. }   Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.
view plainprint?
1. public class MyCustomKey implements Comparable   2. {   3.     private int value;   4.     public MyCustomKey(int value)   5.     {   6.        this.value = value;   7.     }              8.     9.     public int compareTo (MyCustomKey key)   10.     {   11.        int comparison = 0;              12.     13.        // Note:   14.        // Return -1 if this.value < key.value   15.        // Return  0 if this.value = key.value   16.        // Return  1 if this.value > key.value              17.     18.        return (comparison);   19.     }   20. }  
A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey(<value>)); may not give you what you were expecting. So it is always advices to override the hashCode() if objects of that class is being used as a key.
view plainprint?
1. public class MyCustomKey implements Comparable   2. {   3.     private int value;   4.     public MyCustomKey(int value)   5.     {}   6.     public int compareTo (MyCustomKey key)   7.     {}           8.     9.     public int hashCode()   10.     {   11.         // Note:   12.         // If two objects are equal then their corresponding hashCode ()   13.         // should return the same value too.   14.         return (this.value * 199);   15.     }   16. }  
Hashtable class in collection framework Posted by Dinesh Rajput
 A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling thehashcode() method. A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.  It contains only unique elements.  It may have not have any null key or value.  It is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.
Constructors:
The Hashtable defines four constructors. The first version is the default constructor: view plainprint?
1. Hashtable( )   The second version creates a hash table that has an initial size specified by size:
view plainprint?
1. Hashtable(int size)   The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio.
This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward.
view plainprint?
1. Hashtable(int size, float fillRatio)   The fourth version creates a hash table that is initialized with the elements in m.
The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used.
view plainprint?
1. Hashtable(Map m)   Methods: Apart from the methods defined by Map interface, Hashtable defines following methods:
SN Methods with Description
1
void clear( ) Resets and empties the hash table.
2
Object clone( ) Returns a duplicate of the invoking object.
3
boolean contains(Object value) Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
4 boolean containsKey(Object key) Returns true if some key equal to key exists within the hash table. Returns false if the key isn't
found.
5
boolean containsValue(Object value) Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
6
Enumeration elements( ) Returns an enumeration of the values contained in the hash table.
7
Object get(Object key) Returns the object that contains the value associated with key. If key is not in the hash table, a null object is returned.
8
boolean isEmpty( ) Returns true if the hash table is empty; returns false if it contains at least one key.
9
Enumeration keys( ) Returns an enumeration of the keys contained in the hash table.
10
Object put(Object key, Object value) Inserts a key and a value into the hash table. Returns null if key isn't already in the hash table; returns the previous value associated with key if key is already in the hash table.
11
void rehash( ) Increases the size of the hash table and rehashes all of its keys.
12
Object remove(Object key) Removes key and its value. Returns the value associated with key. If key is not in the hash table, a null object is returned.
13
int size( ) Returns the number of entries in the hash table.
14
String toString( ) Returns the string equivalent of a hash table.
Example of Hashtable:
view plainprint?
1. import java.util.*;   2. class Simple{   3.  public static void main(String args[]){   4.     5.   Hashtable hm = new Hashtable();   6.    7.   hm.put(100,"Dinesh");  
8.   hm.put(102,"Sweety");   9.   hm.put(101,"Ankit");   10.   hm.put(103,"Nimmo");   11.    12.   Set set = hm.entrySet();   13.   Iterator itr = set.iterator();   14.    15.   while(itr.hasNext()){   16.    Map.Entry m=(Map.Entry)itr.next();   17.    System.out.println(m.getKey()+" "+m.getValue());   18.   }   19.  }   20. }   Output: 103 Rahul 102 Ravi 101 Vijay 100 Amit
Difference between HashMap and HashTable in Java Posted by Dinesh Rajput
1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMapallows null values as key and value whereas Hashtable doesn't allow nulls). 2. HashMap does not guarantee that the order of the map will remain constant over time. 3. HashMap is non synchronized whereas Hashtable is synchronized. 4. Iterator in the Hashtable is fail-safe because enumerator for the Hashtable is not throwConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. Note on Some Important Terms
1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. 2. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. 3. Structurally modification means deleting or inserting element which could effectively change the structure of map.
Parameter Hashmap Hashtable
Parameter Hashmap Hashtable
Synchronized Not Syncronized Syncronized
Null key and Value
Allows one null key and any number of null values
Not allow null keys or values
Fail fast Iterator in Hashmap is fail fast
Enumeration in Hashtable is not fail fast
ThreadSafe No Yes
Extends Extends AbstractMap class Extends Dictionary class
Performance Faster then Hashtable Slower then Hashmap  
Note - You can synchonized a HashMap with the help of Collections.synchonizedMap(hashmap) view plainprint?
1. Map map=Collections.synchonizedMap(hashmap)   Syncronized →Being synchronized means that operation is thread safe, so only one thread can access the table at a time.
Fail safe - Fail-fast means when you try to modify the content when you are iterating, it will throw ConcurrentModificationException and fail immediately.
For HashMap Itration:
view plainprint?
1. Set keys = hashMap.keySet();   2. for (Object key : key) {   3.     hashMap.put(someObject, someValue); //it will throw the ConcurrentModificati onException   4. }   For HashTable Enumeration:
view plainprint?
1. Enumeration keys = hashTable.keys();   2.  for (Enumeration e = v.elements() ; e.hasMoreElements() ; e.nextElement()) {   3.       hashTable.put(someKey, someValue); //it works   4.  }    
Sorting in collection framework Posted by Dinesh Rajput
We can sort the elements of:
1. String objects 2. Wrapper class objects 3. User-defined class objects Collections class provides static methods for sorting the elements of collection.If collection elements are of Set type, we can useTreeSet. But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements. Method of Collections class for sorting List elements public void sort(List list): is used to sort the elements of List. List elements must be of Comparable type.
Note: String class and Wrapper classes implements the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable.
Example of Sorting the elements of List that contains string objects- view plainprint?
1. import java.util.*;   2. class Simple12{   3. public static void main(String args[]){   4.    5. ArrayList al=new ArrayList();   6. al.add("Dinesh");   7. al.add("Sweetu");   8. al.add("Adesh");   9. al.add("Vinesh");   10.    11. Collections.sort(al);   12. Iterator itr=al.iterator();   13.    14. while(itr.hasNext()){   15. System.out.println(itr.next());   16.  }   17. }   18.    19. }  
Output: Adesh Dinesh Sweetu Vinesh
 Example of Sorting the elements of List that contains Wrapper class objects
view plainprint?
1. import java.util.*;   2. class Simple12{   3. public static void main(String args[]){   4.    5. ArrayList al=new ArrayList();   6. al.add(Integer.valueOf(201));   7. al.add(Integer.valueOf(101));   8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)   9.    10. Collections.sort(al);   11.    12. Iterator itr=al.iterator();   13. while(itr.hasNext()){   14. System.out.println(itr.next());   15.  }   16. }   17. }  
Output: 101 201 230
Java Comparable and comparator Posted by Dinesh Rajput
In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value. Java provides some inbuilt methods to sort primitive types array or Wrapper classes array or list. Here we will first learn how we can sort an array/list of primitive types and wrapper classes and then we will use java.lang.Comparable and java.util.Comparator interfaces to sort array/list of custom classes.
Difference between comparable and comparator in java In java the element in collections can be sorted by using TreeSet or TreeMap. To sort the data elements a class needs to implement Comparator or Comparable interface. Thats why all Wrapper classes like Integer,Double and String class implements Comparable interface.
A class implementing Comparable interface need to override compareTo(Object obj) method and put the logic for sorting.
The method returns an int value :-1,0,1
It will return -1 : If this object is lesser than the passed object It will return 0 : If this object is same the passed object It will return 1 : If this object is greater than the passed object
Consider a class Person.
view plainprint?
1. class Person {   2. public String name;   3. public String lastName;   4.    5. public Person(String name, String lastName){   6.  this.name=name;   7.  this.lastName=lastName;   8. }   9. public String getName(){   10. return name;   11. }   12. public String getLastName(){   13. return lastName;   14. }   15.    16. public static void main(String arg[]){   17.   List myList = new ArrayList();   18.   myList.add(new Person("Robert","USA"));   19.   myList.add(new Person("Andy","UK"));   20.   myList.add(new Person("Harish","India"));   21.   for(Person person : myList){   22.     System.out.println("My name is "+person.getName());   23.   }   24. }   25.    26. }   Output is : My name is Robert My name is Andy My name is Harish
But now i want that the objects to be sorted on name basis should be retrieved in sorted order. Consider a class Person.
view plainprint?
1. class Person implements Comparable{   2. public String name;   3. public String lastName;   4.    5. public Person(String name, String lastName){   6.   this.name=name;   7.   this.lastName=lastName;   8. }   9. public String getName(){   10.   return name;   11. }   12. public String getLastName(){   13.   return lastName;   14. }   15.  
16. public int compareTo(Person p){   17.   return this.name.compareTo(p.getName);   18. }   19. public static void main(String arg[]){   20.   List myList = new ArrayList();   21.   myList.add(new Person("Robert","USA"));   22.   myList.add(new Person("Andy","UK"));   23.   myList.add(new Person("Harish","India"));   24.   Collections.sort(myList);   25.   for(Person person : myList){   26.   System.out.println("My name is "+person.getName());   27.   }   28. }   29. }   Output is : My name is Andy My name is Harish My name is Robert
Couple of things which needs to be taken in consideration:
 Collections.sort() will sort only the collection having objects which implements either one of the comparing interface.  Collections.sort() will sort the same list. Comparator interface is used when an extra logic is required to sort the objects. One need to override compare(Object obj1, Object obj2) method.For example you want the list of Person object to be sorted on the basis of complete name i.e "name lastName" but also on the other hand doesnt want to change the Person class default sorting implementation or Person class is a jar so so no code modification in it can be done. First create a Custom Comparator. view plainprint?
1. public class MyCustomComparator implements Comparator{   2.   public int compare(Object obj1, Object obj2){   3.     Person p1 =(Person) obj1;   4.     Person p2 =(Person) ob2;   5.     String p1Name = p1.getName()+ " " +p1.getLastName();   6.     String p2Name = p2.getName()+ " " +p2.getLastName();   7.     return p1Name.toCompareTo(p2Name);   8.   }   9. }   10. // Changes made in main method of Person class.   11. public static void main(String arg[]){   12.   List myList = new ArrayList();   13.   myList.add(new Person("Robert","USA"));   14.   myList.add(new Person("Robert","UK"));   15.   myList.add(new Person("Robert","India"));   16.   Collections.sort(myList new MyCustomComparator());   17.   for(Person person : myList){   18.   System.out.println("My name is "+person.getName() + " " + person.getLastName() );   19.   }   20. }   OutPut: My name is Robert India My name is Robert UK My name is Robert USA
Couple of things which needs to be taken in consideration: 1) For Comparator interface you need to override method compare(obj) 2) In collections.sort() the instance of Comparator need to be passed. In this example the list is sorted according to the custom Comparator created.