1

I understand that using new String(..) will create a new object, where as literals will be stored in string pool and reused.

Is there any real time use case for this? When would I need to use new String(..)?

Why is the String.valueOf(char[]) or String.valueOf(byte[]) is designed to create new String object? Is there no way you can programmatically add the char[] to the string pool?

Edi
  • 327
  • 4
  • 16
  • How would you convert a `char[]` or probably a `byte[]` to a `String`? You will get only those when reading from `InputStream` actually... – Codebender Jan 09 '16 at 03:48
  • You probably should narrow down your question to [`new String(anotherString)`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(java.lang.String)). – PM 77-1 Jan 09 '16 at 03:52
  • The docs cover it pretty well: ["Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable."](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String%28java.lang.String%29). – resueman Jan 09 '16 at 03:53
  • A string object is a variable. A string literal is a constant. source : http://mindbugzz.blogspot.co.uk/2012/05/what-is-difference-between-strings-and.html – wmehanna Jan 09 '16 at 03:57

1 Answers1

0

One good reason is if you deal with strings that are encoded in something other than UTF. If your data is coming from some odd ASCII (or even EBCDIC) code page, you can pass it in as byte array together with the source code page and the String constructor will take care of the conversion to UTF for you.