简体   繁体   English

Java概念混乱:对象和原始类型

[英]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: OUTPUT:

a is 1 a是1

b is 3 b是3

a is 1 a是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? 为什么“ a”不改变?当int i初始化为零时,这个原始变量如何像FOR LOOP或WHILE LOOP那样变化? Like this: 像这样:

int i = 1;
while (i < = 3) {
 System.out.println(i);
 i *= 2;
}

OUTPUT: OUTPUT:

1 1

2 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? 请让我详细了解,因为我真的很困惑。我是一个原始类型,为什么要更新它,为什么在第一个程序中没有int a?

myMethod() is void, if it returned an int and you assigned a=myMethod(a) then it would change myMethod()是无效的,如果它返回一个int并且您分配了a = myMethod(a),则它将改变

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 a是1

b is 3 b是3

a is 3 一个是3

" Why does "a" not change? " 为什么“ a”不变?

Because primitive a inside of your myMethod is not the same a that you had in your void main . 由于原始a你的内部myMethod是不一样的a ,你在你的有void main Treat it as completely another variable and that its value got copied into myMethod . 完全将其视为另一个变量,并将其值复制到myMethod This primitive`s lifecycle ends in the end of this method execution. 该原语的生命周期在该方法执行的结尾结束。

If you have C++ background then maybe this explanation might help: 如果您具有C ++背景,那么以下解释可能会有所帮助:

  • 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. 当您将对象作为参数传递给方法时-您正在传递对该对象的引用, 更精确地说:在Java中,传递的是引用值的副本。 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. 如果您=null=new Obj ,它将仅影响您方法内部的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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