File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes green mock query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "green mock query" Watch "green mock query" New topic

green mock query

ketki kalkar
Ranch Hand

Joined: May 09, 2007
Posts: 36
Following is a piece of code from green exam no 2.Please explain?

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();
public void amethod(){
int i = 99;
ValHold v = new ValHold();
System.out.print( v.i );
}//End of amethod
public void another(ValHold v, int i){
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.print(i); }//End of another

1) 10030
2) 20030
3) 209930
4) 10020
answer is 4).
Ravi Ahuja
Ranch Hand

Joined: Nov 13, 2006
Posts: 45
Hi ketki
now in the following code
lets see wat happens
the ball starts rolling in the main method
where amethod is called of ObParm class
now in amethod
we are creating an object of class Valhold
and setting its member variable to 30
Hope its okie for you till now
Now here is were you may be lost
now the next line


in this method we are passing the reference created in amethod
Now in java when you pass a reference variable into a method you are actually sending the path of the reference variable and you can access and change the value of the member variable of
class and it would be reflected in the method.
whereas if you change the reference variable itself and you are making any change it wont be reflected it is as you are creating a new reference variable
well lets take it in this way

v.i = 20;

here you are accessing the variable i of ValHold class this change would be reflected above in the amethod
the value of i would be set to 20 from 30

now here

v = vh;

you lost the address of the object
it is not accessible now in this method
hence the value of the variable i stays 20

Impossible is Nothing<br />SCJP 1.4: 96%
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
I think it should become a lot more clear to you if you change all the System.out.print() statements to System.out.println(). I'll give you one hint: You have three print statements that appear to give one output.

If you're still in doubt, write your own print statements as marker output.
I agree. Here's the link:
subject: green mock query
It's not a secret anymore!