Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String declaration [duplicate]

Tags:

java

string

What is the difference between String str = new String("SOME") and String str="SOME" Does these declarations gives performance variation.

like image 558
JavaUser Avatar asked Sep 06 '10 14:09

JavaUser


People also ask

How do you duplicate a string in Java?

To make a copy of a string, we can use the built-in new String() constructor in Java. Similarly, we can also copy it by assigning a string to the new variable, because strings are immutable objects in Java.

How do you repeat a string of characters in Java?

Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);

How do you repeat a string?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

Can I declare in string Java?

By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”);


3 Answers

String str = new String("SOME") 

always create a new object on the heap

String str="SOME"  

uses the String pool

Try this small example:

        String s1 = new String("hello");         String s2 = "hello";         String s3 = "hello";          System.err.println(s1 == s2);         System.err.println(s2 == s3); 

To avoid creating unnecesary objects on the heap use the second form.

like image 187
PeterMmm Avatar answered Sep 30 '22 05:09

PeterMmm


There is a small difference between both.

Second declaration assignates the reference associated to the constant SOMEto the variable str

First declaration creates a new String having for value the value of the constant SOME and assignates its reference to the variable str.

In the first case, a second String has been created having the same value that SOME which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOMEare transformed into the same instance, which uses far less memory.

As a consequence, always prefer second syntax.

like image 22
Riduidel Avatar answered Sep 30 '22 06:09

Riduidel


String s1 = "Welcome"; // Does not create a new instance  
String s2 = new String("Welcome"); // Creates two objects and one reference variable  
like image 28
bhargava krishna Avatar answered Sep 30 '22 05:09

bhargava krishna