GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Flow Control 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 "Flow Control" Watch "Flow Control" New topic
Author

Flow Control

Basu Patel
Ranch Hand

Joined: May 28, 2000
Posts: 60
Please tell me why in the following code,
i=10 & j=40 after execution?

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;
}
}


<BR>Contact Me<BR> <A HREF="mailto:basu_patel@usa.net" rel="nofollow">basu_patel@usa.net</A> <P>
asheet anand
Ranch Hand

Joined: Nov 15, 2000
Posts: 83
its really simple basu,when primitive types are passed as arguments to methods then a copy of a varibale not the original one is passed
so any changes made in the variables does not effect the original variable.
swati bannore
Ranch Hand

Joined: Oct 18, 2000
Posts: 201
It's simple Basu.
In the code, variable i is an instance variable, so its copy is passed to the method.
Whereas variable j is a static variable whose value ur changing in the method.There exists only one copy of class variable.
See what JLS says about static variables

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (�12.4).

SO,in the println statement,updated value of J is printed.


Swati Kale
SCJP
SCWCD
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Some empathy for Basu. There really is no such thing as a "simple" Java problem. I've seen many "simple" causes of bugs in the real world by "experienced" developers that were overlooked because the writers just assumed that overlooking such errors was beyond them. In the problem under discussion, there is a class "Pass" with two methods: main() and amethod(). When "i" is passed to amethod(), a copy of its value is used in the equation "x=x*2". When it is time to print the value of "i" in main(), the local value 10 is printed since the value calculated in amethod() for "i" is not the "i" in main(). However, since "j" is static, when the new value of "j" is calculated in amethod(), the value is assigned to the original instance, not a copy. Worth mentioning is the fact that if "int x" were to be replaced by "int i" as the parameter of amethod(), the result would be the same.
 
GeeCON Prague 2014
 
subject: Flow Control