我想將字符串文字轉換爲全大寫字母。這裏是我的代碼:當字符串文字改變時會發生什麼?
// a and b are the same literal
String a = "Test";
String b = "Test";
// now I want to change all b's letter
// into uppercases, but fail.
b.toUpperCase();
System.out.println("a = " + a + ", " + "b = " + b);
// print: a = Test, b = Test
String c = "Test1";
System.out.println("c = " + c + " , c.toUpperCase() = "
+ c.toUpperCase());
// print: c = Test1 , c.toUpperCase() = TEST1
// change letters of "Test" literal
// into uppercase and success
System.out.println("Test".toUpperCase());
// print: TEST
我的問題是:1。 可以b
沒有變成大寫之一,但c
和即可。爲什麼?
我知道的是: 1. a
和b
引用字符串池中的同一個對象。 2.字符串是不可變的,但它似乎與此問題無關。
什麼讓你覺得你已經改變了'c'的任何東西?你已經顯示了'c.toUpperCase()'的*返回值*,就這些。這不會改變'c'的值(一個引用)或'c'的值所指的字符串中的數據。 –
你在哪裏持有聲明結果//b.toUpperCase(); – 2016-03-05 12:12:58
在Java中,'String'變量是_immutable_,所以一旦創建,就無法更改它們。 –