Java Interview Questions Part 4

How many types of exception can occur in a Java program?

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

  • Checked Exception: Checked exceptions are the one which are checked at compile-time. For example, SQLException, ClassNotFoundException, etc.

 

  • Unchecked Exception: Unchecked exceptions are the one which are handled at runtime because they can not be checked at compile-time. For example, ArithmaticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

 

  • Error: Error cause the program to exit since they are not recoverable. For Example, OutOfMemoryError, AssertionError, etc.

Explain the hierarchy of Java Exception classes?

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

What is the base class for Error and Exception?

The Throwable class is the base class for Error and Exception.

What is the difference between Checked Exception and Unchecked Exception?

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions, e.g., IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.

More details.

 

What is Exception Handling?

Exception Handling is a mechanism that is used to handle runtime errors. It is used primarily to handle checked exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of exceptions: checked and unchecked. Here, the error is considered as the unchecked exception.

More details.

 

Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. So whatever exceptions are likely to be thrown should be declared in the throws clause of the method. Consider the following example.

  1. public  class  Main {  
  2.      public static void main(String []args){  
  3.         try{  
  4.             int a = 1;   
  5.             System.out.println(a/0);  
  6.         }  
  7.         finally  
  8.         {  
  9.             System.out.println("rest of the code...");  
  10. 10.         }  
  11. 11.      }  

12. }  

  1. 13.       

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...


 

Can finally block be used without a catch?

Yes, According to the definition of finally block, it must be followed by a try or catch block, therefore, we can use try block instead of catch. More details.


What is finally block?

The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. In other words, we can say that finally block is the block which is always executed. Finally block follows try or catch block. If you don't handle the exception, before terminating the program, JVM runs finally block, (if any). The finally block is mainly used to place the cleanup code such as closing a file or closing a connection. Here, we must know that for each try block there can be zero or more catch blocks, but only one finally block. The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
More details.

What is the output of the following Java program?

  1. public class ExceptionHandlingExample {  
  2. public static void main(String args[])  
  3. {  
  4.     try  
  5.     {  
  6.         int a = 1/0;  
  7.         System.out.println("a = "+a);  
  8.     }  
  9.     catch(Exception e){System.out.println(e);}  
  10. 10.     catch(ArithmeticException ex){System.out.println(ex);}    

11. }  

12. }  

Output

ExceptionHandlingExample.java:10: error: exception ArithmeticException has already been caught

        catch(ArithmeticException ex){System.out.println(ex);}      

        ^

1 error

Explanation

ArithmaticException is the subclass of Exception. Therefore, it can not be used after Exception. Since Exception is the base class for all the exceptions, therefore, it must be used at last to handle the exception. No class can be used after this.

What is the output of the following Java program?

  1.   public  class  Main {  
  2.      public static void main(String []args){  
  3.         try  
  4.         {  
  5.             throw 90;   
  6.         }  
  7.         catch(int e){  
  8.             System.out.println("Caught the exception "+e);  
  9.         }  
  10. 10.               
  11. 11.     }  

12. }  

Output

Main.java:6: error: incompatible types: int cannot be converted to Throwable

            throw 90;

            ^

Main.java:8: error: unexpected type

        catch(int e){

              ^

  required: class

  found:    int

2 errors

Explanation

In Java, the throwable objects can only be thrown. If we try to throw an integer object, The compiler will show an error since we can not throw basic data type from a block of code.

Is there any case when finally will not be executed?

Finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).More details.

What is the difference between throw and throws?

throw keyword

throws keyword

1) The throw keyword is used to throw an exception explicitly.

The throws keyword is used to declare an exception.

2) The checked exceptions cannot be propagated with throw only.

The checked exception can be propagated with throws

3) The throw keyword is followed by an instance.

The throws keyword is followed by class.

4) The throw keyword is used within the method.

The throws keyword is used with the method signature.

5) You cannot throw multiple exceptions.

You can declare multiple exceptions, e.g., public void method()throws IOException, SQLException.

More details.

 

