Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help me in understanding this program

 
kiruthigha rajan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai im unable to understand the working of the program especially z.x = 6;
class Fizz {
int x = 5;
public static void main(String[] args) {
final Fizz f1 = new Fizz();
Fizz f2 = new Fizz();
Fizz f3 = FizzSwitch(f1,f2);
System.out.println((f1 == f3) + " " + (f1.x == f3.x));
}
static Fizz FizzSwitch(Fizz x, Fizz y) {
final Fizz z = x;
z.x = 6;
return z;
} }
ppls explain in detail thanks in advance
 
Kiran Yadav
Ranch Hand
Posts: 35
Eclipse IDE Firefox Browser Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here z.x = 6; means that, the value of x (int) reference through the object of reference z (Fizz) is equals to 6.

As x(int) reference is avaialable for different object such as x (Fizz), y(Fizz) and z(Fizz). Each object can have differenct value for x (int).

So in this case, x(int) through z(Fizz) object have value as 6.
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


prints true true because FizzSwitch makes f1 and f3 point to the same object.

Regards,
Dan

 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question may want to test you something about final .
f1 is a final. X refers to f1. z is final and initialized to refer to x. X is non-final, but it can still refer to final variable/instance. z is final and z cannot be reassigned to some other instance. But z.x can be reassigned. In this example, you may
see that when z is assigned to x, z.x is 5. When z.x = 6, this x value encapsulated by z can be reassigned to a different value.
 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct me if I am wrong:

Step 1. f1 --> a Fizz object with initial x=5 where ---> means refer


Step 2 x ---> the same Fizz object

Step 3. z ----> the same Fizz object

Step 4 z.6 means update the same Fizz object's x from 5 to 6.

Step 5 : return z means returning that Fizz object

Step 6: assign f3 to the Fizz object returned from step 5

Therefore f3 --> that Fizz object created in step 1 and therefore the x values are the same.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic