wood burning stoves*
The moose likes Java in General and the fly likes Expanations os scjp code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Expanations os scjp code" Watch "Expanations os scjp code" New topic
Author

Expanations os scjp code

madhavi prasad
Greenhorn

Joined: Jul 29, 2004
Posts: 17
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;
}
}


madhaviprasad
Georgy Bolyuba
Ranch Hand

Joined: Feb 18, 2005
Posts: 162
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 ]

SCJP 1.4 (100%) Done.<br />SCJD (URLyBird 1.2.3 Started)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Expanations os scjp code