Friday, March 18, 2016

[Java] Java concept quiz 1 Q1 - static value, constructor, ++ operator

This is a question from internet for testing Java concept, related to static value, constructor, ++ operator, object creating and while loop.

Question

2. public class Bunnies {
3.     static int count = 0;
4.     Bunnies() {
5.         while(count < 10) new Bunnies(++count);
6.     }
7.     Bunnies(int x) { super(); }
8.         public static void main(String[] args) {
9.             new Bunnies();
10.           new Bunnies(count);
11.           System.out.println(count++);
12.      }
13. }
Please found out the result:
A. 9
B. 10
C. 11
D. 12
E. Compilation fails.
F. An exception is thrown at runtime.


=======================================================

Answer:

You can copy the testing code to NetBean:
package quiz;

public class Bunnies {
static int count = 0;
    Bunnies() {
        while(count < 10) new Bunnies(++count);
    }
    Bunnies(int x) { super(); }
    public static void main(String[] args) {
    new Bunnies();
    new Bunnies(count);
    System.out.println(count++);
    }
}
Answer is B: 10

Firstly, it’s legal to invoke "new" from within a constructor, and it’s also legal to call super() on a class with no explicit super class. When the program creating an Bunnies object in line 9, while loop at line 5 was called and change the static value "count" to 10. (p.s. While static count=9 and run new Bunnies(++count); at line 5, the line ++count increase "count" value to 10.)

And then, what line 10 do is pass a int type value named "count" where the value is 10 to create Bunnies object. Constructor at line 7 was called and super() run. However, class Bunnies doesn't have any intermediate parents and all class are extend Object, so super() here is valid here and calling constructor of Object with your super() but did nothing.

At line 11, the code "System.out.println(count++);' would print the static value count (where value is 10) first and then do count++; It would more clear to see how it works if read this figure:


Remarks:

Change line 11 from System.out.println(count++); to System.out.println(++count); , that line would print 11.
public class Bunnies {
static int count = 0;
    Bunnies() {
        while(count < 10) new Bunnies(++count);
    }
    Bunnies(int x) { super(); }
    public static void main(String[] args) {
    new Bunnies();
    new Bunnies(count);
    System.out.println(count);
    System.out.println(++count);

    }
}

Reference:

Stackoverflow - Calling super() with no Superclass?
Practice Exams Java (ISBN:978-0-07-170286-7)

No comments :

Post a Comment