This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Flow Control

 
Basu Patel
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}
 
asheet anand
Ranch Hand
Posts: 83
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 201
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic