Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explain this code

 
krithika naya
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
} }
What is the result?
A. true true
B. false true
C. true false
D. false false
E. Compilation fails.
F. An exception is thrown at runtime.


Answer:
� A is correct. 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.
�˚ B, C, D, E, and F are incorrect based on the above.

here what does the object state referred to?

z.x=6; explain this line

And explain this code.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
 
krithika naya
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sun certified programmer for java 5 by sierra and Bates.

I got this from 3rd chapter,self test question .
 
Joshua Mark
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When FizzSwitch is called, it is accepting Fizz f1 and Fizz f2 as arguments....where Fizz x == f1 and Fizz y == f2

then Fizz z = x means Fizz z = x = f1 which means the reference variables z, x and f1 all point to the same object.

then z.x means set member data x(because the Fizz object has an attribute x - yes this is confusing) on object z to 6. Since z, x, and f1 all reference the same object when you set z.x to 6, x.x = 6 and f1.x = 6.

then it returns the Fizz z and assigns it to Fizz f3. Since z, x and f1 all referenced the same object, f3 now also references the same object, so f3 and f1 both point to the same object. Since the references are both pointing to the same object f1 == f3 is true. And since that is true, obviously f1.x = f3.x

If you are getting confused by line 4 (final Fizz f1 = new Fizz()), all this means is that the reference variable f1 can't be changed. The member data within the Fizz f1 object can change, but you can't assign a different object to f1. Ie if you were to insert f1 = f2 after line five, you would get an exception. Same thing within the FizzSwitch method, line 10 (final Fizz z = x), this means that z can never reference any other object except x, which happens to also equal f1.



Hope that helps.
 
krithika naya
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you very much. now i got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic