Java中有多少个字符串对象? [英] How many string objects in Java?

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

问题描述

我的朋友在一次模拟考试中发给我一个关于字符串对象的Java认证的问题:

My friend sent me a question he saw in one mock exam for the Java certification about string objects:

String makeStrings(){
    String s = "HI";
    s = s + "5";
    s = s.substring(0,1);
    s = s.toLowerCase();
    return s.toString();
}

调用此方法时将创建多少个字符串对象?
考试给出的正确答案是3.但我认为这是5分。

How many string objects will be created when this method is invoked? The correct answer the exam gave was 3. But I think it's five.


  1. HI

  2. 5

  3. HI5

  4. H

  5. h

  1. "HI"
  2. "5"
  3. "HI5"
  4. "H"
  5. "h"

我错了吗?

推荐答案

String makeStrings() {
    String s = "HI";           //String literal
    s = s + "5";               //concatenation creates new String object (1)
    s = s.substring(0,1);      //creates new String object (2)
    s = s.toLowerCase();       //creates new String object (3)
    return s.toString();       //returns already defined String
}

关于连接,创建新的时字符串, JVM 使用 StringBuilder ,即:

With respect to the concatenation, when creating a new String,JVM uses StringBuilder, ie:

s = new StringBuilder(s).append("5").toString(); 

toString() for a StringBuilder 是:

public String toString() {
    return new String(value, 0, count); //so a new String is created
}

substring 创建一个新的String对象,除非整个 String 被编入索引:

substring creates a new String object unless the entire String is indexed:

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > count) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    if (beginIndex > endIndex) {
        throw new StringIndexOutOfBoundsException(endIndex - beginIndex)
    }

    return ((beginIndex == 0) && (endIndex == count)) ? this :
           new String(offset + beginIndex, endIndex - beginIndex, value);
}

toString() NOT 是否创建新字符串:

toString() does NOT create a new String:

public String toString()
{
   return this;
}

toLowerCase()这是一个很长的方法,但是如果 String 已经全部小写,那么返回新字符串

toLowerCase() is a pretty long method, but suffice it to say that if the String is not already in all lowercase, it will return a new String.

鉴于提供的答案是 3 有关Java字符串池的问题 。

Given that the provided answer is 3, as Jon Skeet suggested, we can assume that both of the String literals are already in the String pool. For more information about when Strings are added to the pool, see Questions about Java's String pool.

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

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