简体   繁体   中英

Java Concept Confusion : Objects and Primitive Types

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?

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

" 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:

  • When you pass primitive type arguments into method - you are passing variables that are being copied. You passed value, not instance.
  • When you pass objects as arguments into method - you are passing references to that object, but to be more precise: in java, a copy of reference value is being passed. It is like passing a copy of the address of the object to the method. If you modify this object inside this method, the modifications will be visible outside the method. If you =null or =new Obj it, it will affect the object only inside your method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM