Page 1 of 1

What will 10.5.3 example print

Posted: Mon Oct 21, 2019 12:26 pm
by demetrio
From OCP Oracle Certified Professional Java SE 11 Programmer I Exam Fundamentals 1Z0-815: Study guide for passing the OCP Java 11 Developer Certification Part 1 Exam 1Z0-815 (English Edition) pages 235 and 237:

...

ic.printCount();
new InstanceCounter(). printCount();
System.out.println( InstanceCounter.printCount() +" "+ InstanceCounter.count);

...
will print:
1
2
2 2

I understand that first and second line the constructor is executed but in the last line it is not executed, right?

Re: What will 10.5.3 example print

Posted: Mon Oct 21, 2019 9:52 pm
by admin
Correct. new InstanceCounter() creates an instance of InstanceCounter class.

Code: Select all

public static void main(String[] args){
   InstanceCounter ic = new InstanceCounter(); // creates an instance, so the constructor is executed, which increments count to 1

   ic.printCount(); //print 1 because count is 1

   new InstanceCounter().printCount(); //creates an instance, so the constructor is executed , which increments count to 2. printCount prints 2

   System.out.println(InstanceCounter.printCount()+" "+InstanceCounter.count); //no instance is created, so, count is not affected, therefore printCount prints 2 and 2

}