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.

Hi Na'Vi,
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.

Happy Coding :)
Sunny_K

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.

can't pass the String object as a parameter to create a string with that

Suggest you read the API doc for String. Passing a String as a parameter to a String copnstructor is perfectly OK.

public 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.

actually, when u create string object.. java already inherit java.object class..

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

commented: +1 +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.