Sunday, 2 August 2015

What is the output of following program?

 public class B{
    
      B b= new B();
    
     public int show(){
          return (true ? null : 0);
     }
    
     public static void main(String[] args)  {
    
            B b= new B();
            b.show();
        }
    
    }

Output:
  1. Exception in thread "main" java.lang.StackOverflowError
  2. at com.instanceofjava.B.<init>(B.java:3)
  3. at com.instanceofjava.B.<init>(B.java:5)
  4. at com.instanceofjava.B.<init>(B.java:5) 

Explanation:

  • Whenever we create the object of any class constructor will be called first and memory allocated for all non-static variables
  • Here  B b= new B(); the variable is an object and assigned to a new object of the same class
  • B b= new B(); statement leads to recursive execution of constructor will create infinite objects so at the run time an exception will be raised
  • Exception in thread "main" java.lang.StackOverflowError
  • The common cause for a stack overflow exception is a bad recursive call. Typically this is caused when your recursive functions don't have the correct termination condition

No comments:

Post a Comment