[英]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 ++背景,那么以下解释可能会有所帮助:
=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.