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)?
c2 = c1you make both variables refer to the same object. You don't reassign those variables after that, so they remain the same object. When you dod2 = d1you make both variables refer to the same object. But thend1 = 15makesd1refer to a different object.obj.method(value)is totally different thanobj = value? first one is calling a method of the instance pointed to byobj; second one is changing (replacing) the pointer to point to another instance (this actually is independent of being immutable or not)