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";
Why is the first statement ok? Shouldn't it be
CaseInsensitiveString cis = "Polish";
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?
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.
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With