Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock exam question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock exam question" Watch "Mock exam question" New topic

Mock exam question

Pete Serafin

Joined: Feb 22, 2001
Posts: 1
You create a class called A with a final variable called z. Is it possible to have three instances of A, each of which has a different value for z?
The following answer explains that you can do this, but i thought that z was automatically initialized to 0 and since its final, it cant be changed. Why is my thinking wrong???

The following code shows one way to do it:
class A {
static int nth;
final int z;
A() { z = nth++; }
public static void main(String[] args) {
new A(); new A(); new A();
Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
In this case z is considered a blank final. A blank final is when you declare a final variable without initializing it. If you don't initialize by the time it's used, then it would cause a compiler error. In this instance, you are initializing z in the constructor, so you don't get the compiler error. The reason that the z value is able to change in this example is because you are not explicitly changing the z value. the nth value changes and it just so happens that z aquires that value during initialization. The value of z changes each time z is initialized. If you tried to change the value of z after initialization, then you'd get an error. Note that each time a new A object is created, a blank copy of the final variable z is given to the constructor. The variable nth will change with each new object A because it is a static variable.
[This message has been edited by Sean Casey (edited February 23, 2001).]
[This message has been edited by Sean Casey (edited February 23, 2001).]
Sri Enga
Ranch Hand

Joined: Feb 02, 2001
Posts: 51
refer Maha Anna's explantion , it's worth reading.
I agree. Here's the link:
subject: Mock exam question
It's not a secret anymore!