英文:
Instance methods in String Class in java
问题
"myString".toUpperCase();这里调用了String实例方法toUpperCase(),但没有创建新的String对象。因为toUpperCase()不是静态方法,所以它可以在不创建新的String对象的情况下被调用。
英文:
How String instance methods such as isEmpty and toUpperCase being called without creation of String Object.
"myString".toUpperCase();
since toUpperCase is not static method, how its being called without creation of new String()?
答案1
得分: 0
一个字符串字面量,比如"myString"
,即使在代码中没有明确看到new String()
的调用,它确实创建了一个String
对象¹。考虑String s = "myString";
,否则它将无法工作!所以你可以像通常一样调用它上面的任何方法。
¹ 或者重用现有的字符串对象,参见string pooling。
英文:
A string literal like "myString"
does create a String
object¹, even if you don't explicitly see a new String()
call in the code. Consider String s = "myString";
which couldn't work otherwise! So you can call any method on it as usual.
¹ Or reuses an existing one, see string pooling.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论