-1

My understanding of strings in Java is that they can be either primitive types or objects. When creating strings is it better to create them as objects with the new command and a constructor or as a primitive type similar to int?

user1454994
  • 303
  • 3
  • 5
  • 12
  • 3
    Strings are always objects in Java, regardless of whether or not `new` keyword is used. It usually doesn't make sense to use the `new` keyword though, since it forces the creation of a new instance instead of re-using String instances in the String pool. – Eran Feb 17 '16 at 09:57
  • String is always a object. – Pragnani Feb 17 '16 at 09:57
  • Even when it is declared as `String courseName = "math";` ? – user1454994 Feb 17 '16 at 09:58
  • 1
    Yes, this still creates a String object that contains the value "math". This way is preferable to `new String("math")` though. – Eran Feb 17 '16 at 10:00
  • 1
    Yes.. but String literals are saved in String Constant pool but not in Heap – Pragnani Feb 17 '16 at 10:01
  • @PragnaniKinnera - String constants pool is at the end part of heap :P – TheLostMind Feb 17 '16 at 10:01
  • @TheLostMind yeah I know.. but they will be in special place called PermGen space( permanent generation ). Since it is a separate region, it is not considered part of the Java Heap space – Pragnani Feb 17 '16 at 10:04
  • @PragnaniKinnera - *Since JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application.* Check [here](http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes) – TheLostMind Feb 17 '16 at 10:07

1 Answers1

4

My understanding of strings in Java is that they can be either primitive types or objects

Wrong. Strings are always objects. Its just that String literals ("someStringHere") are treated in a special manner by the compiler and then interned by the JVM.

If your question is whether -

String s = "Abc";
is better than
String s = new String("Abc");,
Yes, since the second one is redundant and creates 2 Strings (one in constants pool and another on heap).

TheLostMind
  • 35,966
  • 12
  • 68
  • 104