0

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...

Edited by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by fardoonmuhafiz
2

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.

Edited by verruckt24: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.