educative.io

Educative

Immutability of int data type

In the example “Exercise: thermometer” sample solutions shows the int temperature’s variable value being changed from -5 to 10. Isnt an int a primitive data type that is immutable?

class Temperature {
  
  public static void main(String[] args) { 

    int temperature = -5;
    if(temperature < 0) {
      System.out.println("It's very, very cold!");
    } 

    temperature = 10;
    if(temperature >= 0) {
      System.out.println("It's not so cold!"); 
    }
  }
}

Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hi Padmanathan!
Actually you are conflating two things:

  • Changing the value of an object itself
  • Changing the object a reference points to

Here temperature = 10 just points the temperature variable to a new object like this:
temperature = new Integer(10)
by the compiler. It doesn’t change the Integer object which originally was pointed to temperature.

Hope it helps. If you still have any queries, please let us know.
Thank you!