java toUpperCase()方法何时创建新对象?
public class Child{
public static void main(String[] args){
String x = new String("ABC");
String y = x.toUpperCase();
System.out.println(x == y);
}
}
输出:true
那么toUpperCase()
总是创建一个新对象吗
# 1 楼答案
toUpperCase()
调用toUpperCase(Locale.getDefault())
,仅当必须时,它才会创建一个新的String
对象。如果输入String
已经是大写,它将返回输入String
不过,这似乎是一个实现细节。我没有在Javadoc中找到它
下面是一个实现: