1. 程式人生 > >String 常量池

String 常量池

程序 運行期 static 範圍 nal () 字符串 .html 雙引號

public class TestString {

public static void main(String[] args) {
/** * **** String類型、包裝類型、常量池(與堆、棧) * *
* 1)== :比較桟區地址
* 2)equals:String/Integer的 equals 比較(變量所指向的在常量池或堆區的)內容
*
* 3)String常量池
*
* 只要使用new定義,無論如何都返回新的引用(棧區保存新的地址),如果要創建的字符串在常量池沒有找到,則要新加一個;另外在堆區開辟空間。
* 直接指定、或者使用純字符串串聯、或字符串加final常量來創建一個字符串,先檢查常量池,如果在常量池沒有找到,則在常量池添加一個並返回新的引用地址;如果找到,則返回相同的唯一的引用。
* 使用包含變量的表達式來創建字符串對象,則不僅會檢查維護String池(沒有則添加新的字符串),而且還會在堆區開辟空間、在棧區保存新的引用地址。
*
*
* 4)Byte,Short,Integer,Long,Character Boolean類型都實現了常量池(這類常量池範圍: -128~127,)
* Double,Float兩種浮點數類型的包裝類則沒有實現。
*
* 5)對於基本類型的變量和常量:變量和引用都存儲在棧中,常量則存儲在常量池中。 https://www.cnblogs.com/SaraMoring/p/5687466.html
*
* ------------------------------------------------------------------------------------
* https://zhidao.baidu.com/question/121174275.html
* java常量池不在堆中也不在棧中,是獨立的內存空間管理。
*  1.棧:存放基本類型的變量數據和對象的引用,但對象本身不存放在棧中,而是存放在堆(new 出來的對象)或者常量池中(字符串常量對象存放在常量池中。)
*  2.堆:存放所有new出來的對象。
*  3.常量池:存放字符串常量和基本類型常量(public static final)。
* 對於字符串:其對象的引用都是存儲在棧中的,如果是編譯期已經創建好(直接用雙引號定義的)的就存儲在常量池中,如果是運行期(new出來的)才能確定的就存儲在堆中。對於equals相等的字符串,在常量池中永遠只有一份,在堆中有多份。
*
*
*
*
*/


String str2 = "hello";
String str3 = "hello";
String str4 = new String("hello");
System.out.println(str2==str3); //true 使用常量池的 hello
System.out.println(str4==str3); //false 使用常量池的 hello,但是new則在返回新的引用

System.out.println(str4.equals(str3)); //true 比較指向的字符串常量池的內容


Integer i1=127;
Integer i2=127;
Integer i3=new Integer(127);
Integer i4=128;
Integer i5=128;

System.out.println(i1==i2); //true 使用常量池的127
System.out.println(i3==i2); //false 常量池也是只有一個127,但是new則在返回新的引用
System.out.println(i4==i5); //false 整數常量池只有 -128~127,超出範圍返回新的引用

System.out.println(i2.equals(i3)); //true 比較指向堆區/常量池的內容
System.out.println(i4.equals(i5)); //true 比較指向堆區/常量池的內容


Boolean b1=false;
Boolean b2=false;
Boolean b3=new Boolean(false);
System.out.println(b1==b2); //true true\false在常量池
System.out.println(b3==b2); //false 使用了new則返回新的引用

System.out.println(b3.equals(b2)); //true 比較指向的在常量池的內容



//
String a = "ab";
String bb = "b";
String b = "a" + bb; //程序運行期來動態分配並將連接後的新地址賦給b
System.out.println((a == b)); //false

String a0 = "ab";
final String bb1 = "b"; //對於final修飾的變量,它在編譯時被解析為常量值
String b0 = "a" + bb1;
System.out.println((a0 == b0)); //true

String a00 = "ab";
final String bb2 = getBB(); //程序運行期調用方法
String b00 = "a" + bb2; //動態分配地址為b
System.out.println((a00 == b00)); //false


}

private static String getBB() {
return "b";
}

}

String 常量池