Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Exam1

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I doubt the answer is wrong for the followng question:
Given the following code what will be output?
public class Pass{
static int j=20;
public static void main(String argv[]){
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x){
x=x*2;
j=j*2;
}
}
1) Error: amethod parameter does not match variable
2) 20 and 40
3) 10 and 40
4) 10, and 20
The answer is 3, but I chose the 4. Is there anything I am missing? Please advise. thx!
Mike
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since variable j is a static variable, j=j*2 does alter the value from 20 to 40. That's why the answer for the value of j is 40. while the value of i is unchanged and remain at 10.
 
Deepak M
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vasansrini:
since variable j is a static variable, j=j*2 does alter the value from 20 to 40. That's why the answer for the value of j is 40. while the value of i is unchanged and remain at 10.

Even if j is not static, the value of j changes !!!
if u remove static from the declaration, make sure u access j using its qualified name, i.e p.j coz main is static !
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic