Tekin Güllü
Tekin Güllü

Reputation: 363

Java Assign Class Values

It is a simple silly question but I don't know but how can I state the situation myself. Assume I have a class like this

public class MyClass
{
  public int value1;
  public void assignValue(int v1)

    {
        value1=v1;
    }
    public MyClass(int v1)
    {
        value1=v1;
    }
    public void write()
    {
        System.out.println("value1 :"+value1);
    }
}

If I run My Program like this

public class Program {

    public static void main(String args[])
    {
        //first
        MyClass c1 = new MyClass(10);
        MyClass c2 = new MyClass(20);
        c2 = c1;
        c1.assignValue(15);
        c1.write();
        c2.write();

       //but these are classes too.
       Integer d1 = 10;//also Integer d1 = new Integer(10); same
       Integer d2 = 20;
       d2 = d1;
       d1 = 15;
       System.out.println(d1);
       System.out.println(d2);
    }
}

Why c1 and c2 s values are equal and why not d1 and d2 are not(I have created from Integer Class an object)?

Upvotes: 0

Views: 1819

Answers (3)

Shravan40
Shravan40

Reputation: 9888

c2 = c1; // Both are pointing to same object

c1.AssignValue(15); // Value is being updated, not the actual reference.

Now, coming to the 2nd part of the code.

d2 = d1; // Both are pointing to same object

d1 = 15; // Reference object has been updated

But d2 are still pointing to the old object.

Upvotes: 2

Vasco
Vasco

Reputation: 802

When you do c2 = c1; you are assingning the reference of the object.

When you do d1 = 15; you are essentially doing d1= new Integer(15). A new object is created and the reference of that held by d1. d2 is still referencing the old object (10)

Upvotes: 0

Shankar kota
Shankar kota

Reputation: 111

Here c1.AssignValue(15); you are changing value not the object reference, but d1 = 15; this will change the object reference.

Upvotes: 1

Related Questions