ahmed_khan_89
ahmed_khan_89

Reputation: 2773

When should I creat String as new() and literal?

I really don't know when and why should I use the constructor for String and not the literal way. I have already looked, found some answers of differences which were not really clear... but nothing about the best practices or "why?" and "when?"

I understood that literal definition is treated by the JVM but also that they are not handled by the Garbage Collector (like static staff, annotations ...)... could this really be a problem for the memory of the JVM ?

I added here the shortest comparison that I found:

What is the difference between creating String as new() and literal? When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

Thank you for your time and help.

Upvotes: 2

Views: 123

Answers (1)

Dolda2000
Dolda2000

Reputation: 25855

Mainly, you'll find yourself using new String when you have some dynamically constructed char[] or byte[] that you want to use as a string. This could be for such reasons as having received data from the network into a byte[] buffer, but there are a multitude of possible reasons.

Note also that, if you want your new string interned into the string pool, you can use the intern() method.

The pool of interned strings hasn't been put into the permgen for quite a while, by the way, and in Java 8 the permgen was removed altogether.

Upvotes: 5

Related Questions