public class Num
{
static Integer i = new Integer(520);
};
public class Demo
{
public static void main(String[] args)
{
Num demo1 = new Num();
Num demo2 = new Num();
if (demo1.i == demo2.i)
{
System.out.println("ture");
}
else
{
System.out.println("false");
}
}
}
輸出為:
true!表明demo1.i和demo2.i只有一分存儲空間.雖然new了兩個對象.但只有一份存儲空間!
public class Num
{
Integer i = new Integer(520);
};
public class Demo
{
public static void main(String[] args)
{
Num demo1 = new Num();
Num demo2 = new Num();
if (demo1.i == demo2.i)
{
System.out.println("ture");
}
else
{
System.out.println("false");
}
}
}
輸出為false
關于static變量或方法..只會創建一份空間..無論是否有對象去引用..
下面是更深入的說明!!!
public class Num
{
static Integer i = new Integer(520);
Integer j = new Integer(520);
}
public class Demo
{
public static void main(String[] args)
{
Num demo1 = new Num();
Num demo2 = new Num();
if (demo1.i == demo2.i)
{
System.out.println("ture");
}
else
{
System.out.println("false");
}
if (demo1.j == demo2.j)
{
System.out.println("ture");
}
else
{
System.out.println("false");
}
System.out.println(Num.i);
}
}
下面一個例子:
public class F1
{
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(10);
int k = 20;
int l = 20;
System.out.println(k ==l);
System.out.println(i == j);
}
};
上面的例 子表明:對于通過new創建的兩個對象的引用i&j,他們所引用的值都相同為10.但是,兩個10存儲在不同的兩個地方,兩個引用不同哦.....
上面例 子的結果為:
ture
false
芳兒寶貝.我愛你