我想将字符串文字转换为全大写字母。这里是我的代码:当字符串文字改变时会发生什么?
// 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_,所以一旦创建,就无法更改它们。 –