Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between String initializations by new String() and new String("") in Java?

Tags:

What is the difference between the following two initializations in Java?

  1. String a = new String();
  2. String b = new String("");
like image 531
user3575425 Avatar asked Apr 09 '15 10:04

user3575425


People also ask

What is the difference between string literal vs New String () in Java?

When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists.

What is new String () in Java?

By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.

What is difference between String str abc and String str new String ABC?

In other words doing String s = new String("ABC") creates a new instance of String , while String s = "ABC" reuse, if available, an instance of the String Constant Pool.

What is the difference between String s Hello and String s new String Hello?

The statement String s = “hello” is initialized to s and creates a single interned object. While String s = new String(“hello”); creates two string objects, one – interned object, two – object on the heap.


1 Answers

Well, they are almost the same.

public static void main(String[] args) {     String s1 = new String();     String s2 = new String("");      System.out.println(s1.equals(s2)); // returns true. } 

Minor differences (rather insignificant) :

  1. new String(); takes less time to execute than new String(""); because the copy constructor does a lot of stuff.

  2. new String("") adds the empty String ("") to the String constants pool if it is not already present.

Other than this, there are no other differences

Note : The use of new String("abc") is almost always bad because you will be creating 2 Strings one on String constants pool and another on heap with the same value.

like image 92
TheLostMind Avatar answered Nov 27 '22 15:11

TheLostMind