Top 7 Java 7 features

java 7 features with examples
Java 7 features


  1. String in switch statements
  2. Type inference for generic instance creation.
  3. The try with resources Statement.
  4. Multiple exception handling System.
  5. Underscored in Numeric literals
  6. Binary Literals with Prefix 0b
  7. java.nio.file package






1.String in switch statements:

  • Did you know previous to java 7 you could do a switch on
    1. char
    2. byte
    3. int
    4. Character
    5. Byte
    6. Integer

  • Java 7 adds String making the switch instruction much friendlier to String inputs
  • The alternative before was to do with if  else statements paired with a bunch of String equal() calls .
  • The result much cleaner and compact code.
  • Here the java 7 switch with string 
  • One of the java 7 new feature strings in switch 
 Example program on java 7 new feature string in switch:

  1. package com.instanceofjavaforus;
  2.  
  3. public class Demo{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  String color="green";
  8.  
  9. switch(color){
  10.  
  11.    case "white": System.out.println("white");
  12.       break;
  13.  
  14.    case "green": System.out.println("green");  
  15.       break;
  16.  
  17.    case "red": System.out.println("red"); 
  18.      break; 
  19.  
  20.    case "yellow": System.out.println("yellow"); 
  21.      break; 
  22.  
  23.    case "blue": System.out.println("blue");    
  24.        break;  
  25.  
  26.    case "pink": System.out.println("pink");
  27.       break; 
  28.  
  29.    case "violet": System.out.println("violet"); 
  30.        break;  
  31.  
  32.      
  33.    default: System.out.println("invalid color")
  34. }
  35. }



 

2.Type inference for generic instance creation:

  • Previously when we are using generics you had to specify the type twice, in the declaration and the constructor
  • Before java 7 to create arraylist of string type
  • List<String> str= new ArrayList<String>();
  • In java 7 you just use the diamond <> operator without the type.
  • List<String> str= new ArrayList<>();

  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  List<String> lst= new ArrayList<>();
  8.   lst.add("ABC");
  9.   lst.add("XYZ");

  10. }
  11. }

 

3.The try with resources Statement:

 

  • The new try statement allows opening up a "resource" in atry block and automatically closing the resource when the block is done.
  • For example in the below piece of code we opened a file print line by line to stdout.
  • But pay close attention to the finally block.



  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  BufferedReader in=null;
  8. try{
  9. in= new BufferedReader(new filereader("test.txt"));
  10. String line=null;
  11. while((line=in.readLine())!=null)){
  12. System.out.println(line);
  13. }
  14. }catch(IOException e){
  15.  e.printStackTrace();
  16. }
  17. finally{
  18. try{
  19. if(in!=null)
  20. in.close();
  21.  }
  22. catch(IOException e){
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. }



  • when using a resource that has to be closed , a finally block is needed to make the clean up code is executed eve if there are exceptions thrown back.
  • The new try catch with resources allows us to automatically close these resources in a more compact set of code.

  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7. try(
  8. BufferedReader  in= new BufferedReader(new filereader("test.txt"))
  9. )
  10. {
  11.  
  12. String line=null;
  13. while((line=in.readLine())!=null)){
  14. System.out.println(line);
  15. }

  16. }catch(IOException e){
  17.  e.printStackTrace();
  18. }
  19. }
  20. }

 

4.Multiple exception handling System:

  • Tired of repetitive error handling code ?
  • APIs like java.io and java.lang.reflect?


  1. package com.instanceofjava;
  2.  
  3. public class Demo{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  try{
  8. Class a= Class.forName("wrongclassname");
  9. Object instance=a.newInstance();

  10. }
  11. catch( ClassNotFoundException e){
  12. System.out.println("Failed to create instance") ;
  13. }
  14. catch( IllegalAccessException e){
  15. System.out.println("Failed to create instance") ;
  16. }
  17. catch( InstanctiationException e){
  18. System.out.println("Failed to create instance") ;
  19. }
  20.  

  21. }
  22. }

  • When the exception handling is basically the same, the improved catch operator now supports
    multiple exceptions in a single statement separated by "|".

  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  try{
  8. Class a= Class.forName("wrongclassname");
  9. Object instance=a.newInstance();

  10. }
  11. catch( ClassNotFoundException  | IllegalAccessException  | InstanctiationException ex ){
  12. System.out.println("Failed to create instance") ;
  13. }
  14.  

  15. }
  16. }

  

5.Underscored in Numeric literals:


  1. package com.instanceofjava;
  2.  
  3. public class Java7FeatureTutorial{
  4.  
  5. public static void main(String args[]){
  6.  
  7. int value = 1_000_000;  
  8.  
  9. long Atmcardnumber =  0123_4567_8901_2345L; //16 digit number
  10.  
  11. long ssn = 777_99_8888L;
  12.  
  13. double pi = 3.1415_9265;
  14.  
  15. float  pifloat = 3.14_15_92_65f;

  16. }
  17. }

6.Binary Literals with Prefix 0b:



  1. package com.instanceofjava;
  2.  
  3. public class Java7FeatureTutorial{
  4.  
  5. public static void main(String args[]){
  6.  
  7. // An 8-bit 'byte' value:
  8. byte byte = 0b00100001;
  9.  
  10. // A 16-bit 'short' value:
  11. short short = 0b0010001010001010;
  12.  
  13. // Some 32-bit 'int' values: 
  14. int a = 0b10100001010001011010000101000101;
  15.  
  16. int b= 0b101;
  17.  
  18. int c = 0B101; // The B can be upper or lower case.

  19. }
  20. }

 

7.java.nio.file package:

  • java 7 introduced java.nio and sub package java
  • java.nio.file
  • java.nio.file.attribute
  • Support for input output file. and to access default file system.  

You might like:

PrintStream Class

  • This class is filer output Stream  class, It adds functionality to another output stream , namely the ability to print representation of various data values conveniently.
  • It is the most convenient class in writing data to another output stream, because of below three reasons.

  1. Unlike other output stream's write() method , write() method of this class never throws an IOException.
  2. Calling flush() method is optional, it is called automatically.
  3. In addition to default write() methods  it is defined new methods called print() and println(). These two methods are overloaded to print all types of java data type values including object. Below are the overloaded print() and println() methods list.
  1. public void print(int x);
  2. public void print(long x);
  3. public void print(float x);
  4. public void print(double x);
  5. public void print(char x);
  6. public void print(boolean x);
  7. public void print(char[] x);
  8. public void print(String x); 
  9. public void print(Object x); 
  1. public void println(int x);
  2. public void println(long x);
  3. public void println(float x);
  4. public void println(double x);
  5. public void println(char x);
  6. public void println(boolean x);
  7. public void println(char[] x);
  8. public void println(String x); 
  9. public void println(Object x);  
  10. public void println();
  • PrintStream class object is created in System class using a static variable called out.
  • So we can access above methods from our class using System class's PrintStream object as shown below.
  • System.out.print("abc");
  • System.out.println("abc");
  • System is predefined class in java.lang package.
  • out is static referenced variable of type PrintStream class. It is created in System class to hold PrintStream class object.
  • println() and print() methods are non static methods defined in PrintStream class to print data.

Difference between print() and println():

  • print() method places cursor in the same line after printing data, so that next coming output will be printed in the same line.
  • But println() method places cursor in the next line after printing data so that next coming output will be printed  in the next line.
What is the output of below program?

  1. package com.instanceofjavaforus;
  2.  
  3. public class PrintDemo{
  4.  
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.        System.out.print("A");
  9.        System.out.println("B");
  10.        System.out.println('C');
  11. }
  12. }




  1. AB
  2. C


Rule #1:

  • We can not call print method without passing arguments because we do not have no argument print method so it leads to Compilation Error.
  • But we can call println() method without passing arguments because we have no argument println() method , it prints new line.
What is the output of below program?

  1. package com.instanceofjavaforus;
  2.  
  3. public class PrintDemo{
  4.  
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.        System.out.println("A");
  9.        System.out.println();
  10.        System.out.println("B"); 
  11.        System.out.print();   // Compilation Error
  12.       System.out.println("B"); 
  13.  
  14. }
  15. }

Rule #2:

  • We cannot call print() or println() methods by passing null literal directly.
  • System.out.println(null);
  • It leads to Compilation Error : Ambiguous error. 
  • Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.
  • Method Overloading:
        1.public void prinltln(String str) { }
        2.public void prinltln(char[] ch){ }
        3.public void prinltln(Object ch){ }
What is the output of below program?

  1. package com.instanceofjavaforus;
  2.  
  3. public class PrintDemo{
  4.  
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.        System.out.println(null); // Compilation Error
  9.        System.out.print(null); // Compilation Error
  10.      
  11.  
  12. }
  13. }

 

Difference between println(Object) and writeObject(Object) methods?

  • writeObject(Object) method serializes the given object and sends its state to underlying output stream. 
  • where as println(Object) method does not perform serialization instead it prints the passed object information that is returned by the toString() method.
  • It means println(Object) method internally calls toString() on given object to print the given object information .
  • If toString() method is not defined in the passed object's class it will call Object class toString() method which is originally defined.
  • toString() method in object class returns current object classname@hashcode in hexadecimal string format.

What is the output of below program?
  • toString() method is not overridden in Example class

  1. package com.instanceofjava;
  2.  
  3. public class Example{
  4.  
  5.   int x, int y;
  6.  
  7.   public static void main(String[] args) {
  8.  
  9.     Example obj = new Example();
  10.        obj.x=1;     
  11.        obj.y=2;
  12.        System.out.println(obj);
  13.       
  14. }
  15. }




  1. com.instanceofjava.Example@53601a4f



What is the output of below program?
  • toString() method is not overridden in Example class

  1. package com.instanceofjava;
  2.  
  3. public class Example{
  4.  
  5.   int x, int y;
  6.  
  7. public String toString(){
  8.    return "x="+x+" "+"y="+y;
  9. }
  10.  
  11.   public static void main(String[] args) {
  12.  
  13.     Example obj = new Example();
  14.      obj.x=1;
  15.      obj.y=2;

  16.        System.out.println(obj);
  17.       
  18. }
  19. }



InputStream vs OutputStream

  • For each type of source and destination in java.io package oracle given a separate class.

InputStream Class:

  • ByteArrayInputStream
  • FileInputStream
  • FilterInputStream
    • BufferedInputStream
    • DataInputStream
    • LineNumberInputStream
    • PushbackInputStream
  • ObjectInputStream
  • PipeInputStream
  • SequenceInputStream
  • StringBufferInputStream

IputStream Class Methods:

  • Since InputStream class is the super class for all input stream classes. It has below methods with general implementation for all sub classes.

1.public int available() throws IOException :

  • Checking available bytes to read.

2.public abstract int read() throws IOException :

  • Reading byte-by-byte.

3.public int read(byte[] b) throws IOException :

  • Reading all  bytes.

4.public int read(byte[] b, int off, int length) throws IOException :

  • Reading selected range of bytes.

5.public boolean markSupported() :

  • Checking is this Stream supports marking.

6.public void mark(int readLimit) :

  •  Marking current position of stream.

7.public void reset() throws IOException :

  • Placing the control at marked place.

8.public long skip(long n) throws IOException :

  • Skip reading given range of bytes.

9.public void close() throws IOException :

  • Closing the stream.

OutputStream Class:

  • ByteArrayOutputStream
  • FileOutputStream
  • FilterOutputStream
    • BufferedOutputStream
    • DataOutputStream
    • PrintStream
  • ObjectOutputStream
  • PipeOutputStream

OutputStream class methods:

  • Since OutputStream is the super class of all binary output stream classes it has below method with general implementation for all sub classes.

1.public abstract void write(int i)throws IOException:

  • Writing one by at time to an output stream.

2.public void write(byte[] b) throws IOException :

  • Writing stream of bytes to an output stream.

3.public void write(byte []b , int off, int length) throws IOException :

  • Writing range of stream of bytes to an output stream.

4.public void flush() throws IOException :

  • Flush all bytes to destination from output Stream.

5.public void close() throws IOException :

  • Close output stream.

FileInputStream and FileOutputStream:

  • These classes are used to read and write data as byte from File.
  • Basically these two streams are used as basic data source and destination for other streams.

DataInputStream and DataOutputStream:

  • These two classes are used to read and write data as primitive data.
  • Basically these two streams are used to add capability to another input stream and output stream to read and write data as primitive types.

ObjectInputStream and ObjectOutputStream:

BufferedInputStream and BufferedOutputStream:

  •  These two classes are used to read and write data as buffers.
  • Basically these two streams are used to improve reading and writing performance of other streams.

SequenceInputStream:

  • This class is used to read data from multiple InputStreams Sequentially.

 PrintStream: 

  • PrintStream class is filter output stream class .
  • Its adds functionality to another OutputStream, namely the ability to print representations of various data values conveniently.


Basic steps to perform IO Operations:

  • Create stream class object based on source and destination.
  • Call read() method to read data from the source.
  • Call write() method to write data to the destination.
For instance , to perform IO Operations on files we must create
  • FileInputStream
  • FileOutputStream or
  • FileReader
  • FileWriter  Streams class objects
-
You might like:

Multiply two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Multiply2Matrices{
  6.  
  7.    public static void main(String args[])
  8.    {
  9.  
  10.       int m, n, p, q, sum = 0, c, d, k;
  11.  
  12.       Scanner in = new Scanner(System.in);
  13.  
  14.       System.out.println("Enter the number of rows and columns of first matrix");
  15.  
  16.       m = in.nextInt();
  17.       n = in.nextInt();
  18.  
  19.       int first[][] = new int[m][n];
  20.  
  21.      System.out.println("Enter the elements of first matrix");
  22.  
  23.       for ( c = 0 ; c < m ; c++ )
  24.          for ( d = 0 ; d < n ; d++ )
  25.             first[c][d] = in.nextInt();
  26.  
  27.       System.out.println("Enter the number of rows and columns of second matrix");
  28.  
  29.       p = in.nextInt();
  30.       q = in.nextInt();
  31.  
  32.      if ( n != p )
  33.          System.out.println("Matrices with entered orders can't be multiplied with each other.");
  34.       else
  35.       {
  36.          int second[][] = new int[p][q];
  37.          int multiply[][] = new int[m][q];
  38.          System.out.println("Enter the elements of second matrix");
  39.  
  40.          for ( c = 0 ; c < p ; c++ )
  41.             for ( d = 0 ; d < q ; d++ )
  42.                second[c][d] = in.nextInt();
  43.  
  44.          for ( c = 0 ; c < m ; c++ )
  45.          {
  46.             for ( d = 0 ; d < q ; d++ )
  47.             {   
  48.                for ( k = 0 ; k < p ; k++ )
  49.                {
  50.                   sum = sum + first[c][k]*second[k][d];
  51.                }
  52.                multiply[c][d] = sum;
  53.                sum = 0;
  54.             }
  55.          }
  56.  
  57.          System.out.println("Multiplication of entered matrices:-");
  58.  
  59.          for ( c = 0 ; c < m ; c++ )
  60.          {
  61.             for ( d = 0 ; d < q ; d++ )
  62.                System.out.print(multiply[c][d]+"\t");
  63.             System.out.print("\n");
  64.          }
  65.  
  66.       }
  67.  
  68.    }
  69. }  

OutPut:


  1. Enter the number of rows and columns of first matrix
  2.  
  3. 2 2
  4.  
  5. Enter the elements of first matrix
  6.  
  7. 2 2
  8. 2 3
  9.  
  10. Enter the number of rows and columns of second matrix
  11.  
  12. 2 2
  13.  
  14. Enter the elements of second matrix
  15.  
  16. 1 1
  17. 1 1
  18.  
  19. Multiplication of entered matrices:-
  20.  
  21. 4    4    
  22. 5    5  


add two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Add2Matrix
  6. {
  7.  
  8.    public static void main(String args[])
  9.    {
  10.  
  11.       int rows, cols, c, d;
  12.  
  13.       Scanner in = new Scanner(System.in);
  14.  
  15.       System.out.println("Please Enter number of rows and columns");
  16.  
  17.       rows = in.nextInt();
  18.       cols  = in.nextInt();
  19.  
  20.       int first[][] = new int[rows][cols];
  21.       int second[][] = new int[rows][cols];
  22.       int sum[][] = new int[rows][cols];
  23.  
  24.       System.out.println("Please Enter elements of first matrix");
  25.  
  26.       for (  c = 0 ; c < rows ; c++ )
  27.          for ( d = 0 ; d < cols ; d++ )
  28.             first[c][d] = in.nextInt();
  29.  
  30.       System.out.println("Please Enter elements of second matrix");
  31.  
  32.       for ( c = 0 ; c < rows ; c++ )
  33.          for ( d = 0 ; d < cols ; d++ )
  34.             second[c][d] = in.nextInt();
  35.  
  36.       for ( c = 0 ; c < rows ; c++ )
  37.          for ( d = 0 ; d < cols ; d++ )
  38.              sum[c][d] = first[c][d] + second[c][d];  //replace '+' with '-' to subtract matrices
  39.  
  40.       System.out.println("Sum of entered matrices:-");
  41.  
  42.       for ( c = 0 ; c < rows ; c++ )
  43.       {
  44.          for ( d = 0 ; d < cols ; d++ )
  45.             System.out.print(sum[c][d]+"\t");
  46.          System.out.println();
  47.       }
  48.    }

  49.  }
  50.    
     

 

Output:

  1. Please Enter number of rows and columns
  2.  
  3. 3
  4. 3
  5.  
  6. Please Enter elements of first matrix
  7.  
  8. 1 1 1
  9. 1 1 1
  10. 1 1 1
  11.  
  12. Please Enter elements of second matrix
  13.  
  14. 2 2 2
  15. 2 2 2
  16. 2 2 2
  17.  
  18. Sum of entered matrices:-
  19.  
  20. 3    3    3    
  21. 3    3    3    
  22. 3    3    3  

You might like:



IO Streams

The basic idea of  IOStreams is
  • Storing and reading data from files
  • reading data from keyword
First let us understand some basic terminology.

Persistent media:

  • The environment that allows us to store data permanently is called persistent media.
  • We can store data permanently in three places
  1. File
  2. Database
  3. Remote Computer 

Persistence:

  •  The process of storing data permanently in a persistence media.

Persistence Logic:

  • The logic that persist data in a persistence media is called persistence logic.
  • Ex: IOStreams based logic, JDBC logic, Networking based logic.

Persistence Technologies:

  •  The technology that provides API to develop persistence logic is called persistence technology.
  • Well known persistence technologies are 
  1. IOStreams : to persist data in files
  2. JDBC, EJB, Hibernate: to persist data in db
  3. Networking: to persist data in remote computer

Where can we store data permanently? 

  • In persistence medias either files or in databases.
  • Storing data in variables and arrays  is temporary. Data will be lost when a local variable goes out of scope or when the program terminates.
  • programmers use files or databases for long term storage of large amount of data. it is available even after termination of the program. We refer to data maintained on files as persistent data, because the data exists beyond the duration of the program execution.
  • To store data in files and databases  Oracle has given in  built API. We all need to do is creating the particular class object calling methods for storing and reading data from that persistence media.
  • IOStreams API is given to store and read data from files
  • JDBC API is given to store and read data from Databases. 

How java application can store or read data from a file?

  • Using stream object.

Introduction to Streams:

  • Stream is logical connection between java program and a file.
  • To store the data in the persistence media there should be a way to connect to persistence media from java application either physically or logically. Stream provides logical connection.
  • "Its a continuous flow of data between java program and persistence media"

Direction of stream flow:

  • Stream has a direction and its direction depends on the viewer's view. In java the viewer is java Application. If you look from Java Application it is sending out from Java Application.


Type of Streams:

  • Generally Streams are divided in to two types based on data flow direction.
  1. InputStream.
  2. OutPutStream.

InputStream:

  • The stream that allows data to come into the java application from the persistent media is called input Stream.

OutPutStream:

  • The stream that allows data to send out from the java application to be stored into the persistence media is called OutPutStream.
  • Basically InputStreams are used to read data from a persistence media , and Oputstreams are used to write or store  data in a persistence media from a java application

Types of Java Streams:

  • In java we are allowed to send data through streams only either in the format of bytes or characters. So based on the type of the data passed through streams .
  • In java streams are divided in to two types.
  1. Binary Streams.
  2. Character Streams.

 1.Binary Streams: 

  • The streams which read and write data in the format of  bytes is called Character streams.

 2.Character Streams:

  • The streams which read and write data in the format of  characters is called Character streams.
Java Streams

Programing Inrerview Questions on try catch

1. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class Demo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.      try{
  8.  
  9.     System.out.println("instance of java");    
  10.  
  11.     }
  12.  
  13. }
  14. }





2. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class Demo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.      try{
  8.  
  9.     System.out.println("try block");   
  10.  
  11.     }
  12.    finally{
  13.  
  14.     System.out.println("finally block");    
  15.  
  16.   }
  17.  
  18. }
  19. }







3. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StringDemo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.             
  8.         try {
  9.  
  10.             int a = 0;
  11.             int b = 10;
  12.             int c = b / a;
  13.  
  14.             System.out.print("try block");
  15.  
  16.         }
  17.         catch(Exception e) {
  18.  
  19.               System.out.print("catch block");
  20.  
  21.         }    
  22.  
  23. }
  24. }




String programing interview questions

1. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StringDemo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.       String str="I love java";
  8.       System.out.println(str.charAt(3));
  9. }
  10. }



2. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StringDemo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.       String str="I love java";
  8.       System.out.println(str.length());
  9. }
  10. }








3. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StringDemo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.       String str1="abc";
  8.       String str2="abc";
  9.  
  10.        System.out.println(str1.equals(str2));
  11. }
  12. }






4. what is the output of following program:

  1. package com.instanceofjavaforus;
  2.  
  3. public class StringDemo{
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.         String str1 = "abc";
  8.         String str2 = "abc";
  9.         String str3= new String("abc");
  10.  
  11.         System.out.println("str1 == str2 ? "+(str1==str2));
  12.         System.out.println("str1 == str3 ? "+(str1==str3));
  13.         System.out.println("str1 equals str3 ? "+(str1.equals(str3)));
  14.  
  15.  
  16. }
  17. }






Inheritance programming interview questions

1. what is the output of following program:

  1. package com.instanceofjava;
  2.  
  3. public class SuperDemo{

  4. public void show(){
  5.  
  6.   System.out.println("super class method called");
  7.  
  8. }
  9.  
  10. }

  1. package com.instanceofjava;
  2. public class SubDemo extends SuperDemo{

  3. public void show(){
  4.  
  5.   System.out.println("sub class method called");
  6.  
  7. }
  8.  public static void main(String args[]){
  9.  SubDemo subobj=new SubDemo();
  10.  subobj.show();
  11. }







2. what is the output of following program:

  1. package com.instanceofjava;
  2.  
  3. public class SuperDemo{

  4.  int x;

  5. }

  1. package com.instanceofjava;
  2. public class SubDemo extends SuperDemo{
  3.  
  4.  int y;
  5.  
  6. public void show(){
  7.  
  8.  super.x=y+2;
  9.   System.out.println("x="+super.x+"y="+y);
  10.  
  11. }
  12.  
  13.  public static void main(String args[]){
  14.  
  15.  SubDemo subobj=new SubDemo();
  16.  subobj.show();
  17.  
  18. }




3. what is the output of following program:

  1. package com.instanceofjava;
  2.  
  3. public class SuperDemo {

  4.  int x;

  5. }

  1. package com.instanceofjava;
  2.  
  3. public class SubDemo extends SuperDemo{
  4.  
  5.  int y;
  6.  
  7. public void show(){
  8.  
  9.  super.x=y+2;
  10.   System.out.println("x="+super.x+"y="+y);
  11.  
  12. }
  13.  
  14.  public static void main(String args[]){
  15.  
  16.  SubDemo subobj=new SubDemo();
  17.  subobj.x=2;
  18.  subobj.y=2;
  19.  subobj.show();
  20.  
  21. }




4. what is the output of following program:

  1. package com.instanceofjava;
  2.  
  3. public class SuperDemo{

  4.  int x;
  5. SuperDemo(){
  6.  
  7.  x=24;

  8. }
  9. }

  1. package com.instanceofjava;
  2. public class SubDemo extends SuperDemo{
  3.  
  4.  int y;
  5.  
  6. public void show(){
  7.  
  8.   System.out.println("x="+super.x);
  9.   System.out.println("y="+y);
  10.  
  11. }
  12.  
  13.  public static void main(String args[]){
  14.  
  15.  SubDemo subobj=new SubDemo();
  16.  subobj.show();
  17.  
  18. }





Arrays in java

Array:

  • Array is referenced data type used to store multiple values.
  • we can not change size of array at runtime.
  • memory can not be altered Once the memory has been allocated for an array at the run time.
  • Arrays are objects


Need of array:

  • In  real time projects array is used to collect same type of objects to send all values with single method call.

Problem of primitive data types:

  • We can not store values in continuous memory locations using primitive data types .
  • We have two problems due to this limitation

1.we cant store multiple values:

  • If we want to store multiple values , say 1 to 10 , we must create 10 variables .
  • All those 10 variables are created at different locations.

2.In single method call we can not pass multiple values :

  • we can not pass all values to the remote computer with single network call or method call.Using primitive variables  , which increases burden on network and also increase number of lines of code in program.

Solution:

  • Values must be stored in continuous memory locations with single variable name. To solve above two problems ,
  • This can be possible using array.
  • In java array is reference data type . it is used to store fixed number of multiple values of same type in continuous memory locations.
  • Like other data types array is not a keyword it is a concept. it creates continuous memory locations using other primitive or reference types.

 Array Limitation: 

  •  Array size is fixed , means we can not increase or decrease its size after its creation.

Array Declaration:

  • <Accessibility modifier><Modifier><datatype>[] <array variable name>;

For example:

  • public static int[] i;
  • public static Example[] e;
  • Like in C or C++ , in java we can not mention array size in declaration part. It leads Compile time error.
  • int[5] i; Compile time Error: illegal start of expression
  • int [] i;

Possible declaration:

  1. After data type : int[] i;
  2. Before variable name : int []i;
  3. After variable name : int i[];

Type of arrays:

  1.  Single dimensional : int [] i;
  2. Two dimensional : int[][] i;
  3. Three dimensional : int [][][] i;

Array object creation:

  • <Accessibility Modifier><Modifier><data type>[]<array name>={<list of values with , separator>};
  • int [] ia={10,20,30,40};

Super keyword

super:

  • The functionality of super keyword is only to point the immediate super class object of the current object.
  • super keyword is applicable only in the non static methods and super keyword not applicable in the static methods.
  • super keyword used to access the members of the super class object.
  • super.member;
  • It is used to store super class non static members memory reference through current sub class object for separating super class members from subclass members.

Uses:

  • Using super keyword we can explicitly point the immediate super class object and access all the super class members which are present with the same name of the subclass members from the sub class methods.

  1. package com.instanceofjavaforus;
  2.  public Class SuperDemo{ 
  3. int a,b;
  4.  
  5. public void show() {

  6. System.out.println(a);
  7. System.out.println(b);
  8.  
  9. }
  10. }


  1. package com.instanceofjavaforus;
  2. public Class Subdemo{ 
  3. int a,b;
  4. void disply(){

  5. System.out.println(a);
  6. System.out.println(b);
  7.  
  8. super.a=10;
  9. super.b=20;
  10.  
  11.   super.show();
  12.  
  13. }
  14.  
  15. public static void main (String args[]) {
  16.  Subdemo obj= new Subdemo();
  17.  obj.a=1;
  18. obj.b=2;
  19. obj.disply();

  20.  
  21. }
  22. }
  23. Output: 
  24. 1
  25. 2
  26. 10
  27. 20

  • Using super keyword we can explicitly call the super class constructor.
  • The statement which explicitly calling super class constructor should be always the first statement of the sub class constructor.
  • The statement which explicitly calls the super class constructor should be present inside a constructor only.


  1. package com.instanceofjavaforus;
  2.  public Class SuperDemo{ 
  3. int a,b;
  4.  
  5. public void show() {

  6. System.out.println(a);
  7. System.out.println(b);
  8.  
  9. }
  10.  SuperDemo(int x, int y){
  11.  a=x;
  12. b=y
  13. }
  14. }


  1. package com.instanceofjavaforus;
  2. public Class Subdemo{ 
  3. int a,b;
  4.  
  5. SubDemo(int x, int y){
  6. super(10,20);
  7.  a=x;
  8. b=y
  9. }
  10.  
  11. void disply(){

  12. System.out.println(a);
  13. System.out.println(b);
  14.   super.show();
  15. }
  16.  
  17. public static void main (String args[]) {
  18.  Subdemo obj= new Subdemo(1,2);
  19.  
  20. obj.disply();

  21.  
  22. }
  23. }
  24. Output: 
  25. 1
  26. 2
  27. 10
  28. 20

 

Key points to remember:

  • It is a keyword used to store super class non static members reference in subclass object.
  • Pre defined instance variable used to hold super class object reference through sub class object.
  • Used to separate super class and sub class members if both have same name.
  • It must be used explicitly if super class and sub class members have the same name.
  • Used to call super class constructor from sub class constructor.


Factory Method Pattern


Factory Method Pattern:

  • Problem: Using new keyword we can not create object with flexibility and by applying restrictions.
  • Solution: Use Factory pattern (or) Factory method.
  • By defining a abstract class or an interface but let the subclass  decide which class object to instantiate.
  • A method of a class capable of constructing and returning its own class object or other class object is called "factory method".
  • There are two types of factory methods.
  1. Static factory method.
  2. Instance factory method.

 1.Static Factory method:

  • A static method defined to construct and return object of same class or different is known as static factory method.
  • Some of the pre defined static factory methods are as follows.
  1. Thread th= Thread.currentThread();
  2. Class c=Class.forName();
  3. Runtime rt=Runtime.getRuntime();
  4. Calendar c=Calendar.getInstance();

2.Instance Factory method:

  • A non static method defined to construct and return object of same class or different is known as instance factory method.
  • Some of the pre defined instance factory methods are as follows.
  1.  String s= new String("instance of");
     String s1=s.concat("java");
  2. StringBuffer sb=new StringBuffer("instance of");
    sb=sb.subString(0,2);
  3. Date d= new Date();
    String s=d.toString();
Program on Factory method / Factory Design pattern:

Step 1: create an interface:

  1. package com.instanceofjavaforus;
  2.  
  3. public interface Vehicle {
  4.  
  5.  public void engine();
  6.  
  7. }
     

 Step 2: create a Two Wheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class TwoWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("Two Wheeler");
  7.     }
  8.  
  9. }

Step 3:: create a Four Wheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class FourWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("FourWheeler");
  7.     }
  8.  
  9. }

