• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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

 
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jacob Sonia wrote:



Read the comments, please.
I think it's clear now.
 
Jacob Sonia
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}

}
 
reply
    Bookmark Topic Watch Topic
  • New Topic