What will 10.5.3 example print

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
demetrio
Posts: 16
Joined: Mon Sep 30, 2019 11:40 am
Contact:

What will 10.5.3 example print

Post 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?

admin
Site Admin
Posts: 10404
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: What will 10.5.3 example print

Post 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

}

Post Reply

Who is online

Users browsing this forum: No registered users and 12 guests