-5

Are primitive data types mutable or immutable in java?

student{
  int id;
}

now student has id as instance member.

student st = new Student();
int id = 20;
st.id = id;
id = 30;

Does student object get changes? What happens if we use Integer wrapper class instead of primitives?

Sufian
  • 6,405
  • 16
  • 66
  • 120
Santoshkumar Kalasa
  • 477
  • 1
  • 5
  • 15

1 Answers1

3

Primitive datatypes in Java have no references. When you set

st.id = id;

you only set the value (20) on the primitive variable st.id. There is no connection between st.id and id.

Otherwise when you use Integer, st.id and id are references.

Integer id = new Integer(20);

creates and Object in the heap and id is the reference that points to it.

st.id = id;

copies the reference to st.id. This reference also points to the object (Integer(20)) in the heap.

But a change of

id = new Integer(21);

doesnt change the value of st.id. It only changes the pointer of id to a different Object in heap.

Benjamin Schüller
  • 2,104
  • 1
  • 17
  • 29