Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

With the code: public class JavaIsGood { public static void main(String[] args)

ID: 3594422 • Letter: W

Question

With the code:

public class JavaIsGood {

public static void main(String[] args) {

String str = new String("I love Java!");

Object obj = str;

String n = (String)obj;

}

}

When casting obj to str in String n = (String)obj, a new object is created?

When declaring str in String str = new String(..), the String constructor is being invoked from the class String?

The new keyword in the line String str = new String(..), is instantiating the class String which means the same thing as creating a String object?

When assigning str to obj in Object obj = str, a new object is created?

Explanation / Answer

When casting obj to str in String n = (String)obj, a new object is not created as String uses string pooling i.e. if same string value exists in heap, it will point to existing Object.

When declaring str in String str = new String(..), the String constructor is being invoked from the class String?

Yes. String constructor invoked from class String.

The new keyword in the line String str = new String(..), is instantiating the class String which means the same thing as creating a String object?

Yes

When assigning str to obj in Object obj = str, a new object is created?

Yes, because the class type has changed, Object class instance may have its own extra properties which are not inn String class.