Java Versions, Features and History


Java Versions, Features and History

  • Released on 23 January 1996, JDK 1.0 version.
  • Released on 19 February 1997 JDK 1.1 version.
    New features in JDK 1.1
    1. JDBC (Java Database Connectivity)
    2. Inner Classes
    3. Java Beans
    4. RMI (Remote Method Invocation)
    5. Reflection (introspection only)
  • Released on 8 December 1998 J2SE 1.2 version.
    New features in J2SE 1.2
    1. Collections framework.
    2. Java String memory map for constants.
    3. Just In Time (JIT) compiler.
    4. Jar Signer for signing Java ARchive (JAR) files.
    5. Policy Tool for granting access to system resources.
    6. Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
    7. Java Plug-in
    8. Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
    9. Audio support in Applets.
  • Released on 8 May 2000 J2SE 1.3 version.
    New features in J2SE 1.3
    1. Java Sound
    2. Jar Indexing
    3. A huge list of enhancements in almost all the java area.
  • Released on 6 February 2002 J2SE 1.4 version.
    New features in J2SE 1.4
    1. XML Processing
    2. Java Print Service
    3. Logging API
    4. Java Web Start
    5. JDBC 3.0 API
    6. Assertions
    7. Preferences API
    8. Chained Exception
    9. IPv6 Support
    10. Regular Expressions
    11. Image I/O API
  • Released on 30 September 2004 J2SE 1.5 version.
    New features in J2SE 1.5
    1. Generics
    2. Enhanced for Loop
    3. Autoboxing/Unboxing
    4. Enum
    5. Varargs
    6. Static Import
    7. Metadata (Annotations)
    8. Instrumentation
  • Released on 11 December 2006 J2SE 1.6 version.
    New features in J2SE 1.6
    1. Scripting Language Support
    2. JDBC 4.0 API
    3. Java Compiler API
    4. Pluggable Annotations
    5. Native PKI, Java GSS, Kerberos and LDAP support.
    6. Integrated Web Services.
    7. Lot more enhancements.
  • Released on 28 July 2011 J2SE 1.7 version.
    New features in J2SE 1.7
    1. Strings in switch Statement
    2. Type Inference for Generic Instance Creation
    3. Multiple Exception Handling
    4. Support for Dynamic Languages
    5. Try with Resources
    6. Java nio Package
    7. Binary Literals, underscore in literals
    8. Diamond Syntax
    9. Automatic null Handling


  • Released on 18th march 2014 JDK 1.8 version.
    New features in JDK 1.8
           

  1. Default and Static methods in Interface
  2. Lambda Expressions
  3. Optional
  4. Streams
  5. Method References
  6. Data Time API
  7. Nashorn Javascript Engine
  8. Parallel Arrays

Can we overload static methods in java

  • Yes. We can overload static methods in java.
  • Method overriding is not possible but method overloading is possible for static methods.
  • Before that lets see about method overloading in java.

Method overloading:

  •  Defining multiple methods with same name and with different arguments is known as method overloading.
  • Multiple methods with same name and different arguments so compile time itself we can tell which method is going to get executed based on method call.
  • Method overloading also known as compile time polymorphism. 

Static methods - method overloading 

  • Its always possibles static method overloading.
  • Defining multiple static methods with same name and different arguments will possible.
  • By this we can define multiple main methods in our class with different arguments but only default main method will be called by the JVM remaining methods we need to call explicitly.
  • Lets see an example java program which explains static method overloading.

  1. class StaticMethodOverloading{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("staticMethod(): Zero arguments");
  6.  
  7.  
  8. public static void staticMethod(int a){
  9.  
  10. System.out.println("staticMethod(int a): one argument");
  11.  
  12.  
  13. public static void staticMethod(String str, int x){
  14.  
  15. System.out.println("staticMethod(String str, int x): two arguments");
  16.  
  17. }
  18.  
  19. public static void main(String []args){
  20.   
  21.   StaticMethodOverloading.staticMethod();
  22.   StaticMethodOverloading.staticMethod(12);
  23.   StaticMethodOverloading.staticMethod("Static method overloading",10);
  24.  
  25. }
  26. }


 Output:

  1. staticMethod(): Zero arguments
  2. staticMethod(int a): one argument
  3. staticMethod(String str, int x): two arguments


Java Program to overload main method in java

  1. class mainMethodOverloading{
  2.  
  3. public static void main(boolean x){
  4.  
  5. System.out.println("main(boolean x) called ");
  6.  
  7.  
  8. public static void main(int x){
  9.  
  10. System.out.println("main(int x) called");
  11.  
  12.  
  13. public static void main(int a, int b){
  14.  
  15. System.out.println("main(int a, int b) called");
  16.  
  17. }
  18.  
  19. public static void main(String []args){
  20.    
  21.  
  22. System.out.println("main(String []args) called ");
  23.  
  24.   mainMethodOverloading.main(true);
  25.   mainMethodOverloading.main(10);
  26.  mainMethodOverloading.main(37,46);
  27.  
  28.  
  29. }
  30. }




 Output:

  1. main(String []args) called
  2. main(boolean x) called
  3. main(int x) called
  4. main(int a, int b) called

Can we override static methods in java

  • Exact answer is NO. We can not override static methods.
  • Before discussing this topic lets see what is static in java. 

Static methods in java:

  •  Static means class level if we declare any data or method as static then those data(variables) and methods belongs to that class at class level.
  • Static variables and static methods belongs to class level.
  • Static methods are not the part of objects state . Belongs to class
  • Without using object we can call these static methods.
 here the detailed explanation on static methods

Instance methods in java:


  • Instance methods will be called at run time.
  • Instance variables and instance methods are object level. variables values may change from one object to another where as static variable values are class level so if we access by using any object and changes that values will effect to all objects means its class level variable.
  •  Lets see about overriding in java.

Method overriding in java:


  •  Defining the super class method in sub class with same signature.
  • Even though in inheritance all properties of supers class can access in sub class we have an option of overriding super class methods in sub class known as method overriding.
  • So by this every-time sub-most object method will be called.

Instance methods - Method Overriding

  
  1. class SuperClassDemo{
  2.  
  3. public void instanceMethod(){
  4.  
  5. System.out.println("SuperClassDemo instanceMethodcalled");
  6.  
  7. }
  8.  
  9. }

  1. class SubClassDemo extends SuperClassDemo{
  2.  
  3. public void instanceMethod(){
  4.  
  5. System.out.println("SubClassDemo instanceMethod called");
  6.  
  7. }
  8. public static void main(String []args){
  9.   
  10.   SuperClassDemo superObj= new SuperClassDemo();
  11.   SuperClassDemo  superobj1= new  SubClassDem(); 
  12.   SubClassDemo subObj= new  SubClassDem(); 
  13.   // here no need to create object to call a static method please note that.

  14.   superObj.instanceMethod();
  15.   superObj1.instanceMethod();
  16.   subObj.instanceMethod();
  17.  
  18. }
  19. }

Output

  1. SuperClassDemo instanceMethodcalled
  2. SubClassDemo instanceMethodcalled
  3. SubClassDemo instanceMethodcalled

 Static methods - method overriding:

  • Lest an example program on static methods in method overriding concept and then discus about this clearly.
  1. class SuperClassDemo{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("SuperClassDemo staticMethod called");
  6.  
  7. }
  8.  
  9. }

  1. class SubClassDemo extends SuperClassDemo{
  2.  
  3. public static void staticMethod(){
  4.  
  5. System.out.println("SubClassDemo staticMethod called");
  6.  
  7. }
  8. public static void main(String []args){
  9.   
  10.   SuperClassDemo superObj= new SuperClassDemo();
  11.   SuperClassDemo  superobj1= new  SubClassDem(); 
  12.   SubClassDemo subObj= new  SubClassDem(); 
  13.   // here no need to create object to call a static method please note that.

  14.   superObj.staticMethod();
  15.   superObj1.staticMethod();
  16.   subObj.staticMethod();
  17.  
  18. }
  19. }



Output

  1. SuperClassDemo staticMethod called
  2. SuperClassDemo staticMethod called
  3. SubClassDemo staticMethod called

 Method Overriding - Method Hiding:

  • Method overriding : in method overriding we will define super class method in sub class with same signature and these methods will be called at run time based on the object.
  • Method Hiding: In method hiding even though super class methods are accesible in sub class they are not the part of sub class so the methods and these methods will be called based on the class.
  • In method Hiding if we define same static method in super class and sub class they are not same they are unique and distinct from the other.



public static void main(String[] args) in Java

  • main method is a standard method used by JVM to execute any java program(Java SE).
  • Lets see an example class without main method.

  1. package instanceofjava;
  2. public Demo{
  3.  
  4. }


  • This class will compile fine but while executing JVM fails to find the main method in that class
  • So it will throw an exception: NoSuchMethodError:main

  1. package instanceofjava;
  2. public Demo{
  3. public static void main(String [] args){
  4.  
  5. }
  • This program will compile and executed. Because at run time JVM calls the main method on that class.

Why main method is public?

  •  To call by JVM from anywhere main method should be public.
  • If JVM wants to call our method outside of our package then our class method should be public.

  1. package instanceofjava;
  2. public MainDemo{
  3. public static void main(String [] args){
  4.  
  5. }
  6. }

public static void main(string args) interview Questions

Why main method is static?

  • To execute main method without creating object then the main method oshould be static so that JVM will call main method by using class name itself.

Why main method return type is void?

  • main method wont return anything to JVM so its return type is void.

 Why the name main?

  • This is the name which is configured in the JVM.

Why the arguments String[] args?

  •  Command line arguments.
  • String array variable name args : by the naming conventions they named like that we can write any valid variable name.

Can we write static public void main(String [] args)?

  • Yes we can define main method like static public void main(String[] args){}
  •  Order of modifiers we can change.

  1. package instanceofjava;
  2. public MainDemo{
  3. static public void main(String [] args){
  4.  
  5. }
  6. }

What are the possible public static void main(String [] args)method declaration with String[] args?

  • public static void main(String[] args){ }
  • public static void main(String []args){ }
  • public static void main(String args[] ){ }
  • public static void main(String... args){ } 
  • Instead of args can place valid java identifier.

Can we declared main method with final modifier?

  • Yes we can define main method with final modifier.

  1. package instanceofjava;
  2. public MainDemo{
  3. public static final void main(String [] args){
  4.  
  5. }

Main method with all possible modifiers:

 

  1. package instanceofjava;
  2. public MainDemo{
  3. static final synchronized public void main(String [] args){
  4.  
  5.  System.out.println("Main method");
  6.  
  7. }

Output:

  1. Main method

Overloading main method:

  • We can declare multiple main methods with same name as per overloading concept.  
  • So we can overload main method but every time JVM looks for main method with String[] args method.
  • Lets see an example program on main method overloading.
  • main(String[] args) method will be called automatically by JVM.
  • If we want to call other methods we need to call explicitly.

 

  1. package instanceofjava;
  2. public MainDemo{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method String [] args");
  6.  
  7. public static void main(int[] args){
  8.  
  9.  System.out.println("Main method int[] args");
  10.  
  11. }
  12.  





Output:

  1. Main method String [] args


Main method Inheritance:

  • Inheritance concept is applicable for main method.
  • If a sub class not having main method and extending a super class which is having main method.
  • Then if we execute super class main method will be executed fine.
  • If we execute sub class which is not having main method also executed fine and super class main method will be called.

  1. package instanceofjava;
  2. public A{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method of class A");
  6.  
  7.  



Output:

  1. Main method of class A

 

  1. package instanceofjava;
  2. public B extends A{
  3.  
Output:

  1. Main method of class A

What happen if both super and sub class having main method?

  • Actually its not overriding concept here. it is a method hiding concept in this scenario regarding with main method.

  1. package instanceofjava;
  2. public A{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method of class A");
  6.  
  7.  

Output:

  1. Main method of class A


  1. package instanceofjava;
  2. public B extends A{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method of class B");
  6.  
  7.  


Output:

  1. Main method of class B

Static block in Java

  • Static variables are class level variables and without instantiating class we can access these variables.

    1. Static int a;


  • Class loading time itself these variables gets memory
  • Static methods are the methods with static keyword are class level. without creating the object of the class we can call these static methods.

    1. public static void show(){ 
    2.  
    3. }

  • Now its time to discuss about static blocks.
  • Static block also known as static initializer
  • Static blocks are the blocks with static keyword.
  • Static blocks wont have any name in its prototype.
  • Static blocks are class level.
  • Static block will be executed only once.
  • No return statements.
  • No arguments.
  • No this or super keywords supported.
  •  
    1. static{ 
    2.  
    3.  }

     

What is the need of static block?

  • Static blocks will be executed at the time of class loading.
  • So if you want any logic that needs to be executed at the time of class loading that logic need to place inside the static block so that it will be executed at the time of class loading. 
  • To initialize the static variables while class loading itself we need static block.
  • If we have multiple classes then if you want to see the order of those classes loading then static block needed.

When to use static blocks?

  • If you want to access static variables before executing the constructor.
  • If you want to execute your code only once even any number of objects created.
  • If you want to initialize static constants.

When and where static blocks will be executed?

  • Static blocks will be executed at the time of class loading by the JVM  by creating separate stack frames in java stacks area (Please refer JVM Architecture  to know about stacks area).
  • Static blocks will be executed in the order they defined from top to bottom.



  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6. static{
  7.       System.out.println("First static block executed");
  8. }
  9.  
  10. static{
  11.      System.out.println("Second static block executed");
  12. }
  13.  
  14. static{
  15.      System.out.println("Third static block executed");
  16. }
  17.  
  18. }
     
Output:
  1. First static block executed
  2. Second static block executed
  3. Third static block executed

Order of execution of static block and main method:

  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6. public static void main (String[] args) throws java.lang.Exception
  7. {
  8.         System.out.println("Main method executed");
  9. }
  10.  
  11. static{
  12.       System.out.println("First static block executed");
  13. }
  14.  
  15. static{
  16.      System.out.println("Second static block executed");
  17. }
  18.  
  19. static{
  20.      System.out.println("Third static block executed");
  21. }
  22.  
  23. }
     
Output:
  1. First static block executed
  2. Second static block executed
  3. Third static block executed
  4. Main method executed


Order of execution of Static block and constructor:

 

  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6. StaticBlockDemo(){
  7.  
  8.   System.out.println("Constructor executed");
  9.  
  10. }
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13.  
  14.     System.out.println("Main method executed");
  15.     StaticBlockDemo obj = new StaticBlockDemo();
  16.  
  17. }
  18.  
  19. static{
  20.       System.out.println("First static block executed");
  21. }
  22.  
  23. static{
  24.      System.out.println("Second static block executed");
  25. }
  26.  
  27. static{
  28.      System.out.println("Third static block executed");
  29. }
  30.  
  31. }
     


Output:
  1. First static block executed
  2. Second static block executed
  3. Third static block executed
  4. Main method executed
  5. Constructor executed

What is the output of following program:


  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6.   static int a=getNum();

  7. public static int getNum(){
  8.  
  9. System.out.println("In method m1()");
  10. return 10;
  11.  
  12. }

  13. public static void main (String[] args) throws java.lang.Exception
  14. {
  15.  
  16.     System.out.println("Main method executed");
  17.   
  18.  
  19. }
  20.  
  21. static{
  22.       System.out.println("First static block executed");
  23. }
  24.  
  25. static{
  26.      System.out.println("Second static block executed");
  27. }
  28.  
  29. static{
  30.      System.out.println("Third static block executed");
  31. }
  32.  
  33. }
     
Output:
  1. In method m1()
  2. First static block executed
  3. Second static block executed
  4. Third static block executed
  5. Main method executed


How Java Technology Change My Life

  • We can not promise you fame, fortune or even a job if you learn the Java Programming
  • Still , It is likely to make your programs better and requires less effort than other languages.
  • We believe that Java technology will help you do the following.

1. Get Started Quickly:

  • Although the java programming is powerful object oriented language, its easy to learn.

2.Write less code

  •  Comparisons of program metrics(class count , method count and so on.) suggest that a program written in java programming language can be four times smaller than the same program written in C++.

3.Write Better code:

  •  Java Programming language encourages good coding practices and automatic garbage collection helps you avoid memory leak.

4.Develop programs more quickly:

  • The Java programming language is simpler than C++  and as such , your development time could be up to twice as fast when writing in it.
  • Your programs also require fewer lines of code.

5.Avoid platform dependencies:

  • You can keep your program portable by avoiding the use of libraries written in other languages.

6.Write once run anywhere:

  • Because applications written in the java programming language are compiled into machine independent bytecode, they run consistently on any java platform.

 7.Distribute software more easily:

  • With Java web start software , users will be able to launch your application with a single click of the mouse .
  • An automatic version check at start up ensures that users are always up to date with the latest version of your software .
  • If an update is available , the java web start software will automatically update their installation.

 What can Java Technology Do?

  • The general purpose , high level java programming language is powerful software platform.
  • Every full implementation of the java platform gives you the following features.

Development Tools:

  • The development tools provide everything you will need for 
  • compiling , 
  • running ,
  • mongering,
  • debugging and documenting your application.  

Application Programming Interface(API):

  • The API provides the core functionality of the java programming language . It offers a wide array of useful classes ready for use in your own applications.

Deployment Technologies:

  • The JDK software provides standard mechanism such as the java web start software  and java plug in software for developing your applications to end users.

User Interface Tool-kits:

  •  The swing and Java 2D tool kits make it possible to create sophisticated Graphical User Interfaces(GUIs).

Integration Libraries:

  • Integration libraries such as Java IDL API, JDBC API, Java Naming and Directory Interface(JNDI)  API, Java RMI and Java remote method invocation over Internet inter -ORB protocol Technology(Java RMI-IIOP technology)  enable database access and manipulation of remote objects.

Static import In java

  • If we want to use any predefined class or user defined class or interface or enum which is present in a package we need to import those  entire packages or those classes so that we can use those classes present inside the package.

  • import packagename.ClassTest;
  • import packagename.*;
  • For example if we want to read some data from keyboard we can use scanner class present in util package.
  • import java.util.Scanner;
  • We can import everything inside a package by using .*
  • import java.util.*;
  • Without importing want to use that class then code seems to like this




  1. package com.instanceofjava;
  2. class A{
  3.   
  4. public static void main(String [] args){
  5.  
  6.    int number;
  7.   java.util.Scanner in = new java.util.Scanner(System.in);
  8.  
  9.     System.out.println("Enter a number to check even or odd");
  10.     number=in.nextInt();
  11.   
  12.  
  13. }
  14. }

  • if we use import no need to mention class name in declaration 


  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class A{
  6.   
  7. public static void main(String [] args){
  8.  
  9.    int number;
  10.   Scanner in = new Scanner(System.in);
  11.  
  12.     System.out.println("Enter a number to check even or odd");
  13.     number=in.nextInt();
  14.   
  15.  
  16. }
  17. }


Static import:

  • Normal imports will import the all the classes so that we can use them. similarly static imports will import all static data so that can use without class name.
  • Static imports introduced in Java 5.
  • Lets see one program without static import.

 Without Static Import:


  1. package com.instanceofjava;
  2.  
  3. class StaticImport{
  4.   
  5. public static void main(String [] args){
  6.  
  7.     System.out.println(Math.PI); //3.141592653589793
  8.     System.out.println(Integer.MAX_VALUE);//2147483647
  9.     System.out.println(Integer.parseInt("123"));//123
  10.  
  11. }
  12. }

Using Static import:

static import in java with example:
  1. package com.instanceofjava;
  2.  
  3.  import static java.lang.Integer.*;
  4.  import static java.lang.Math.*;
  5.  
  6. class StaticImport{
  7.   
  8. public static void main(String [] args){
  9.  
  10.     System.out.println(PI); //3.141592653589793
  11.     System.out.println(MAX_VALUE);//2147483647
  12.     System.out.println(parseInt("123"));//123
  13.  
  14. }
  15. }

static imports in java 1.5 examples:

Importing Math class:

 

  1. package com.instanceofjava;
  2.  
  3.  import static java.lang.Math.*;
  4.  
  5. class StaticImport{
  6.   
  7. public static void main(String [] args){
  8.  
  9.     System.out.println(PI); //3.141592653589793

  10.     double square;
  11.  
  12.     double d1 = 3.0;
  13.     double   d2 = 4.0;
  14.  
  15.     square = sqrt(pow(d1, 2) + pow(d2, 2));
  16.     System.out.println(square);
  17.  
  18. }
  19. }

Importing System class:

 

  1. package com.instanceofjava;
  2.  
  3.  import static java.lang.System.out;
  4.  
  5. class StaticImport{
  6.   
  7. public static void main(String [] args){
  8.  
  9.      out.println("Good morning, " + "java2s");
  10.      out.println("Have a day!");
  11.  
  12. }
  13. }

Importing User defined classes:



  1. package com.instanceofjava;

  2.  
  3. class Colors{
  4.  
  5.      public static int white = 1;
  6.      public static int black = 2;
  7.      public static int red = 3;
  8.      public static int blue = 4;
  9.      public static int orange = 5;
  10.      public static int grey = 6;
  11.      public static int green =7;
  12.  
  13. }


  1. package com.instanceofjava;

  2.  import static com.instanceofjava.Colors.*; 

  3. class StaticImportDemo{
  4.  
  5. public static void main(String [] args){
  6.  
  7.     System.out.println(white );//1
  8.     System.out.println(blue);//4
  9.  
  10. }
  11.  
  12. }


Arrays and Collections:





  1. package com.instanceofjava;

  2.  import static com.instanceofjava.Colors.*; 

  3. class StaticImportDemo{
  4.  
  5. public static void main(String [] args){
  6.  
  7.    int[] array = new int[] {5, 4, 6, 3, 2, 1};
  8.  
  9.         sort(array);
  10.  
  11.      for (int i = 0; i < array.length; i++) {
  12.             System.out.print(array[i]+" ");
  13.       }  
  14.  
  15.   ArrayList al= new ArrayList();
  16.        al.add(1);
  17.         al.add(12);
  18.         al.add(3);
  19.        al.add(2);
  20.  
  21.        sort(al); 

  22.          Iterator itr= al.iterator();
  23.          while(itr.hasNext()){
  24.              System.out.printl(itr.next()+" ");
  25.          }
  26.  
  27. }
  28.  
  29. }

OutPut:

  1. 1 2 3 4 5 6
  2. 1 2 3 12



Advantages and Disadvantages of Static imports in java:

  • One of the advantage of using static imports is reducing keystrokes and re usability.
  • System.out.println() ; we can write as out.println() .  But using eclipse short cut syso (ctrl+sapce)  gives System.out.println() faster than static imports usage. 
  • And there may be a chance of  complexity in readability.
  • If we use class name before method like Math.sqrt() then can understand easily that method belongs to particular class . with static imports reduces readability.
  • One more disadvantage is naming conflicts.
  • If we use Integer.Max_value we cannot use Float.Max_value


Java programming interview questions
  1. Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?
  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

ObjectInputStream and ObjectOutputStream

  • ObjectInputStream and ObjectOutputStream classes are used to store objects state permanently in files or to send to remote computer via network.
  • ObjectOutputStream class is subclass of ObjectOutput interface. It implements below method to write object to underline output stream.

  1. public void writeObject(Object ob)throws IOException

  • ObjectInputStream class is a subclass of ObjectInput interface. It implements below method to read object to underline output stream.
  1. public Object readObject() throws IOException

Rule:

  • To write or send object to external world it must be java.io.Serializable interface type.
  • It means this objects class must be a sub class of java.io.Serializable interface, else write() method throws java.io.NotSerializableException.

Constructors to create above two classes objects:

  • Like DataInputStream and DataOutputStream , ObjectInputStream and  ObjectOutputStream are also can not connect to source and destination directly. So their constructors take other input and output stream class objects.
  1. public ObjectInputStream(InputStream in)
  2. public ObjectOutputStream(OutputStream out)

  1. package instanceofjava;
  2.  
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectOutputStream;
  5. import java.io.Serializable;
  6.  
  7. public class SerDemo implements Serializable {
  8.  
  9.     String name;
  10.     String phonum;
  11.     String address;
  12.     int pin;
  13.  
  14.    public String getName() {
  15.        return name;
  16.     }
  17.  
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.  
  22.     public String getPhonum() {
  23.         return phonum;
  24.    }
  25.  
  26.     public void setPhonum(String phonum) {
  27.         this.phonum = phonum;
  28.     }
  29.  
  30.    public String getAddress() {
  31.         return address;
  32.     }
  33.  
  34.     public void setAddress(String address) {
  35.         this.address = address;
  36.     }
  37.  
  38.    public int getPin() {
  39.         return pin;
  40.     }

  41.   public void setPin(int pin) {
  42.         this.pin = pin;
  43.     }
  44.  
  45. public static void main(String[] args)throws Exception{
  46.  
  47.     SerDemo empobj= new SerDemo();
  48.     empobj.setName("sai");
  49.     empobj.setAddress("xxx, xxxstreet ");
  50.     empobj.setPhonum("040-9999999");
  51.     empobj.setPin(500072);
  52.  
  53.     ObjectOutputStream oos= new ObjectOutputStream(new
  54.     FileOutputStream("E:\\employee.ser"));
  55.  
  56.     oos.writeObject(empobj);
  57.  
  58. }
  59. }




  1. package instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.ObjectInputStream;
  5.  
  6. public class DeserDemo {
  7.  
  8. public static void main(String[] args)throws Exception{   
  9.  
  10.    ObjectInputStream ois= new ObjectInputStream(new FileInputStream("E:\\employee.ser"));
  11.       SerDemo obj= (SerDemo)ois.readObject();
  12.       System.out.println(obj.getAddress()):
  13.  
  14.     }
  15. }

Output:

  1. sai
  2. xxx, xxxstreet 
  3. 500072
  4. 040-9999999

  • This is the actual functionality of ObjectOutputStream and ObjectInputStream: Serialization and deserialization

Serialization:

  • Serialization is the process of converting objects into stream of  bytes and sending them to underlying output stream.
  • Using serialization we can store object state permanently in a destination , for example on remote computer.
  • Serialization operation performed by the writeObject() method of ObjectOutputStream.

Deserialization:

  • Deserialization is the process of converting stream of bytes into original object.
  • Deserialization operation is performed by readObject() of ObjectInputStream.

Rule:

  • Only java.io.serializable type objects are serialized. Serializable is a marker interface, it does not have any methods.  
  • It provides special permission or identity to JVM to serialize Object.
  • If the given object is not of type serializable interface then writeObject() will throw an unchecked exception called java.io.NotSerializableException.

DataInputStream and DataOutPutStream

  • These classes are used to read and write data as primitive type from the underlying InputStreams and Output Streams.
  • DataInputStream and DataOutputStream classes have special methods to perform reading and writing operations as primitive data.

DataInputStream:

  • DataInputStream is a sub class of FilterInputStream and DataInput Interface.
  • It implements  below methods from the DataInput interface for reading bytes from a binary stream and convert them in to corresponding java primitive type.

 DataInputStream methods:

  • public byte readByte()
  • public short readShort()
  • public int readInt()
  • public long readLong()
  • public float readFloat()
  • public double readDouble()
  • public char readChar()
  • public boolean readBoolean()
  • public String readUTF()
  • public String readLine()

DataOutPutStream:

  • DataOutputStream class is a subclass of FilterOutputStream and DataOutput interface.
  • It implements below methods from DataOutput interface for converting data of any java primitive types to a stream of bytes and writing these bytes to a binary stream.


DataOutPutStream Methods:

  • public void writeByte(byte b)
  • public void writeShort(short s)
  • public void writeInt(int i)
  • public void writeLong(long l)
  • public void writeFloat(float f)
  • public void writeDouble(double d)
  • public void writeChar(char ch)
  • public void writeBoolean(boolean b)
  • public void writeUTF(String s)
  • public void writeBytes(String s)

  • To read data as primitive types using above readXxx() methods , the data must be written to the file as primitive types using writeXxx() methods.
  • readXxx() methods must be called in the same order in which the writeXxx() methods are called otherwise wrong value will be returned or EOFException will occur.

Program to Write data as primitive type using DataInputStream


  1. package instanceofjava;
  2.  
  3. import java.io.DataOutputStream;
  4. import java.io.FileOutputStream;
  5.  
  6. public class DOSDemo {
  7.  
  8. public static void main(String [] args) throws Exception{
  9.  
  10.   FileOutputStream fos= new FileOutputStream("data.txt");
  11.   DataOutputStream dos = new DataOutputStream(fos);
  12.  
  13.     dos.writeInt(37);
  14.     dos.writeFloat(2.15f);
  15.     dos.writeChar('c');
  16.     dos.writeBoolean(true);
  17.     dos.writeUTF("instance of java");
  18.  
  19.   }
  20. }



  • After compilation and execution in current working directory you can find the "data.txt".
  • Check data.txt file size.
  • To check file size "right click on the file"-> click on properties
  • You will get size = size of all primitive data types mentioned in program check it.
  • From this program we can prove boolean takes 1 byte, the minimum memory location size in java is 1 byte. 
  • For string data including double quotes JVM provides 1 byte for each character.

Program to Read data as primitive type using DataOutputStream

  1. package instanceofjava;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.FileInputStream;
  5.  
  6. public class DISDemo {
  7.  
  8. public static void main(String [] args) throws Exception{
  9.  
  10.     FileInputStream fis= new FileInputStream("D:\\data.txt");
  11.    DataInputStream dis = new DataInputStream(fis);
  12.  
  13.     int i=    dis.readInt();
  14.    float f=dis.readFloat();
  15.    char ch=dis.readChar();
  16.    boolean b=dis.readBoolean();
  17.    String str= dis.readUTF();
  18.  
  19.     System.out.println(i);
  20.     System.out.println(f);
  21.     System.out.println(ch);
  22.     System.out.println(b);
  23.     System.out.println(str);
  24.  
  25.     }
  26. }

  • Execute the above application by changing readXxx() methods calling order.
  • Then check you will get right value or not.
  • Actually readXxx() method read number of bytes from the file based on the data type.
  • For example if we call readInt() method it read 4 bytes from file.
  • So if our bytes are available in file program executed fine, execution terminates with EOFException.

Limitations in DataInputStream and DataOutputStream:

  • Using DataInputStream and DataOutputstream we can not read and write objects from persistence media.
  • They have only capability to read data up to only primitive data types.

Solution:

  • To read and write objects we must use ObjectInputStream and ObjectOutputStream.

Java 8 Interface Static and Default Methods


Java 8 interface static and default methods

  • Java 8 introduced two new methods in interface they are
    1.default methods
    2.static methods
  • By this interfaces and abstract class are same but still having lot differences like abstract class can have a constructor etc will discuss more before that we need to know about these Java 8 features of interfaces.
  • Defaults methods are also called as defender methods can be implemented inside the interface
  • Like normal class now with java 8 we can declare static methods in side a interface.
  • Lets jump deep into Java 8 default and static methods 

  

1.Interface Default Methods in Java 8


  • Before Java 8 in interfaces we can and able to declare only abstract methods only.
  • If we declare a method without abstract that will be treated as abstract by default.
  • As we know all methods in interfaces are by default abstract methods.
  • These methods wont have body means implementations
  • The class which is implementing this interface need to provide body / implementation for this abstract methods.
  • Now with java 8 default methods we can add methods to interface without disturbing existing functionality.
  • So instead of overriding now we can inherit these default methods from interfaces

  • Defaults methods are also  known as defender methods or virtual extension methods
  • Default methods will help us to avoid utility classes.
  • We can define utility methods inside the interface and use it in all classes which is implementing.
  • One of the major reason to introduce this default methods in java 8 is to support lambda expressions in collections API and to enhance.


  1. package com.instanceofjava;
  2. interface Java8Interface{
  3.  
  4. abstract void show();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. }

  1. package com.instanceofjava;
  2. class Sample implements Java8Interface {
  3.  
  4. void show(){
  5. System.out.print("overridden method ")
  6.  }
  7. public static void main(String[] args){
  8.   
  9. Sample obj= new Sample();
  10.  
  11. obj.show(); // calling implemented method
  12. obj.display(); // calling inherited method
  13. Java8Interface.display(); calling using interface name
  14.  
  15. }
  16.  
  17. }



Output:

 

  1. overridden method
  2. default method of interface
  3. default method of interface


How to call default methods:

 

  • We can all these default methods by using interface name and also by using object of the class which is implementing.
  • From above example
  • obj.show(); // calling implemented method
  • obj.display(); // calling inherited method
  • Java8Interface.display(); calling using interface name

Can we override java 8 default method

  • As we discussed above default methods in interfaces are implemented methods with bodies
  • Yes we can override same method in class which is implementing this interface.
  • Lets see one sample program how to override and what happens if we override


  1. package com.instanceofjava;
  2. interface InterfaceWithDefault{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. class Demo implements InterfaceWithDefault{
  3.  
  4. void defMethod(){
  5.  
  6. System.out.print("overridden method in class Demo ") 
  7.  
  8.  }
  9. public static void main(String[] args){
  10.   
  11. Demo obj= new Demo();
  12.  
  13. obj.defMethod(); // calling overridden method
  14. Java8Interface.defMethod(); calling using interface name : interface defMethod will be called
  15.  
  16. }
  17.  
  18. }

Output:


  1. overridden method in class Demo
  2. default method of interface

What happens if we implement two interfaces having same default methods

  • Now lets see if a class implementing two interfaces which are having same default methods
  • Whatever the implementation in the two interfaces defined if we implementing two interfaces which are having a default method in both then compilation error will come if two methods have same signature. works fine if two methods have same name with different arguments.
  • Check the below example programs to understand more.


  1. package com.instanceofjava;
  2. interface A{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface: A");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. interface B{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("default method of interface: B");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. class Demo implements A, B{ // compilation error will come
  3.  
  4. public static void main(String[] args){
  5.   
  6. Demo obj= new Demo();
  7.  
  8.  
  9. }
  10.  
  11. }


  • If we implement two interfaces which are having same method with same parameters then compilation error will occur.
  • Duplicate default methods named "defMethod" with the parameters () and () are inherited from the types A and B.
  • If we define two methods with different type of parameters then we can work with both interfaces.



  1. package com.instanceofjava;
  2. interface A{
  3.  
  4. default void defMethod(){
  5.  
  6. System.out.println("Default method of interface: A");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. interface B{
  3.  
  4. default void defMethod(String str){
  5.  
  6. System.out.println("Default method of interface: B");
  7. System.out.println(str);
  8.  
  9.  
  10. }
  11.  
  12. }

  1. package com.instanceofjava;
  2. class Demo implements A, B{ // compilation error will come
  3.  
  4. public static void main(String[] args){
  5.   
  6. Demo obj= new Demo();
  7. obj.defMethod();
  8. obj.defMethod("Java 8")
  9.  
  10.  
  11. }
  12.  
  13. }

Output:

  1. Default method of interface: A
  2. Default method of interface: B 
  3. Java 8


1.Interface Static Methods in Java 8

  • Another Java 8 interface method is static method.
  • Now we can define static methods inside interface but we can not override these static methods.
  • These static method will act as helper methods.
  • These methods are the parts of interface not belongs to implementation class objects.

  1. package com.instanceofjava;
  2. interface StaticInterface{
  3.  
  4. Static void print(String str){
  5.  
  6. System.out.println("Static method of interface:"+str);
  7.  
  8. }
  9. }

  1. package com.instanceofjava;
  2. class Demo implements StaticInterface{
  3.  
  4. public static void main(String[] args){
  5.   
  6.  StaticInterface.print("Java 8")
  7.  
  8. }
  9.  
  10. }

Output:

  1. Static method of interface: Java 8


8 New Java 8 Features



Java 8 features

  1. Default and Static methods in Interface
  2. Lambda Expressions
  3. Optional
  4. Streams
  5. Method References
  6. Data Time API
  7. Nashorn Javascript Engine
  8. Parallel Arrays

 

 

 

1.Default and Static methods in Interface :

  • Java 8 introduces new features to interfaces.
  • Before java 8 interface having only abstract methods but now java 8 added two more type of methods to interface !.
  • First one is default method. A method which is having a default keyword with method body.
  • Actually interfaces wont have any implemented methods  but now with java 8 default method we can add a method with default implementation by using "default " keyword.
  • The classes which are implementing this interface can use these default method and same time it can override the existing method. But its not mandatory to override.

  1. package com.instanceofjava;
  2. interface Java8InterfaceDemo{
  3.  
  4. abstract void add();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. }


  • The second new method introduced in java 8 is static method.
  • Yes like in classes now we can define a static methods inside interface by using "static".
  • Basically static methods which are defined in interface are interface level only. if we want to call these static methods which are defined in interfaces we need to use interface name so that we can access these methods.

  1. package com.instanceofjava;
  2. interface Java8InterfaceDemo{
  3.  
  4. abstract void add();
  5.   
  6. default void display(){
  7.  
  8. System.out.println("default method of interface");
  9.  
  10. }
  11.  
  12. public static void show(){
  13.  
  14. System.out.println("static method of interface");
  15.  
  16. }
  17.  
  18. }

2.Lambda Expressions 

  • One of the most awaited and biggest release in java 8 is lamda expressions.
  • Ability to pass functionality/ behavior  to methods as arguments.
  • Allows us to write a method in the same place we are going to use it.

  1. package com.instanceofjava;
  2. interface JavalamdaExpression{
  3.  
  4. public static void main(String[] args){
  5.  
  6.  Arrays.asList( "j", "a", "v" ,"a","8").forEach( e -> System.out.print( e ) );
  7.  // java8
  8. }
  9.  
  10. }



3.java.util.Optional:

  • One of the best and cool feature of java 8 is Optional class. Which is a final calls from java.util package.
  • The major repeating statement in every project is checking "NullPointerException". Before using any object we need to check whether it is null or not if its not null then only we need to proceed.
  • Optional is just like a container which holds a value of type <T> or "null". By using isPresent() method of Optional class we can check particular object is null not not.


  1. package com.instanceofjava;
  2. import java.util.Optional:
  3. class Java8OptionalDemo{
  4.  

  5.  
  6. public static void main(String[] args ){
  7.  
  8.  Optional< String > str = Optional.ofNullable( null );
  9.  System.out.println( "str having value ? " + str.isPresent() ); // output : str having value ? false
  10.  
  11. }
  12.  
  13. }



4.Streams:

  • One of the excellent feature from java 8 as java.util.stream.
  • Stream API  introduces real-world functional-style programming into the Java.
  • Provides functional operations on stream of elements such as list , set and map 
  • Supports filtering, mapping and removal of duplicates of elements in collections, are implemented lazily.
  • Now we can get Streams from collections, arrays and bufferedReaders etc.


  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3. class Java8StreamsDemo{
  4.  
  5. public static void main(String[] args ){
  6.  
  7.   Arrays.stream(new int[] {1, 2, 3,4,5})
  8.     .map(n -> 2 * n + 1) 
  9.    .average()
  10.     .ifPresent(System.out::println); // output: 7.0
  11.  
  12.  
  13. }
  14.  
  15. }

5.Method Reference:

  • We can use lambda expressions to create anonymous methods. 
  • Sometimes, however, a lambda expression does nothing but call an existing method.
    In those cases, it's often clearer to refer to the existing method by name.
  • Using Method references refer to the existing method by name, they are compact, easy-to-read lambda expressions for methods that already have a name


  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3.  
  4. class Java8MethodRef{
  5.  
  6.   public  void show(String str){
  7.  
  8.         System.out.println(str);
  9.  
  10.    }
  11.  
  12. public static void main(String[] args ){
  13.  
  14.    Arrays.asList("a", "b", "c").forEach(new A()::show); // a b c

  15.  
  16. }
  17.  
  18. }

6.Data Time API  

  • The next cool feature from java 8 is new date time API(jsr 310) added within java.time package.
  • Before java 8 if we want to format dates we use SimpleDateFormatter class in java 8 while declaring date itself it has constructor to pass format of date.
  •  Some of the new classes introduced in java 8 date time are as follows.
  1. LocalTime
  2. LocalDate 
  3. LocalDateTime
  4. OffsetDate
  5. OffsetTime
  6. OffsetDateTime




  1. package com.instanceofjava;
  2. import java.util.Arrays;
  3.  
  4. class Java8DateTimeAPI{
  5.  
  6. public static void main(String[] args ){
  7.          
  8.     LocalDate currentDate = LocalDate.now();
  9.     System.out.println(currentDate);
  10.     
  11.     LocalDate twentyMarch2015 = LocalDate.of(2015, Month.MARCH, 06);
  12.     System.out.println(twentyMarch2015);  //2015-03-06
  13.  
  14.      LocalDate firstApril2015 = LocalDate.of(2015, 4, 1);
  15.      System.out.println(firstApril2015);//2015-04-01

  16.  
  17. }
  18.  
  19. }

 

7.Nashorn Javascript Engine


  •  Java 8 come with new Nashorn Javascript Engine which is allowing us to develop and run JavaScript applications.


  1. package com.instanceofjava;
  2.  
  3. import javax.script.ScriptEngine;
  4. import javax.script.ScriptEngineManager;
  5. import javax.script.ScriptException;
  6.  
  7. import java.util.Arrays;
  8.  
  9. class Java8JavaScript{
  10.  
  11. public static void main(String[] args ){
  12.          
  13.   ScriptEngineManager manager = new ScriptEngineManager();
  14.   ScriptEngine engine = manager.getEngineByName( "JavaScript" );
  15.   System.out.println( engine.getClass().getName() );
  16.   System.out.println( "output:" + engine.eval( "function show() { return 10; }; show();" ) );
  17.  
  18. }
  19.  
  20. }

  1. jdk.nashorn.api.scripting.NashornScriptEngine
  2. output:10


8.Parallel Array Sorting

  • As of now java 7 we already having Arrays.sort() method to sort objects now java 8 introduced parallel sorting which has more speed than arrays.sort() and follows Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads that are available in the thread pool.
  • Java 8 added parallel sorting functionalities to java.util.Arrays to take advantage of multithread machines 


  1. package com.instanceofjava;
  2. import java.util.Arrays;

  3. class Java8JavaScript{
  4.  
  5. public static void main(String[] args ){
  6.          
  7.          int arr[]={1,4,2,8,5};
  8.          Arrays.parallelSort(arr);
  9.  
  10.          for(int i:arr){  
  11.              System.out.println(i);  
  12.            } 
  13.  
  14. }
  15.  
  16. }



You might like:
Select Menu