[英]Java Concept Confusion : Objects and Primitive Types
我對這個概念很困惑:
/* 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是1
b是3
a是1
為什么“ a”不改變?當int i初始化為零時,這個原始變量如何像FOR LOOP或WHILE LOOP那樣變化? 像這樣:
int i = 1;
while (i < = 3) {
System.out.println(i);
i *= 2;
}
OUTPUT:
1
2
請讓我詳細了解,因為我真的很困惑。我是一個原始類型,為什么要更新它,為什么在第一個程序中沒有int a?
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是1
b是3
一個是3
“ 為什么“ a”不變? ”
由於原始a
你的內部myMethod
是不一樣的a
,你在你的有void main
。 完全將其視為另一個變量,並將其值復制到myMethod
。 該原語的生命周期在該方法執行的結尾結束。
如果您具有C ++背景,那么以下解釋可能會有所幫助:
=null
或=new Obj
,它將僅影響您方法內部的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.