Thursday, 16 January 2014

Nested Class & Interfaces in Java



Nested classes (Inner classes)

    Nested classes
    Advantage of Nested classes
    Difference between nested class and inner class
    Types of Nested classes

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

    class Outer_class_Name{
     ...
     class Nested_class_Name{
      ...
     }
     ...
    }

Do You Know ?

    What is the internal code generated by the compiler for member inner class ?
    What are the two ways to create annonymous inner class ?
    Can we access the non-final local variable inside the local inner class ?
    How to access the static nested class ?
    Can we define an interface within the class ?
    Can we define a class within the interface ?

Advantage of nested classes
There are basically three advantages of nested classes. They are

    Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
    Nested classes can lead to more readable and maintainable code because it logically group classes in one place only.
    Code Optimization as we need less code to write.

Que) What is the difference between nested class and inner class?
Inner class is a part of nested class. Non-static nested classes are known as nested classes.
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.

    non-static nested class(inner class)
        a)Member inner class
        b)Annomynous inner class
        c)Local inner class
    static nested class



What we will learn in Nested classes ?

    Nested class
    Member inner class
    Annonymous inner class
    Local Inner class
    static nested class
    Nested interface


1)Member inner class
A class that is declared inside a class but outside a method is known as member inner class.
Invocation of Member Inner class

    From within the class
    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.

    class Outer{
     private int data=30;
     class Inner{
      void msg(){System.out.println("data is "+data);}
     }
      
     void display(){
      Inner in=new Inner();
      in.msg();
     }
     public static void main(String args[]){
      Outer obj=new Outer();
      obj.display();
     }
    }

Output:data is 30
  

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.

    import java.io.PrintStream;
    
    class Outer$Inner
    {
        final Outer this$0;
        Outer$Inner()
        {   super();
            this$0 = Outer.this;
        }
    
        void msg()
        {
            System.out.println((new StringBuilder()).append("data is ")
                        .append(Outer.access$000(Outer.this)).toString());
        }
    
     }

Example of member inner class that is invoked outside a class

In this example, we are invoking the msg() method of Inner class from outside the outer class i.e. Test class.

    <b><i>//Program of member inner class that is invoked outside a class</i></b>
    
    class Outer{
      private int data=30;
      class Inner{
       void msg(){System.out.println("data is"+data);}
      }
    }
    
    class Test{
     public static void main(String args[]){
      Outer obj=new Outer();
      Outer.Inner in=obj.new Inner();
      in.msg();
      }
    }

Output:data is 30
 

2)Annonymous inner class

A class that have no name is known as annomymous inner class.
Annonymous class can be created by:

    Class (may be abstract class also).
    Interface

Program of annonymous inner class by abstract class

    abstract class Person{
      abstract void eat();
    }
    
    class Emp{
     public static void main(String args[]){
      Person p=new Person(){
      void eat(){System.out.println("nice fruits");}
      };
    
      p.eat();
     }
    }

Output:nice fruits

What happens behind this code?

      Person p=new Person(){
      void eat(){System.out.println("nice fruits");}
      };
    
     }
    }

    A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
    An object of Annonymous class is created that is reffered by p reference variable of Person 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

    import java.io.PrintStream;
    static class Emp$1 extends Person
    {
       Emp$1(){}
    
       void eat()
        {
            System.out.println("nice fruits");
        }
    }

Program of annonymous inner class by interface

    interface Eatable{
     void eat();
    }
    
    class Emp{
     public static void main(String args[]){
      
     Eatable e=new Eatable(){
      public void eat(){System.out.println("nice fruits");}
     };
     e.eat();
     }
    }

Output:nice fruits

What does the compiler for annonymous inner class created by interface
It performs two main tasks behind this code:

      Eatable p=new Eatable(){
      void eat(){System.out.println("nice fruits");}
      };
    
     }
    }

    A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.
    An object of Annonymous class is created that is reffered by p reference variable of Eatable 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 created by interface

    import java.io.PrintStream;
    static class Emp$1 implements Eatable
    {
    Emp$1(){}
    
    void eat(){System.out.println("nice fruits");}
    }


Basics of Java OOPs Concepts String Handling Exception Handling
Nested Classes
Nested Class Member Inner class Annonymous Inner class Local Inner class static nested class Nested Interface
Multithreading Synchronization I/O Serialization Networking AWT Event Handling Swing LayoutManager Applet Reflection API Collection JDBC Java New Features RMI Internationalization
space


3)Local inner class
A class that is created inside a method is known as local inner class. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
Program of local inner class

    class Simple{
     private int data=30;//instance variable
     void display(){
      class Local{
       void msg(){System.out.println(data);}
      }
      Local l=new Local();
      l.msg();
     }
     public static void main(String args[]){
      Simple obj=new Simple();
      obj.display();
     }
    }

Output:30

Internal code generated by the compiler for local inner class
In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.

    import java.io.PrintStream;
    class Simple$1Local
    {
        final Simple this$0;
    
        Simple$1Local()
        {    
            super();
            this$0 = Simple.this;
        }
        void msg()
        {
            System.out.println(Simple.access$000(Simple.this));
        }
      
    }

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

    class Simple{
     private int data=30;//instance variable
     void display(){
      int value=50;//local variable must be final
      class Local{
       void msg(){System.out.println(value);}//C.T.Error
      }
      Local l=new Local();
      l.msg();
     }
     public static void main(String args[]){
      Simple obj=new Simple();
      obj.display();
     }
    }

Output:Compile Time Error

Program of accessing final local variable in local inner class

    class Simple{
     private int data=30;//instance variable
     void display(){
      final int value=50;//local variable must be final
      class Local{
       void msg(){System.out.println(data+" "+value);}//ok
      }
      Local l=new Local();
      l.msg();
     }
     public static void main(String args[]){
      Simple obj=new Simple();
      obj.display();
     }
    }

Output:30 50


4)static nested class

A static class that is created inside a class is known as static nested class. It cannot access the non-static members.

    It can access static data members of outer class including private.
    static nested class cannot access non-static (instance) data member or method.

Program of static nested class that have instance method

    class Outer{  
      static int data=30;  
      
      static class Inner{  
       void msg(){System.out.println("data is "+data);}  
      }  
       
      public static void main(String args[]){  
      Outer.Inner obj=new Outer.Inner();  
      obj.msg();  
      }  
    }  

Output:data is 30
   

In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object.
Internal code generated by the compiler for static nested class

    import java.io.PrintStream;  
      
    static class Outer$Inner  
    {  
    Outer$Inner(){}  
      
    void msg(){  
    System.out.println((new StringBuilder()).append("data is ")  
    .append(Outer.data).toString());  
    }  
          
    }  

Program of static nested class that have static method

    class Outer{  
      static int data=30;  
      
      static class Inner{  
       static void msg(){System.out.println("data is "+data);}  
      }  
       
      public static void main(String args[]){  
      Outer.Inner.msg();//no need to create the instance of static nested class  
      }  
    }  

Output:data is 30
   


Basics of Java OOPs Concepts String Handling Exception Handling
Nested Classes
Nested Class Member Inner class Annonymous Inner class Local Inner class static nested class Nested Interface
Multithreading Synchronization I/O Serialization Networking AWT Event Handling Swing LayoutManager Applet Reflection API Collection JDBC Java New Features RMI Internationalization
space
<<prev
Nested Interface
An interface which is declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly.
Points to remember for nested interfaces
There are given some points that should be remembered by the java programmer.

    Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
    Nested interfaces are declared static implicitely.

Syntax of nested interface which is declared within the interface

    interface interface_name{  
     ...  
     interface nested_interface_name{  
      ...  
     }  
    }  
       

Syntax of nested interface which is declared within the class

    class class_name{  
     ...  
     interface nested_interface_name{  
      ...  
     }  
    }  
       

Example of nested interface which is declared within the interface
In this example, we are going to learn how to declare the nested interface and how we can access it.

    interface Showable{  
      void show();  
      interface Message{  
       void msg();  
      }  
    }  
      
    class Test implements Showable.Message{  
     public void msg(){System.out.println("Hello nested interface");}  
      
     public static void main(String args[]){  
      Showable.Message message=new Test();//upcasting here  
      message.msg();  
     }  
    }  

download the example of nested interface

Output:hello nested interface

As you can see in the above example, we are acessing the Message interface by its outer interface Showable because it cannot be accessed directly. It is just like almirah inside the room, we cannot access the almirah directly because we must enter the room first. In collection frameword, sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map i.e. accessed by Map.Entry.
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.

    public static interface Showable$Message  
    {  
      public abstract void msg();  
    }  

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.

    class A{  
      interface Message{  
       void msg();  
      }  
    }  
      
    class Test implements A.Message{  
     public void msg(){System.out.println("Hello nested interface");}  
      
     public static void main(String args[]){  
      A.Message message=new Test();//upcasting here  
      message.msg();  
     }  
    }  

Output:hello nested interface

Can we define a class inside the interface ?
Yes, Ofcourse! 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:

    interface M{  
      class A{}  
    }  



String Handling

String Handling

    String Handling
    How to create string objects?
        String literal
        new keyword
    Why Java uses the concept of String literal?

String Handling provides a lot of concepts that can be performed on a string such as concatenating string, comparing string, substring etc.
In java, string is basically an immutable object. We will discuss about immutable string later. Let's first understand what is string and how we can create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.


Do You Know ?

    Why String objects are immutable ?
    How to create an immutable class ?
    What is string constant pool ?
    What code is written by the compiler if you concat any string by + (string concatenation operator) ?
    What is the difference between StringBuffer and StringBuilder class ?

How to create String object?
There are two ways to create String object:

    By string literal
    By new keyword

1) String literal:
String literal is created by double quote.For Example:

    String s="Hello";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:

    String s1="Welcome";
    String s2="Welcome";//no new object will be created

string literal
In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
2) By new keyword:

    String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).


Basics of Java OOPs Concepts
String Handling
String Immutable String String Comparison String Concatenation Substring Methods of String class StringBuffer class StringBuilder class Creating Immutable class toString method StringTokenizer class
Exception Handling Nested Classes Multithreading Synchronization I/O Serialization Networking AWT Event Handling Swing LayoutManager Applet Reflection API Collection JDBC Java New Features RMI Internationalization
space


Immutable String:
In java, strings are immutable (unmodifiable) objects.For example

    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       s.concat(" Tendulkar");//concat() method appends the string at the end
       System.out.println(s);//will print Sachin because strings are immutable objects
     }
    }

Output:Sachin

As you can see in the above figure that two objects will be created but no reference variable refers to "Sachin Tendulkar".But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:

    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       s=s.concat(" Tendulkar");
       System.out.println(s);
     }
    }

Output:Sachin Tendulkar

Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.




string comparison in java

We can compare two given on the basis of content and reference. It is used in authentication (equals() method), sorting (compareTo() method) etc.

There are three ways to compare String objects:

    By equals() method
    By = = operator
    By compareTo() method

1) By equals() method:
equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:

    public boolean equals(Object another){} compares this string to the specified object.
    public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.

    //<b><i>Example of equals(Object) method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="Sachin";
       String s3=new String("Sachin");
       String s4="Saurav";
    
       System.out.println(s1.equals(s2));//true
       System.out.println(s1.equals(s3));//true
       System.out.println(s1.equals(s4));//false
     }
    }

Output:true
       true
       false

    //<b><i>Example of equalsIgnoreCase(String) method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="SACHIN";
    
       System.out.println(s1.equals(s2));//false
       System.out.println(s1.equalsIgnoreCase(s3));//true
     }
    }

Output:false
       true

2) By == operator:
The = = operator compares references not values.

    //<b><i>Example of == operator</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="Sachin";
       String s3=new String("Sachin");
    
       System.out.println(s1==s2);//true (because both refer to same instance)
       System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
     }
    }

Output:true
       false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:

    s1 == s2 :0
    s1 > s2   :positive value
    s1 < s2   :negative value

    //<b><i>Example of compareTo() method:</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="Sachin";
       String s3="Ratan";
    
       System.out.println(s1.compareTo(s2));//0
       System.out.println(s1.compareTo(s3));//1(because s1>s3)
       System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
     }
    }

Output:0
       1
       -1
String Concatenation in Java

Concating strings form a new string i.e. the combination of multiple strings.

There are two ways to concat string objects:

    By + (string concatenation) operator
    By concat() method

1) By + (string concatenation) operator
String concatenation operator is used to add strings.For Example:

    //Example of string concatenation operator
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin"+" Tendulkar";
       System.out.println(s);//Sachin Tendulkar
     }
    }

Output:Sachin Tendulkar

The compiler transforms this to:

    String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation operator can concat not only string but primitive values also.For Example:

    class Simple{
     public static void main(String args[]){
    
       String s=50+30+"Sachin"+40+40;
       System.out.println(s);//80Sachin4040
     }
    }

Output:80Sachin4040

Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}

    //<b><i>Example of concat(String) method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin ";
       String s2="Tendulkar";
    
       String s3=s1.concat(s2);
    
       System.out.println(s3);//Sachin Tendulkar
      }
    }

Output:Sachin Tendulker



Substring in Java


A part of string is called substring. In other words, substring is a subset of another string.

In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is inclusive and endIndex is exclusive.

You can get substring from the given String object by one of the two methods:

    public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
    public String substring(int startIndex,int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string:

    startIndex:starts from index 0(inclusive).
    endIndex:starts from index 1(exclusive).

Example of java substring

    //Example of substring() method
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin Tendulkar";
       System.out.println(s.substring(6));//Tendulkar
       System.out.println(s.substring(0,6));//Sachin
     }
    }

Output:Tendulkar
              Sachin

Methods of String class

java.lang.String class provides a lot of methods to work on string. Let's see the commonly used methods of String class.
Method Description
1)public boolean equals(Object anObject) Compares this string to the specified object.
2)public boolean equalsIgnoreCase(String another) Compares this String to another String, ignoring case.
3)public String concat(String str) Concatenates the specified string to the end of this string.
4)public int compareTo(String str) Compares two strings and returns int
5)public int compareToIgnoreCase(String str) Compares two strings, ignoring case differences.
6)public String substring(int beginIndex) Returns a new string that is a substring of this string.
7)public String substring(int beginIndex,int endIndex) Returns a new string that is a substring of this string.
8)public String toUpperCase() Converts all of the characters in this String to upper case
9)public String toLowerCase() Converts all of the characters in this String to lower case.
10)public String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
13)public char charAt(int index) Returns the char value at the specified index.
14)public int length() Returns the length of this string.
15)public String intern() Returns a canonical representation for the string object.

First seven methods have already been discussed.Now Let's take the example of other methods:
toUpperCase() and toLowerCase() method

    //<b><i>Example of toUpperCase() and toLowerCase() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.toUpperCase());//SACHIN
       System.out.println(s.toLowerCase());//sachin
       System.out.println(s);//Sachin(no change in original)
     }
    }

Output:SACHIN
       sachin
       Sachin

trim() method

    //<b><i>Example of trim() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="  Sachin  ";
       System.out.println(s);//  Sachin  
       System.out.println(s.trim());//Sachin
     }
    }

Output:  Sachin
       Sachin

startsWith() and endsWith() method

    //<b><i>Example of startsWith() and endsWith() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.startsWith("Sa"));//true
       System.out.println(s.startsWith("n"));//true
     }
    }

Output:true
       true

charAt() method

    //<b><i>Example of charAt() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.charAt(0));//S
       System.out.println(s.charAt(3));//h
     }
    }

Output:S
       h

length() method

    //<b><i>Example of length() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.length());//6
      }
    }

Output:6

intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    //<b><i>Example of length() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s=new String("Sachin");
       String s2=s.intern();
       System.out.println(s2);//Sachin
      }
    }

Output:Sachin

Synchronization


Synchronization

Synchronization is the capabilility 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.

Why use Synchronization?

The synchronization is mainly used to
  1. To prevent thread interference.
  2. To prevent consistency problem.


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.
  • Mutual Exclusive
    1. Synchronized method.
    2. Synchronized block.
    3. static synchronization.
  • 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:
  1. Class Table{  
  2.   
  3. void printTable(int n){//method not synchronized  
  4.    for(int i=1;i<=5;i++){  
  5.      System.out.println(n*i);  
  6.      try{  
  7.       Thread.sleep(400);  
  8.      }catch(Exception e){System.out.println(e);}  
  9.    }  
  10.   
  11.  }  
  12. }  
  13.   
  14. class MyThread1 extends Thread{  
  15. Table t;  
  16. MyThread1(Table t){  
  17. this.t=t;  
  18. }  
  19. public void run(){  
  20. t.printTable(5);  
  21. }  
  22.   
  23. }  
  24. class MyThread2 extends Thread{  
  25. Table t;  
  26. MyThread2(Table t){  
  27. this.t=t;  
  28. }  
  29. public void run(){  
  30. t.printTable(100);  
  31. }  
  32. }  
  33.   
  34. class Use{  
  35. public static void main(String args[]){  
  36. Table obj = new Table();//only one object  
  37. MyThread1 t1=new MyThread1(obj);  
  38. MyThread2 t2=new MyThread2(obj);  
  39. t1.start();  
  40. t2.start();  
  41. }  
  42. }  
Output: 5
       100
       10
       200
       15
       300
       20
       400
       25
       500
       

Solution by synchronized method

  • If you declare any method as synchronized, it is known as synchronized method.
  • Synchronized method is used to lock an object for any shared resource.
  • When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the method returns.
  1. <b><i>//Program of synchronized method</i></b>  
  2.   
  3. Class Table{  
  4.   
  5.  synchronized void printTable(int n){//synchronized method  
  6.    for(int i=1;i<=5;i++){  
  7.      System.out.println(n*i);  
  8.      try{  
  9.       Thread.sleep(400);  
  10.      }catch(Exception e){System.out.println(e);}  
  11.    }  
  12.   
  13.  }  
  14. }  
  15.   
  16. class MyThread1 extends Thread{  
  17. Table t;  
  18. MyThread1(Table t){  
  19. this.t=t;  
  20. }  
  21. public void run(){  
  22. t.printTable(5);  
  23. }  
  24.   
  25. }  
  26. class MyThread2 extends Thread{  
  27. Table t;  
  28. MyThread2(Table t){  
  29. this.t=t;  
  30. }  
  31. public void run(){  
  32. t.printTable(100);  
  33. }  
  34. }  
  35.   
  36. class Use{  
  37. public static void main(String args[]){  
  38. Table obj = new Table();//only one object  
  39. MyThread1 t1=new MyThread1(obj);  
  40. MyThread2 t2=new MyThread2(obj);  
  41. t1.start();  
  42. t2.start();  
  43. }  
  44. }  
Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
       

