0

There is a rule in Java, that to create any object of class we have to use 'new' keyword, but when we use String class,we can create object as

String s = "hello"; 

so we haven't used new as an operator still new object has been created in String constant pool in heap! Can anyone explain how we created an object without using new keyword!

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Anuj Patel
  • 39
  • 1
  • 5
  • `"hello"` is a `String` [literal](https://en.wikipedia.org/wiki/Literal_(computer_programming)) – Amadan Sep 30 '19 at 08:30
  • 1
    Java language designers are free to build any "magic" into the compiler. Creating objects without `new` keyword is one of these. Another situation when an object is created without `new` keyword is autoboxing. – Sergey Kalinichenko Sep 30 '19 at 08:31
  • Read [this](https://stackoverflow.com/a/41908347/5675692) – Ashvin Sharma Sep 30 '19 at 08:32
  • The ClassLoader delivered a String. Actually "hello" is stored as UTF-8 string in the .class using it. – Joop Eggen Sep 30 '19 at 08:32
  • This is a String literal - a fixed value in **source code**. So it's done on compilation (checking with pool). – miiiii Sep 30 '19 at 08:34
  • So in heap memory, there are two partition, one is String constant pool and another is heap (non constant) pool. Am i right? Correct me if i am wrong! – Anuj Patel Sep 30 '19 at 08:45

1 Answers1

1

Comparision of string initialization performance for String Literal and String object. :

String Literal
String str = “Hello”;

This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “Hello”, then str will reference of that string and no new String object will be created.

String Object
String str = new String(“Hello”);

This is string object. In this method JVM is forced to create a new string reference, even if “Hello” is in the reference pool.

taurus05
  • 2,491
  • 15
  • 28
  • Got your point, just need bit more understanding about string constant pool and heap pool – Anuj Patel Sep 30 '19 at 08:43
  • So in heap memory, there are two partition, one is String constant pool and another is heap (non constant) pool. Am i right? Correct me if i am wrong! – Anuj Patel Sep 30 '19 at 08:45
  • 1
    For clarity: The seven characters `"Hello"` make up a String literal, in both cases. `str` is a variable containing a String object, in both cases. `new String("Hello")` picks up the object defined by the literal and makes another object from it. Also, be careful when pasting code into Stack Overflow: this code cannot be compiled because the quotes are not 'QUOTATION MARK' (U+0022). – Amadan Sep 30 '19 at 08:55