• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this code printing false false...this is from K&B book

 
Jacob Sonia
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jacob Sonia wrote:


Read the comments, please.
I think it's clear now.
 
Jacob Sonia
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry i interpreted the code like this...my mistake
And thanks a lot for so nice and quick response
public class Fizz {
int x = 5;
public static void main(String[] args) {
Fizz f1 = new Fizz(); //new object on the heap
Fizz f2 = new Fizz(); //new object on the heap
Fizz f3 = switchFizz(f1, f2); //f3 reference points on f1 object
if(f1 == f3)f2 = f1; //that's true - f3 reference points on f1 object (== checks if there are the same object)

System.out.println((f2 == f3) + " " + (f2.x == f3.x)); //false false - f2 doesn't point on the same object as f3
//f2.x = 6(because there are f1=f3) and f3.x=5;
}
static Fizz switchFizz(Fizz f1, Fizz f2){ //we have the copy of references passing to this method (copy and original //are the same!)
final Fizz z = f1; //OK this is only final reference. There are no final objects!
z.x = 6;
return z; //reference z points on f1
}

}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic