This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Expanations os scjp code

 
madhavi prasad
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

The out put of the below code is 10 & 40 can any explain me how it is 10 and 40.

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;
}
}
 
Georgy Bolyuba
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you passing i (which is 10 at that moment) to the p.amethod(i); method, you realy passing a copy of bit-pattern of i.
(00000000000000000000000000001010) - bin

So, next, inside p.amethod(i); you do x=x*2;. The value of x was 10 and now it became 20 as you can guess. But, "i" still has value of 10, couse x is just a copy of i, remember?

Next, j=j*2;. Well, j was 20 now it is 40. Simple. You accessing static variable (j) from instance method and, for example, IntelliJ IDEA will complain about it, but it's legal.

Next, p.amethod(i); is over - this meens:
- x variable is gone
- j has value of 40
- i has value of 10

So, the output is just like it should be, yeah?

[ July 08, 2005: Message edited by: George Bolyuba ]
[ July 08, 2005: Message edited by: George Bolyuba ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic