Which is the most efficient way of creating a string object in java? String s="helo"; or String s=new String("helo"); in terms of memory usage?
Thanks in advance...

Recommended Answers

All 4 Replies

Read it for yourself

String objects are immutable and you can always reuse something that is immutable because you know that it isn't going to get modified. When you are writing "String s = new String("hello");", you are creating an unnecessary object; not only that it is also inefficient cause objects creation itself is. Moreover an object created this way cannot be reused. If this statement gets called in a loop or in a method it would unnecessarily create several objects which could all have been represented by a single one. So always use the "String s = "hello";" version instead of the other, this way any other string object with the same string literal can reuse this one.

PS: You seem so intelligent when parotting intelligent people....Here the intelligent person is Joshua Bloch, psst...but let this be sold on my name.

EDIT : Beaten, Peter has pointed out the exact article/item I was mentioning from.

I'm just lazy to type it specially if I can find exact page of whatever I read previously on given topic ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.