ITeye博客

How many string objects are created?

standalone · 2013-06-01 10:18 · java · 编程语言 · Markdown

This is a very common java interview question.

Given the following:

String x = new String("xyz");

y="abc";

x=x+y;

How Many Strings have been created:

A - 2

B - 3

C - 4

D - 5

To answer this question, I suggest you to read

http://www.javaranch.com/journal/200409/Journal200409.jsp

评论(1)

  1. #1 楼 · standalone · 2013-06-01 10:25

    One answer I agree with:

    Whenever we create a String object..that is created in heap. Now if the object is created as a String Literal(Not using a String Constructor),then only a reference of the Object that is created in heap is stored in the StringPool.

    Take this Example.

    class A

    {

    ...

    A a1=new A();

    A a2=a1;

    A a3=a2;

    }

    Here Only one object is created in the heap, and a1,a2,a3 only are the references of that Object.

    Since the question is for Objects not References, so 3 objects are created in the heap.

评论功能维护中,当前仅展示历史评论。