创建了多少个 Java 字符串? [英] How many Java Strings Created?

查看:36
本文介绍了创建了多少个 Java 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String [] args){ 
    String s = "java"; //line 1
    s.concat(" SE 6"); //line 2
    s.toLowerCase();  //line 3
    System.out.print(s); //line 4
 }

这个问题的答案是4".我以为是3".我的困惑是第3行,它再次创建了java"字符串,但是java不知道字符串常量池中已经存在java"字符串,那为什么还要创建它?

The answer to this question is "4". I thought it would be "3". My confusion is line 3, which creates "java" string again, but doesn't java know that the "java" string already exist in the string constant pool, so why create it again?

推荐答案

创建了 3 个 Java 字符串.

3 Java Strings are created.

1. "java"  -> Goes into String constants pool // will be added if no already present
2.  " SE 6" --> Goes into String constants pool?
3. java SE 6 --> Goes on heap (call to concat)// Note : You are not re-assinging the value returned from concat() So s will still be "java"
** toLowerCase() \\ does nothing in your case since "java" is already present. toLowerCase retruns the same "java" object ( as there is no modification required to turn it into lowercase)

这篇关于创建了多少个 Java 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