-1

What is the difference between creating Object, for example in my code, type Obj with operator "new" and Object type String?

public class Objs {
    int a;

    public Objs(int a)
    {
        this.a = a;
    }

    public static void main(String[] args)
    {
        String str = new String("Hello");
        String str1 = str; // (str1 == str) == true
        str += ", world!!"; // after this (str1 == str) == false - Why?

        Objs o = new Objs(4);
        Objs o1 = o;        //(o == o1) == true
        o.a += 9;           // after this (o == o1) == true also
    }
}

Why after I'm changing value of "str", references "str" and "str1" become not equal, but if I'm doing the same with class Obj references stay equal?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
A.Starshov
  • 39
  • 6
  • 3
    Strings are immutable in Java. The assignment operator is putting a new string instance into the `str` variable, not modifying the original. Meanwhile, you never change the value referred to by the reference `o`. You simply update a property on that object instance. – nbrooks Mar 11 '19 at 20:41
  • 2
    you are not doing the same: adding something to an object (`str +=`) is not the same as adding something to a field of an object(`o.a +=`) {{your title is totally misleading - not related to `new`}} – user85421 Mar 11 '19 at 20:43
  • Besides what @nbrooks said, important thing here is that: equals() compares the content and == checks the reference. – alexandrum Mar 11 '19 at 20:44

2 Answers2

5

Here:

str += ", world!!"

you're creating a new object with changed value (that's how + operator works for Strings in java). Here:

o.a += 9; 

you're modifying the field of the object, but it's still the same reference.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
0

Because a String type in Java is immutable that means a string object can not be modified, instead, a new string object is created with the given expression.

str += ", world!!"; // at this line, a new str object is created with given concatenation, hence str loses reference to the previous object and now points to the new one - that is the reason.

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25