局部變量
定義在方法中的變量
屬于方法蝙泼,在棧內(nèi)存的方法的棧幀中程剥。
隨方法的調(diào)用而產(chǎn)生,隨方法的結(jié)束而消失
沒有默認(rèn)的初始化值汤踏,必須手動賦值后织鲸,才能使用
測試代碼
//正確寫法
int a = 10;
System.out.println(a);
//錯誤寫法
// int a;
// long a;
// char a;
long a;
System.out.println(a);
錯誤寫法拋出異常
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable a may not have been initialized
成員變量
定義在類中成員位置的變量(類中方法外)
屬于對象舔腾,在堆內(nèi)存的對象中
隨對象的創(chuàng)建而產(chǎn)生,隨對象的消失而消失搂擦。
有初始值
- 基本數(shù)據(jù)類型
- 整數(shù)類型:0
- 小數(shù)類型:0.0
- 布爾類型:false
- 字符類型:'\u0000' (Unicode值, 控制臺輸出的是空格)
- 引用數(shù)據(jù)類型:null
測試代碼
class Test {
// 基本數(shù)據(jù)類型
int i;
long l;
byte b;
char c;
// 引用類型
String s;
int[] a;
// 擴(kuò)展稳诚,數(shù)組 new 之后,在堆中 int 類型自動初始化為 0 瀑踢。
int[] extend = new int[5];
public void outPut(){
System.out.println("int--" + i);
System.out.println("long--" + l);
System.out.println("byte--" + b);
System.out.println("char--" + c + "占位專用");
System.out.println("String--" + s + "占位專用");
System.out.println("數(shù)組--" + a);
System.out.println("數(shù)組 new 之后扳还,堆中int類型初始化為0--" + Arrays.toString(a));
}
}
測試輸出
int--0
long--0
byte--0
char-- 占位專用
String--null占位專用
數(shù)組--null
數(shù)組 new 之后,堆中int類型初始化為0--[0, 0, 0, 0, 0]