Same Example of synchronized method by using annonymous class

In this program, we have created the two threads by annonymous class, so less coding is required.
  1. <b><i>//Program of synchronized method by using annonymous class</i></b>  
  2.   
  3. Class Table{  
  4.   
  5.  synchronized void printTable(int n){//synchronized method  
  6.    for(int i=1;i<=5;i++){  
  7.      System.out.println(n*i);  
  8.      try{  
  9.       Thread.sleep(400);  
  10.      }catch(Exception e){System.out.println(e);}  
  11.    }  
  12.   
  13.  }  
  14. }  
  15.   
  16. class Use{  
  17. public static void main(String args[]){  
  18. final Table obj = new Table();//only one object  
  19.   
  20. MyThread1 t1=new MyThread1(){  
  21. public void run(){  
  22. obj.printTable(5);  
  23. }  
  24. };  
  25. MyThread1 t2=new MyThread1(){  
  26. public void run(){  
  27. obj.printTable(100);  
  28. }  
  29. };  
  30.   
  31. t1.start();  
  32. t2.start();  
  33. }  
  34. }  
Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
       
- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/synchronization.html#sthash.zk7NZbB8.dpuf

Java Version History


Java Version History

There are many java versions that has been released.

    JDK Alpha and Beta (1995)
    JDK 1.0 (23rd Jan, 1996)
    JDK 1.1 (19th Feb, 1997)
    J2SE 1.2 (8th Dec, 1998)
    J2SE 1.3 (8th May, 2000)
    J2SE 1.4 (6th Feb, 2002)
    J2SE 5.0 (30th Sep, 2004)
    Java SE 6 (11th Dec, 2006)
    Java SE 7 (28th July, 2011)



Java Version History

There are many java versions that has been released.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)
- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/history-of-java.html#sthash.v4tFHvyQ.dpuf

Java Version History

There are many java versions that has been released.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)

- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/history-of-java.html#sthash.v4tFHvyQ.dpufJava Version History

There are many java versions that has been released.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)

- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/history-of-java.html#sthash.v4tFHvyQ.dpufJava Version History

There are many java versions that has been released.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)

- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/history-of-java.html#sthash.v4tFHvyQ.dpufJava Version History

There are many java versions that has been released.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)
- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/history-of-java.html#sthash.v4tFHvyQ.dpuf

Java Version History

There are many java versions that has been released.
  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan, 1996)
  3. JDK 1.1 (19th Feb, 1997)
  4. J2SE 1.2 (8th Dec, 1998)
  5. J2SE 1.3 (8th May, 2000)
  6. J2SE 1.4 (6th Feb, 2002)
  7. J2SE 5.0 (30th Sep, 2004)
  8. Java SE 6 (11th Dec, 2006)
  9. Java SE 7 (28th July, 2011)
- See more at: file:///C:/Users/vijay/Desktop/JavaTpoint/JavaTpoint/www.javatpoint.com/history-of-java.html#sthash.v4tFHvyQ.dpuf

JDK Versin Story and Updates


JDK Alpha and Beta (1995)

Alpha and Beta Java public releases had highly unstable  and . The supplied Java web browser was named WebRunner.

JDK 1.0 (January 23, 1996)[edit]

Codename Oak. Initial release[3][4] The first stable version was the JDK 1.0.2. is called Java 1.[4]
Note : In versions of Java and the JDK up to 1.0.1, you could use private and protected together to create yet another form of protection that would restrict access to methods or variables solely to subclasses of a given class. As of 1.0.2, this capability has been removed from the language.

JDK 1.1 (February 19, 1997)[edit]

Major additions included:[5]
  • an extensive retooling of the AWT event model
  • inner classes added to the language
  • JavaBeans
  • JDBC
  • RMI
  • reflection which supported Introspection only, no modification at runtime was possible.
  • JIT(Just In Time) compiler on Microsoft Windows platforms, produced for JavaSoft by Symantec

J2SE 1.2 (December 8, 1998)[edit]

Codename Playground. This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 and the version name "J2SE" (Java 2 Platform, Standard Edition) replaced JDK to distinguish the base platform from J2EE (Java 2 Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition). This was a very significant release of Java as it tripled the size of the Java platform to 1520 classes in 59 packages. Major additions included:[6]

J2SE 1.3 (May 8, 2000)[edit]

Codename Kestrel. The most notable changes were:[7][8]

J2SE 1.4 (February 6, 2002)[edit]

Codename Merlin. This was the first release of the Java platform developed under the Java Community Process as JSR 59. Major changes included:[9][10]
Language changes
Library improvements
  • regular expressions modeled after Perl regular expressions
  • exception chaining allows an exception to encapsulate original lower-level exception
  • Internet Protocol version 6 (IPv6) support
  • non-blocking IO (named NIO) (New Input/Output) (Specified in JSR 51.)
  • logging API (Specified in JSR 47.)
  • image I/O API for reading and writing images in formats like JPEG and PNG
  • integrated XML parser and XSLT processor (JAXP) (Specified in JSR 5 and JSR 63.)
  • integrated security and cryptography extensions (JCE, JSSE, JAAS)
  • Java Web Start included (Java Web Start was first released in March 2001 for J2SE 1.3) (Specified in JSR 56.)
  • Preferences API (java.util.prefs)
Support and security updates for Java 1.4 ended in October 2008.[11]

J2SE 5.0 (September 30, 2004)[edit]

Codename Tiger. Originally numbered 1.5, which is still used as the internal version number.[12] This version was developed under JSR 176.
J2SE 5.0 entered its end-of-public-updates period on April 8, 2008 updates are no longer available to the public as of November 3, 2009. Updates will be available to Oracle Customers until May 2014.[13]
Tiger added a number of significant new language features:[14][15]
  • Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). (Specified by JSR 14.)
  • Metadata: Also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.)
  • Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). (Specified by JSR 201.)
  • Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). (Specified by JSR 201.)
  • Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
  • Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collectionclasses. (Specified by JSR 201.)
  • Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory.
  • Static imports
There were also the following improvements to the standard libraries:
Java 5 is the last release of Java to officially support the Microsoft Windows 9x line (Windows 95, Windows 98, Windows ME),[17] while Windows Vista is the newest version of Windows that J2SE 5 was supported on prior to Java 5 going end of life in October 2009.[11]
Java 5 is the default version of Java installed on Apple Mac OS X 10.5 (Leopard). Java 6 can be installed and set as the default to be used on 64-bit (Core 2 Duo and higher) processor machines.[18] Java 6 is also supported by 32-bit machines running Mac OS X 10.6 (Snow Leopard).

Java SE 6 (December 11, 2006)[edit]

Codename Mustang. As of this version, Sun replaced the name "J2SE" with Java SE and dropped the ".0" from the version number.[19] Internal numbering for developers remains 1.6.0.[20] This version was developed under JSR 270.
During the development phase, new builds including enhancements and bug fixes were released approximately weekly. Beta versions were released in February and June 2006, leading up to a final release that occurred on December 11, 2006.
Major changes included in this version:[21][22]
  • Support for older Win9x versions dropped; unofficially, Java 6 Update 7 was the last release of Java shown to work on these versions of Windows.[citation needed] This is believed[by whom?] to be due to the major changes in Update 10.
  • Scripting Language Support (JSR 223): Generic API for tight integration with scripting languages, and built-in Mozilla JavaScript Rhino integration
  • Dramatic performance improvements for the core platform,[23][24] and Swing.
  • Improved Web Service support through JAX-WS (JSR 224)
  • JDBC 4.0 support (JSR 221).
  • Java Compiler API (JSR 199): an API allowing a Java program to select and invoke a Java Compiler programmatically.
  • Upgrade of JAXB to version 2.0: Including integration of a StAX parser.
  • Support for pluggable annotations (JSR 269)[25]
  • Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).
  • JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.[26]
Java 6 reached the end of its supported life in February 2013, at which time all updates, including security updates, were scheduled to be stopped.[27][28] Oracle released one more update to Java 6 in March 2013, which patched some security vulnerabilities.[29]

Java 6 updates[edit]

After Java 6 release, Sun, and later Oracle, released several updates which, while not changing any public API, enhanced end-user usability or fixed bugs.[30]
ReleaseRelease DateHighlights
Java SE 6 Update 12007-05-07
Java SE 6 Update 22007-07-03
Java SE 6 Update 32007-10-03
Java SE 6 Update 42008-01-14HotSpot VM 10
Java SE 6 Update 52008-03-05
Java SE 6 Update 62008-04-16
Java SE 6 Update 7[31]Unofficially, Java SE 6 Update 7 (1.6.0.7) is the last version of Java that was shown to be working on the Win9x family of operating systems[citation needed]
Java SE 6 Update 10[32]2008-10-15HotSpot VM 11. Major changes for this update include:
  • Java Deployment Toolkit, a set of JavaScript functions to ease the deployment of applets and Java Web Start applications.[33]
  • Java Kernel, a small installer including only the most commonly used JRE classes. Other packages are downloaded when needed.
  • Enhanced updater.
  • Enhanced versioning and pack200 support: server-side support is no longer required.[34]
  • Java Quick Starter, to improve cold start-up time.
  • Improved performance of Java2D graphics primitives on Windows, using Direct3D and hardware acceleration.
  • A new Swing look and feel called Nimbus and based on synth.[35]
  • Next-Generation Java Plug-In: applets now run in a separate process and support many features of Web Start applications.[36]
Java SE 6 Update 11[37]2008-12-0313 security fixes[38]
Java SE 6 Update 12[39]2008-12-12No security fixes; 64-bit Java plug-in (for 64-bit web browsers only); Windows Server 2008 support; performance improvements of graphics andJavaFX applications
Java SE 6 Update 13[40]2009-03-247 security fixes, JNDI store and retrieve Java objects in LDAP slightly modified, JMX Change (createMBeanunregisterMBean), 4 new root certs added
Java SE 6 Update 14[41]2009-05-28HotSpot VM 14. This release includes extensive performance updates to the JIT compiler, compressed pointers for 64-bit machines, as well as support for the G1 (Garbage First) low pause garbage collector.[42][43]
The -XX:+DoEscapeAnalysis option directs the HotSpot JIT compiler to use escape analysis to determine if local objects can be allocated on the stack instead of the heap.[44]
Some developers have noticed an issue introduced in this release which causes debuggers to miss breakpoints seemingly randomly.[45] Sun has a corresponding bug, which is tracking the issue. The workaround applies to the Client and Server VMs.[46] Using the -XX:+UseParallelGCoption will prevent the failure. Another workaround is to roll back to update 13, or to upgrade to update 16.
Java SE 6 Update 152009-08-04Introduced patch-in-place functionality[47]
Java SE 6 Update 162009-08-11Fixed the issue introduced in update 14 which caused debuggers to miss breakpoints[48]
Java SE 6 Update 17[49]2009-11-04Security fixes; 2 new root certificates
Java SE 6 Update 18[50]2010-01-13No security fixes; Hotspot VM 16; support for Ubuntu 8.04 LTS Desktop Edition, SLES 11, Windows 7, Red Hat Enterprise Linux 5.3, Firefox 3.6, VisualVM 1.2; updated Java DB; many performance improvements
Java SE 6 Update 19[51]2010-03-30Security fixes; root certificate changes: seven new, three removed, five replaced with stronger signature algorithms; interim fix for TLS renegotiation attack
Java SE 6 Update 20[52]2010-04-15Two security fixes
Java SE 6 Update 21[53]2010-07-07No security fixes; Hotspot VM 17; support for Red Hat Enterprise Linux 5.4 and 5.5, Oracle Enterprise Linux 4.8, 5.4, 5.5; Google Chrome 4 support; support for Customized Loading Progress Indicators; VisualVM 1.2.2
Java SE 6 Update 22[54]2010-10-1229 security fixes; RFC 5746 support
Java SE 6 Update 23[55]2010-12-08No security fixes; Hotspot VM 19; better support for right-to-left languages
Java SE 6 Update 24[56]2011-02-1521 security fixes; updated Java DB
Java SE 6 Update 252011-03-21No security fixes; Hotspot VM 20; support for Internet Explorer 9, Firefox 4 and Chrome 10; improved BigDecimal; includes "tiered" compilation in the Server VM that enables it to start quickly as does the Client VM, while achieving better peak performance (this feature is enabled by specifying -server and -XX:+TieredCompilation command options)[57]
Java SE 6 Update 26[58]2011-06-0717 new security fixes.[59] Last version compatible with Windows Vista SP1.
Java SE 6 Update 27[60]2011-08-16No security fixes; certification for Firefox 5
Java SE 6 Update 29[61]2011-10-1820 security fixes, various bug fixes[62]
Java SE 6 Update 30[63]2011-12-12No security fixes; fix for SSL regression in Update 29; support for Red Hat Enterprise Linux 6
Java SE 6 Update 31[64]2012-02-1414 security fixes and one bug fix
Java SE 6 Update 32[65]2012-04-26No security fixes, various bug fixes
Java SE 6 Update 33[66]2012-06-1214 security fixes, improved VM configuration file loading
Java SE 6 Update 34[67]2012-08-14No security fixes, various bug fixes
Java SE 6 Update 35[68]2012-08-30Contains a security-in-depth fix[69]
Java SE 6 Update 37[70]2012-10-1630 security fixes
Java SE 6 Update 38[71]2012-12-11Various bug fixes[72]
Java SE 6 Update 39[73]2013-02-0150 security fixes
Java SE 6 Update 41[74]2013-02-195 security fixes
Java SE 6 Update 43[75]2013-03-042 security fixes
Java SE 6 Update 45[76]2013-04-1642 security fixes;[77] other changes;[76] final public update[78]
Java SE 6 Update 51[79]2013-06-18Not available publicly, only available through the Java SE Support program and in Apple Update for OS X Snow Leopard, Lion & Mountain Lion; up to 40 security fixes[80]
Java SE 6 Update 65[81]2013-10-15Not available publicly, only available through the Java SE Support program and in Apple Update for OS X Snow Leopard, Lion & Mountain Lion; at least 11 critical security fixes[82]
Java SE 6 Update 712014-01-14Not available publicly, only available through the Java SE Support program and in Apple Update for OS X Snow Leopard, Lion & Mountain Lion; 34 fixes[83]

