• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

a question from Marcus Green Exam

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone explain why we get ans. 10,0,20 from the following question?
Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
}//End of amethod
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
1) 10,0, 30
2) 20,0,30
3) 20,99,30
4) 10,0,20
Thanks.
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sarah,
This has been dicussed many times in this forum!
The answer is simply that java passes values by reference which means that the reference variable itself can't be changed but the references objects' state can be changed.
The long answer:
1. Start with calling o.amethod
2. Set local variable i = 99
3. Create new ValHold: v (default: state of i = 10)
4. Change v state to i = 30
5. Call another method sending in v and local i
6. Inside another method get local v referencing the object pointed to by parameter v, and local i referencing the object pointed to by parameter i.
7. Change local i to 0
8. Change state of local v (pointing to same object as parameter v) to state of 20
9. Create new local ValHold variable: vh (default state of i = 10)
10. Assign local variable v to point to vh object
11. Print out local variable v state 10 (see 9&10) and print out local variable i 0
12. Return from another method
13. Print out variable v state 20 (see 8)
The main idea is that one objects can be referenced by two variables at the same time. Hence, if we change one (local v inside amethod) we also change the other (parameter v sent to amethod)!
Regards,
Manfred.
 
reply
    Bookmark Topic Watch Topic
  • New Topic