• 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:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

mock question doubt about "final" - objective 7.3 -

 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Its taken from the book's self test answers by Kathy and Bert, SCJP study guide. on page 270

the question is, given...what's the result?

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;
}}

Answer is - true true.
The book explained that as " The references f1, z and f3 all refer to the same instance of Fizz. The final modifier assures that a reference variable cannot be referred to a different object, but final doesn't keep the object's state from changing.

.
.
.
.
now I am just wondering that how "(f1.x == f3.x)" would give the result "true"?

thanks for your help in advance
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is because when code does "z.x = 6", it is changing the same value where the object f1 is referring. And we are returning this temp z object and assigning it to the f3.

Hope you are clear.
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
because of FizzSwitch being static or Fizz z being final?

sorry i am such a blockhead
 
Jigar Upadhyay
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is just because objects in JAVA always "Pass By Reference".
 
I'm not dead! I feel happy! I'd like to go for a walk! I'll even read a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic