Immutable and Not Immutable objects - Pooky/java-enterprise-examples GitHub Wiki

Java objects

Java is objected oriented, that's kind of different from functional programing. Everything in Java is object, except from some specific cases. Let's talk about Immutable and Not-Immutable objects.

Immutable and Not-Immutable objects

I don't know, who design java terminology but I never understand, why they use this fancy world. It's much better to replace it with different changeless or unalterable. So Immutable is changeless, unalterable. That mean, not possible to change.

What does that mean?

Object's in Java can be changeable or changeless. Object that you can not change are called changeless. After you create them, you can not change their content. Few examples of this objects are:

  • String
  • Integer
  • Boolean

This types do not have any method, which would allow you to change their value or content. They don't provide any method like "setValue()" or "updateValue()". To change value of this object, you need to create new one.

You create a new String object and store reference in variable a. Now, if you would like to change value of a you need to create new string and assign it to variable. There is no other way around. The old reference to the String will be destroyed automatically, by java mechanism called garbage collector.

// Create new String
String a = "19";

// Create another String
String a = new String("19");

// And one more
String a = String.valueOf("19");

In above example, we use different possibilities how to create String. Every time we creating new String, even if the value of the String is same as previous! That's really important. What is happening behind the scene is something like this:

Variable a = empty;

// Create new String
String a = "19";

// Assign new reference variable a to new String
Variable a = reference #1

// Create another String
String a = new String("19");

// Old reference is replaced with new reference
Variable a = reference #2

// And one more
String a = String.valueOf("19");

// Old reference is replaced with new reference
Variable a = reference #3

// Unused references are collected and then removed by Java Garbage Collector
reference #1 - will be removed
reference #2 - will be removed

For better understanding, now see some objects, which can be changed.

Changeable objects

Object in java can look like this:

class MyObject{

    private String valueOfObject;

    public void setValue(String value){
        this.valueOfObject = value;
    }

}