Reputation:
I am really confused about this concept:
/* Example with primitive data type */
public class Example1 {
public static void main (String[] args){
int a = 1;
System.out.println("a is " + a);
myMethod( a );
System.out.println("a is " + a);
}
public static void myMethod(int b){
b = 3;
System.out.println("b is " + b);
}
}
OUTPUT:
a is 1
b is 3
a is 1
Why does "a" not change?How does this primitive variable CHANGE like for a FOR LOOP or a WHILE LOOP when int i is initialed to zero? Like this:
int i = 1;
while (i < = 3) {
System.out.println(i);
i *= 2;
}
OUTPUT:
1
2
Please let me know in detail, as I am really confused.i is a primitive type, why does it get updated, and why does not int a in the first program?
Upvotes: 1
Views: 368
Reputation: 3173
"Why does "a" not change?"
Because primitive a
inside of your myMethod
is not the same a
that you had in your void main
. Treat it as completely another variable and that its value got copied into myMethod
. This primitive`s lifecycle ends in the end of this method execution.
If you have C++ background then maybe this explanation might help:
=null
or =new Obj
it, it will affect the object only inside your method.Upvotes: 0
Reputation: 71
myMethod() is void, if it returned an int and you assigned a=myMethod(a) then it would change
int a = 1;
System.out.println("a is " + a);
a= myMethod(a); //where myMethod is changed to return b instead of void
System.out.println("a is " + a);
a is 1
b is 3
a is 3
Upvotes: 1