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; } }
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
posted
0
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
posted
0
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.