0
class Stack
{
    int size;
    Stack(int size1)
    {
        size=size1;
    //  System.out.println("Constructor created"+size);//prints 3
    }
    int top1=-1;
    {System.out.println(size);}//prints 0
    int top2=size;
    {System.out.println(size);}//prints 0
    int []stack=new int[size];
}

Why is the size 0 in this case?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • where do you initialize the Stack class? – Dan Dinu May 30 '17 at 11:40
  • 1
    Possible duplicate of [In Java, what is the order of initialization for those statements after main method](https://stackoverflow.com/questions/43154736/in-java-what-is-the-order-of-initialization-for-those-statements-after-main-met) – Tom May 30 '17 at 12:09

2 Answers2

1

Your 2 System.out.println printing 0 are called in instance initializers. These initializers are called before your contructor is called.

You can learn more here: Static initializer in Java

Your full output must be

0
0
Constructor created3
StephaneM
  • 4,779
  • 1
  • 16
  • 33
0

instance initializers are executed before constructors.. in your case, you are giving size value in constructor and before that it was zero..

reference

PrabaharanKathiresan
  • 1,099
  • 2
  • 17
  • 32