What is the output of the following Java program?

  1. public  class  Main   
  2. {  
  3.     void a()  
  4.     {  
  5.         try{  
  6.         System.out.println("a(): Main called");  
  7.         b();  
  8.         }catch(Exception e)  
  9.         {  
  10. 10.             System.out.println("Exception is caught");  
  11. 11.         }  
  12. 12.     }  
  13. 13.     void b() throws Exception  
  14. 14.     {  
  15. 15.      try{  
  16. 16.          System.out.println("b(): Main called");  
  17. 17.          c();  
  18. 18.      }catch(Exception e){  
  19. 19.          throw new Exception();  
  20. 20.      }  
  21. 21.      finally   
  22. 22.      {  
  23. 23.          System.out.println("finally block is called");  
  24. 24.      }  
  25. 25.     }  
  26. 26.     void c() throws Exception   
  27. 27.     {  
  28. 28.         throw new Exception();  
  29. 29.     }  
  30. 30.   
  31. 31.     public static void main (String args[])  
  32. 32.     {  
  33. 33.         Main m = new Main();  
  34. 34.         m.a();  
  35. 35.     }  

36. }  

Output

a(): Main called

b(): Main called

finally block is called

Exception is caught

Explanation

In the main method, a() of Main is called which prints a message and call b(). The method b() prints some message and then call c(). The method c() throws an exception which is handled by the catch block of method b. However, It propagates this exception by using throw Exception() to be handled by the method a(). As we know, finally block is always executed therefore the finally block in the method b() is executed first and prints a message. At last, the exception is handled by the catch block of the method a().

What is the output of the following Java program?

  1. class Calculation extends Exception  
  2. {  
  3.     public Calculation()   
  4.     {  
  5.         System.out.println("Calculation class is instantiated");  
  6.     }  
  7.     public void add(int a, int b)  
  8.     {  
  9.         System.out.println("The sum is "+(a+b));  
  10. 10.     }  

11. }  

12. public  class  Main {  

  1. 13.      public static void main(String []args){  
  2. 14.         try  
  3. 15.         {  
  4. 16.             throw new Calculation();   
  5. 17.         }  
  6. 18.         catch(Calculation c){  
  7. 19.             c.add(10,20);  
  8. 20.         }  
  9. 21.     }  

22. }   

Output

Calculation class is instantiated

The sum is 30

Explanation

The object of Calculation is thrown from the try block which is caught in the catch block. The add() of Calculation class is called with the integer values 10 and 20 by using the object of this class. Therefore there sum 30 is printed. The object of the Main class can only be thrown in the case when the type of the object is throwable. To do so, we need to extend the throwable class.

What is the output of the following Java program?

23. class Calculation extends Exception  

24. {  

  1. 25.     public Calculation()   
  2. 26.     {  
  3. 27.         System.out.println("Calculation class is instantiated");  
  4. 28.     }  
  5. 29.     public void add(int a, int b)  
  6. 30.     {  
  7. 31.         System.out.println("The sum is "+(a+b));  
  8. 32.     }  

33. }  

34. public  class  Main {  

  1. 35.      public static void main(String []args){  
  2. 36.         try  
  3. 37.         {  
  4. 38.             throw new Calculation();   
  5. 39.         }  
  6. 40.         catch(Calculation c){  
  7. 41.             c.add(10,20);  
  8. 42.         }  
  9. 43.     }  

44. }   

Output

Calculation class is instantiated

The sum is 30

Explanation

The object of Calculation is thrown from the try block which is caught in the catch block. The add() of Calculation class is called with the integer values 10 and 20 by using the object of this class. Therefore there sum 30 is printed. The object of the Main class can only be thrown in the case when the type of the object is throwable. To do so, we need to extend the throwable class.

What is the output of the following Java program?

  1. public class Calculation   
  2. {  
  3.     int a;   
  4.     public Calculation(int a)  
  5.     {  
  6.         this.a = a;  
  7.     }  
  8.     public int add()  
  9.     {  
  10. 10.         a = a+10;   
  11. 11.         try   
  12. 12.         {  
  13. 13.             a = a+10;   
  14. 14.             try   
  15. 15.             {  
  16. 16.                 a = a*10;   
  17. 17.                 throw new Exception();   
  18. 18.             }catch(Exception e){  
  19. 19.                 a = a - 10;  
  20. 20.             }  
  21. 21.         }catch(Exception e)  
  22. 22.         {  
  23. 23.             a = a - 10;   
  24. 24.         }  
  25. 25.         return a;  
  26. 26.     }  
  27. 27.       
  28. 28.     public static void main (String args[])  
  29. 29.     {  
  30. 30.         Calculation c = new Calculation(10);  
  31. 31.         int result = c.add();  
  32. 32.         System.out.println("result = "+result);  
  33. 33.     }  

34. }  

Output

result = 290

Explanation

The instance variable a of class Calculation is initialized to 10 using the class constructor which is called while instantiating the class. The add method is called which returns an integer value result. In add() method, a is incremented by 10 to be 20. Then, in the first try block, 10 is again incremented by 10 to be 30. In the second try block, a is multiplied by 10 to be 300. The second try block throws the exception which is caught by the catch block associated with this try block. The catch block again alters the value of a by decrementing it by 10 to make it 290. Thus the add() method returns 290 which is assigned to result. However, the catch block associated with the outermost try block will never be executed since there is no exception which can be handled by this catch block.

What is exception propagation?

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This procedure is called exception propagation. By default, checked exceptions are not propagated.

  1. class TestExceptionPropagation1{  
  2.   void m(){  
  3.     int data=50/0;  
  4.   }  
  5.   void n(){  
  6.     m();  
  7.   }  
  8.   void p(){  
  9.    try{  
  10. 10.     n();  
  11. 11.    }catch(Exception e){System.out.println("exception handled");}  
  12. 12.   }  
  13. 13.   public static void main(String args[]){  
  14. 14.    TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
  15. 15.    obj.p();  
  16. 16.    System.out.println("normal flow...");  
  17. 17.   }  

18. }  

Test it Now

Output:

exception handled

normal flow.

 

What do you understand by an IO stream?

The stream is a sequence of data that flows from source to destination. It is composed of bytes. In Java, three streams are created for us automatically.

  • System.out: standard output stream
  • System.in: standard input stream
  • System.err: standard error stream

..

Give the hierarchy of InputStream and OutputStream classes.

OutputStream Hierarchy

 

InputStream Hierarchy

What are the FileInputStream and FileOutputStream?

Java FileOutputStream is an output stream used for writing data to a file. If you have some primitive values to write into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through the FileOutputStream class. However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. Consider the following example of writing a byte into a file.

  1. import java.io.FileOutputStream;    
  2. public class FileOutputStreamExample {    
  3.     public static void main(String args[]){      
  4.            try{      
  5.              FileOutputStream fout=new FileOutputStream("D:\\testout.txt");      
  6.              fout.write(65);      
  7.              fout.close();      
  8.              System.out.println("success...");      
  9.             }catch(Exception e){System.out.println(e);}      
  10. 10.       }      

11. }    

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. You can also read character-stream data. However, for reading streams of characters, it is recommended to use FileReader class. Consider the following example for reading bytes from a file.

  1. import java.io.FileInputStream;    
  2. public class DataStreamExample {    
  3.      public static void main(String args[]){      
  4.           try{      
  5.             FileInputStream fin=new FileInputStream("D:\\testout.txt");      
  6.             int i=fin.read();    
  7.             System.out.print((char)i);      
  8.     
  9.             fin.close();      
  10. 10.           }catch(Exception e){System.out.println(e);}      
  11. 11.          }      
  12. 12.         }    
  13. 13.     

 

 

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. The ByteStream classes are used to perform input-output of 8-bit bytes whereas the CharacterStream classes are used to perform the input/output for the 16-bit Unicode system. There are many classes in the ByteStream class hierarchy, but the most frequently used classes are FileInputStream and FileOutputStream. The most frequently used classes CharacterStream class hierarchy is FileReader and FileWriter.

What are the super most classes for all the streams?

All the stream classes can be divided into two types of classes that are ByteStream classes and CharacterStream Classes. The ByteStream classes are further divided into InputStream classes and OutputStream classes. CharacterStream classes are also divided into Reader classes and Writer classes. The SuperMost classes for all the InputStream classes is java.io.InputStream and for all the output stream classes is java.io.OutPutStream. Similarly, for all the reader classes, the super-most class is java.io.Reader, and for all the writer classes, it is java.io.Writer.

What is the purpose of using BufferedInputStream and BufferedOutputStream classes?

Java BufferedOutputStream class is used for buffering an output stream. It internally uses a buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. Whereas, Java BufferedInputStream class is used to read information from the stream. It internally uses the buffer mechanism to make the performance fast.

What is serialization?

Serialization in Java is a mechanism of writing the state of an object into a byte stream. It is used primarily in Hibernate, RMI, JPA, EJB and JMS technologies. It is mainly used to travel object's state on the network (which is known as marshaling). Serializable interface is used to perform serialization. It is helpful when you require to save the state of a program to storage such as the file. At a later point of time, the content of this file can be restored using deserialization. It is also required to implement RMI(Remote Method Invocation). With the help of RMI, it is possible to invoke the method of a Java object on one machine to another machine.

 More details.

 

How can you make a class serializable in Java?

A class can become serializable by implementing the Serializable interface.

What is the transient keyword?