Java SE 7 (July 28, 2011)[edit]

Java 7 (codename Dolphin[84]) is a major update that was launched on July 7, 2011[85] and was made available for developers on July 28, 2011.[86] The development period was organized into thirteen milestones; on June 6, 2011, the last of the thirteen milestones was finished.[87][88] On average, 8 builds (which generally included enhancements and bug fixes) were released per milestone. The feature list at the OpenJDK 7 project lists many of the changes.
Additions in Java 7 include:[89]
  • JVM support for dynamic languages, with the new invokedynamic bytecode under JSR-292,[90] following the prototyping work currently done on the Multi Language Virtual Machine
  • Compressed 64-bit pointers[91] (available in Java 6 with -XX:+UseCompressedOops)[92]
  • These small language changes (grouped under a project named Coin):[93]
  • Strings in switch[94]
  • Automatic resource management in try-statement[95]
  • Improved type inference for generic instance creation, aka the diamond operator <>[96]
  • Simplified varargs method declaration[97]
  • Binary integer literals[98]
  • Allowing underscores in numeric literals[99]
  • Catching multiple exception types and rethrowing exceptions with improved type checking[100]
  • Concurrency utilities under JSR 166[101]
  • New file I/O library to enhance platform independence and add support for metadata and symbolic links. The new packages are java.nio.file and java.nio.file.attribute[102][103]
  • Timsort is used to sort arrays instead of merge sort
  • Library-level support for elliptic curve cryptography algorithms
  • An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs
  • New platform APIs for the graphics features originally implemented in version 6u10 as unsupported APIs[104]
  • Enhanced library-level support for new network protocols, including SCTP and Sockets Direct Protocol
  • Upstream updates to XML and Unicode
Lambda (Java's implementation of lambda functions), Jigsaw (Java's implementation of modules), and part of Coin were dropped from Java 7. Java 8 will be released with the remaining features (except for Jigsaw, which will be in Java 9) in spring 2014.[105][106]

Java 7 updates[edit]

Oracle plans to issue updates to the Java 7 family on a quarterly basis.[107]
ReleaseRelease DateHighlights
Java SE 7[108]2011-07-28Initial release. HotSpot VM 21
Java SE 7 Update 1[109]2011-10-1820 security fixes, other bug fixes
Java SE 7 Update 2[110]2011-12-12No security fixes; HotSpot VM 22; reliability and performance improvements; support for Solaris 11 and Firefox 5 and later; JavaFX included with Java SE JDK, improvements for web-deployed applications
Java SE 7 Update 3[111]2012-02-1414 security fixes[112]
Java SE 7 Update 4[113]2012-04-26No security updates; HotSpot VM 23; JDK Support for Mac OS X
Java SE 7 Update 5[114]2012-06-1214 security fixes[115]
Java SE 7 Update 6[116]2012-08-14JavaFX and Java Access Bridge included in Java SE JDK and JRE installation, JavaFX support for touch-enabled monitors and touch pads, JavaFX support for Linux, JDK and JRE Support for Mac OS X, JDK for Linux on ARM[117]
Java SE 7 Update 7[118]2012-08-304 security fixes[69]
Java SE 7 Update 9[119]2012-10-1630 security vulnerabilities fixes[120]
Java SE 7 Update 10[121]2012-12-11New security features, such as the ability to disable any Java application from running in the browser and new dialogs to warn you when the JRE is insecure, and bug fixes
Java SE 7 Update 11[122]2013-01-13Olson Data 2012i, bugfix for problems with registration of plugin on systems with Stand-alone version of JavaFX Installed, security fixes for CVE-2013-0422;[123] the default security level for Java applets and web start applications has been increased from "Medium" to "High"
Java SE 7 Update 13[124]2013-02-0150 security fixes
Java SE 7 Update 15[125]2013-02-195 security fixes
Java SE 7 Update 17[126]2013-03-042 security fixes
Java SE 7 Update 21[127]2013-04-16Multiple changes including 42 security fixes, a new Server JRE that doesn't include the plug-in, and the JDK for Linux on ARM
Java SE 7 Update 25[128]2013-06-18Multiple changes including 40 security fixes[80][129]
Java SE 7 Update 40[130]2013-09-10New security features, hardfloat ARM, Java Mission Control and Retina Display support[131]
Java SE 7 Update 45[132]2013-10-1551 security fixes,[133] Protections against unauthorized redistribution of Java applications, Restore security prompts, JAXP changes, TimeZone.setDefault change.
Java SE 7 Update 51[134]2014-01-1436 security fixes[135][136]