Step 4: create a SixWheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class SixWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("SixWheeler");
  7.     }
  8.  
  9. }

Step 5: create a TestEngine class which is having factory method:

  1. package com.instanceofjavaforus;
  2.  public class TestEngine {
  3.  public Vehicle getVehicle(String venname){
  4.      if(venname==null){
  5.             return null;
  6.        }else if(venname.equalsIgnoreCase("TwoWheeler")){
  7.             return new TwoWheeler();
  8.         }else if(venname.equalsIgnoreCase("FourWheeler")){
  9.             return new FourWheeler();
  10.         }else if(venname.equalsIgnoreCase("SixWheeler")){
  11.             return new SixWheeler();
  12.         }
  13.     
  14.         return null;
  15.     }
  16. }

Step 6: create a FactoryDemo class:

  1. package com.instanceofjavaforus;
  2.  public class FactoryDemo {
  3.   public static void main(String args[]){
  4.  
  5.      TestEngine te= new TestEngine();
  6.  
  7.         Vehicle vehcle1=te.getVehicle("TwoWheeler");
  8.        vehcle1.engine();
  9.  
  10.         Vehicle vehcle2=te.getVehicle("FourWheeler");
  11.         vehcle2.engine();
  12.  
  13.         Vehicle vehcle3=te.getVehicle("SixWheeler");
  14.          vehcle3.engine();
  15.  }
  16. }

  1. OutPut:
  2. TwoWheeler
  3. FourWheeler
  4. SixWheeler