If you define any data member as transient, it will not be serialized. By determining transient keyword, the value of variable need not persist when it is restored. More details.

What is Deserialization?

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

  1. import  java.io. *;  
  2. class Depersist{  
  3.  public static void main(String args[])throws Exception{  
  4.     
  5.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
  6.   Student s=(Student)in.readObject();  
  7.   System.out.println(s.id+" "+s.name);  
  8.   
  9.   in.close();  
  10. 10.  }  

11. }  

211 ravi

 

What is Externalizable?

The Externalizable interface is used to write the state of an object into a byte stream in a compressed format. It is not a marker interface.

Can an exception be rethrown?

Yes.

What is the reflection?

Reflection is the process of examining or modifying the runtime behavior of a class at runtime. The java.lang.Class class provides various methods that can be used to get metadata, examine and change the runtime behavior of a class. The java.lang and java.lang.reflect packages provide classes for java reflection. It is used in:

  • IDE (Integrated Development Environment), e.g., Eclipse, MyEclipse, NetBeans.
  • Debugger
  • Test Tools, etc.

What is the purpose of using java.lang.Class class?

The java.lang.Class class performs mainly two tasks:

  • Provides methods to get the metadata of a class at runtime.
  • Provides methods to examine and change the runtime behavior of a class.

What is the output of the following Java program?

  1. class Simple{    
  2.  public Simple()  
  3.  {  
  4.    System.out.println("Constructor of Simple class is invoked");  
  5.  }  
  6.  void message(){System.out.println("Hello Java");}    
  7. }    
  8.     
  9. class Test1{    
  10. 10.  public static void main(String args[]){    
  11. 11.   try{    
  12. 12.   Class c=Class.forName("Simple");    
  13. 13.   Simple s=(Simple)c.newInstance();    
  14. 14.   s.message();    
  15. 15.   }catch(Exception e){System.out.println(e);}    
  16. 16.  }    

17. }    

Output

Constructor of Simple class is invoked

Hello Java

Explanation

The newInstance() method of the Class class is used to invoke the constructor at runtime. In this program, the instance of the Simple class is created.

What is Garbage Collection?

Garbage collection is a process of reclaiming the unused runtime objects. It is performed for memory management. In other words, we can say that It is the process of removing unused objects from the memory to free up space and make this space available for Java Virtual Machine. Due to garbage collection java gives 0 as output to a variable whose value is not set, i.e., the variable has been defined but not initialized. For this purpose, we were using free() function in the C language and delete() in C++. In Java, it is performed automatically. So, java provides better memory management.

More details.

What is gc()?

The gc() method is used to invoke the garbage collector for cleanup processing. This method is found in System and Runtime classes. This function explicitly makes the Java Virtual Machine free up the space occupied by the unused objects so that it can be utilized or reused. Consider the following example for the better understanding of how the gc() method invoke the garbage collector.

  1. public class TestGarbage1{  
  2.  public void finalize(){System.out.println("object is garbage collected");}  
  3.  public static void main(String args[]){  
  4.   TestGarbage1 s1=new TestGarbage1();  
  5.   TestGarbage1 s2=new TestGarbage1();  
  6.   s1 = null ;  
  7.   s2 = null ;  
  8.   System.gc();  
  9.  }  

10. }  

Test it Now

       object is garbage collected

       object is garbage collected

What is the purpose of the finalize() method?

The finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing. The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created an object without new, you can use the finalize method to perform cleanup processing (destroying remaining objects). The cleanup processing is the process to free up all the resources, network which was previously used and no longer needed. It is essential to remember that it is not a reserved keyword, finalize method is present in the object class hence it is available in every class as object class is the superclass of every class in java. Here, we must note that neither finalization nor garbage collection is guaranteed. Consider the following example.

  1. public  class  FinalizeTest {  
  2.     int j=12;  
  3.     void add()  
  4.     {  
  5.         j = j + 12;  
  6.         System.out.println("J="+j);  
  7.     }  
  8.     public void finalize()  
  9.     {  
  10. 10.         System.out.println("Object is garbage collected");  
  11. 11.     }  
  12. 12.     public static void main(String[] args) {  
  13. 13.         new FinalizeTest().add();  
  14. 14.         System.gc();  
  15. 15.         new FinalizeTest().add();  
  16. 16.     }  

17. }  

  1. 18.       

 

What kind of thread is the Garbage collector thread?

Daemon thread.

 

Guess you like

Origin www.cnblogs.com/codingyangmao/p/12714123.html