An immutable object is one that cannot be changed (with the expectation that you get the same object back). This might be slightly confusing, so let me explain one of the simplest examples I can think of. Say I have the following code:
string myString = "Hello World!";
Strings are an example of immutable objects. Now, obviously you can change the value of myString
, however, you are not simply making changes to the myString
object when you do this. The language actually creates a NEW string object that myString
will point to. (I cannot remember the exact details for how this works, for the reason why, see this answer)
//This is creating a new string object, although it looks like a simple
//manipulation of what currently exists.
myString = "Goodbye World!";
Immutable variables (as you call them) on the other hand (commonly referred to as "constants" or "constant fields" in my experience), CANNOT change. Your compiler will complain if you attempt to modify it in any way. There are many reasons why you'd want to do that (a Google search will give you dozens). In short, make a field constant where you know the value will never and should never be altered, even if by accident.
This might be a weak example, but say you have a program that builds a Vehicle
object and you know the most wheels you will ever need is 18. You could say:
const int MAX_WHEELS = 18;
And that can never change by accident. Any time you use MAX_WHEELS, it will always be 18. I do not know the details, but it seems likely that the compiler will just substitute value in for the field name, but maybe someone can correct me on that.