Design patterns in java


Design patterns:

  • Pattern means set of guide lines.
  • Design patterns are solutions to commonly reoccurring problems in software development.
  • Design patterns are well proven solutions to common software problems.
  • Design patterns are best practices to use software technologies effectively in application development.  
  • Design patterns used in analysis and requirement  phase of  SDLC.
  • Design patterns can be implemented by using programming language.

Advantages:

  • Reusable.
  • These are already defined solutions to common re occurring problems so it reduces time.
  • They are already defined so Easy to understand and debug.

Categorization:

  • These are categorized into two parts.
  1. Java SE Design patterns.
  2. Java EE Design patterns.

Java SE Design patterns: 

  •  In Java SE there are mainly three types.

1.Creational Design patterns:

  1. Factory Pattern
  2. Abstract Factory Pattern
  3. Singleton Pattern
  4. Prototype Pattern
  5. Builder Pattern.

2.Structural Design patterns:

  1. Adapter Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

3.Behavioral Design patterns:

  1. Chain Of Responsibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Memento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern
Read More:
Factory pattern


Sort ArrayList in descending order

Descending order:

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListDesc {
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(1);
  15.             arrayList.add(2);
  16.             arrayList.add(3);
  17.            arrayList.add(4);
  18.             arrayList.add(5);
  19.             arrayList.add(6);
  20.  
  21.             /*
  22.            Use static Comparator reverseOrder() method of Collections 
  23.         utility class to get comparator object
  24.            */
  25.  
  26.          Comparator comparator = Collections.reverseOrder();
  27.  
  28.           System.out.println("Before sorting  : "  + arrayList);
  29.         
  30.  
  31.            /*
  32.               use
  33.               static void sort(List list, Comparator com) method of Collections class.
  34.             */
  35.  
  36.             Collections.sort(arrayList,comparator);
  37.             System.out.println("After sorting  : + arrayList);
  38.  
  39.        }
  40.     }
     

  1. OutPut:
  2. Before sorting  : [1, 2, 3, 4, 5, 6]
  3. After sorting  : [6, 5, 4, 3, 2, 1]
     

Ascending order:


  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListAsc{
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(10);
  15.             arrayList.add(4);
  16.             arrayList.add(7);
  17.            arrayList.add(2);
  18.             arrayList.add(5);
  19.             arrayList.add(3);
  20.  
  21.           
  22.  
  23.           System.out.println("Before sorting  : "  + arrayList);
  24.         
  25.  
  26.            /*
  27.               use
  28.               static void sort(List list) method of Collections class.
  29.             */
  30.  
  31.             Collections.sort(arrayList);
  32.             System.out.println("After sorting  : + arrayList);
  33.  
  34.        }
  35.     }
     



  1. OutPut:
  2. Before sorting  : [10, 4, 7, 2, 5, 3]
  3. After sorting  : [2, 3, 4, 5, 7, 10]
Select Menu