String q = new String(“Cat”);
String r = q;
String s = new String(r);
I understand that the first line would equate to String q = "Cat"; and the second would be String r = q;, but what would the last one equate to without using new? I originally thought it was the same as the second line, but later it says that two string objects are created.
I would like to explain you how the string() works.. it actually takes an array of characters as input to create a string. You can impose a String object to another directly but can't pass the String object as a parameter to create a string with that. Hope this explanation help you.
Strings can be considered as wrapper classes for character arrays(But they are not so in reality.).The first two lines of your code refer to the same String literal Cat.But declaring another String f like this:
String f=new String("Cat");
will casue it ti point to another memory location in the heap.The same is true for all other wrapper classes.
Some slightly confusing replies here, so to clarify...
To understand these examples you need to be clear on the difference between a String object (contains a sequence of characters stored on the heap somewhere) and a String variable (contains a reference (like a pointer) to a String object).
new String("cat") creates a a new String object containing the character sequence "cat" String q = ... creates a reference variable that refers to that new String object String r = q; creates another reference variable, and copies the value (reference) from q into it. r and q now both refer to the same String object. new String(r) creates another new String object. It gets its character sequence by copying the character sequence from the String that r refers to. You now have two distinct String objects which contain identical sequences of characters String f = ... creates a reference variable that refers to that new String object