0

Given this example code:

class basic {
     public static void main(String[] args) {
        String s1 = "Java";
        String s2 = new String("Java");
    }
}

Are s1 and s2 both reference variables of an object? Do those two lines of code do the same thing?

3
  • s1 and s2 are both references, certainly. Lines 3 and 4 don't do exactly the same thing. Normally a string literal like "Java" would be comparable with == for all other literals in a program. But calling new String forces a new object and the two references are no longer equal with ==. Commented Jan 8, 2022 at 5:42
  • Welcome to Stack Overflow. Please read How to Ask. I tried to edit your question to ask the question directly, and avoid conversational language - this is not a discussion forum, thus anything to do with you as a programmer - i.e., not about the code - is off topic. Commented Jan 8, 2022 at 5:49
  • 1
    However, I'm not clear what you mean by "reference variables of an object". They are variables that have an object type (specifically, java.lang.String), which (under the hood) store object references. However, we normally just call these "objects", because Java does not let you work with the references "as references" - you only get the objects themselves whenever you interact with the variable. See e.g. javaranch.com/campfire/StoryPassBy.jsp. Commented Jan 8, 2022 at 5:50

2 Answers 2

1

Lines 3, 4 don't do the same thing, as:

String s1 = "Java"; may reuse an instance from the string constant pool if one is available, whereas new String("Java"); creates a new and referentially distinct instance of a String object.

Therefore, Lines 3 and 4 don't do the same thing.

Now, lets have a look at the following code:

String s1 = "Java";
String s2 = "Java";

System.out.println(s1 == s2);      // true

s2 = new String("Java");
System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

== on two reference types is a reference identity comparison. Two objects that are equals are not necessarily ==. Usually, it is wrong to use == on reference types, and most of the time equals need to be used instead.

Sign up to request clarification or add additional context in comments.

Comments

0

Initializing String using a new keyword String s2 = new String("Java"); creates a new object in the heap of memory. String initialized through this method is mutable means to say the value of the string can be reassigned after initialization.
Whereas, String s1 = "Java" direct String initialization using the Literal creates an object in the pooled area of memory. String created through Literal doesn’t create a new object. It just passed the reference to the earlier created object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.