Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Strings: "String s = new String("silly");"

Tags:

java

string

I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:

String s = new String("silly"); 

Because it creates unnecessary String objects. But instead it should be written like this:

String s = "No longer silly"; 

Ok fine so far...However, given this class:

public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish"; 
  1. Why is the first statement ok? Shouldn't it be

    CaseInsensitiveString cis = "Polish";

  2. How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?

like image 763
JavaNewbie Avatar asked Dec 02 '08 16:12

JavaNewbie


People also ask

What is String s new String ()?

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 does String s mean in Java?

In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char[] ch={'j','a','v','a','t','p','o','i','n','t'}; String s=new String(ch);

What is difference between String and new String?

String(String original) : Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

What happens when we create String using new operator?

So, in your case : String a = new String("abc"); "abc" will be resolved as a compile time constant and thus will be added to the String constants pool for the current JVM. Next, the value of a will be resolved at run-time and will be added to the heap during run-time.


1 Answers

String is a special built-in class of the language. It is for the String class only in which you should avoid saying

String s = new String("Polish"); 

Because the literal "Polish" is already of type String, and you're creating an extra unnecessary object. For any other class, saying

CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); 

is the correct (and only, in this case) thing to do.

like image 120
Adam Rosenfield Avatar answered Sep 20 '22 11:09

Adam Rosenfield