Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String declaration - Two different types, which is better? [duplicate]

Possible Duplicates:
Java String declaration
Java Strings: “String s = new String(”silly“);”
What is the purpose of the expression “new String(…)” in Java?

Whats is the difference between

String a = new String("SomeValue");

and

String a = "SomeValue";

What is the difference and Which one is better and why ?

Thanks.

like image 685
nik7 Avatar asked Dec 31 '25 16:12

nik7


1 Answers

Unless you have a unusual, specific need and use case, always use the 2nd version, without the new.

Edited in response to @Ynwa

If you specifically need a String that you know is unique, and you will be comparing with == (which is also unusual), then use the 1st case. For example, it you have some Queue of Strings, and you need a specific String to mean "all done". Now, conceivably, you could use null or some weird String of Armenian characters, but maybe null is legal for your logic, and what if your software eventually gets used in Armenia? The clean way is

    public final static String TERMINATOR = new String("Terminator");  // actual text doesn't matter ... 
   // then, some loop taking from the Queue 
   while (keepGoing) {    
      String s = myQueue.take();    
      if (s == TERMINATOR) 
         keepGoing = false;    
     else   
       // normal processing of s 
   }

If the client puts "Terminator" on the Queue, it will get processed. So you do not prevent them from using "Terminator". But if the client puts ThatQueueClass.TERMINATOR onto the Queue, it will get shut down.

like image 172
user949300 Avatar answered Jan 02 '26 10:01

user949300



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!