Immutable Strings

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Could print() use the reference to the original String object to change the contents of that object?

Answer:

No — because String objects are immutable. Not even the main() method can change the original object.

Immutable Strings

It is good that String objects are immutable (they can't be changed) because the main() method can be sure that the message is completely under its control. Although the print() method gets a copy of the reference, it can't change the original object.

Not all objects are immutable. For example, in the following, MyPoint objects have public instance variables x, and y. These can be changed by any method that has a referece to the object.

class MyPoint
{
  public int x=3, y=5;

  public void print()
  {
    System.out.println("x = " + x + "; y = " + y );
  }
}

class PointTester
{
  public static void main ( String[] args )
  {
    MyPoint pt = new MyPoint();

    pt.print();

    pt.x = 45;  pt.y = 83;

    pt.print();
  }
}

Important: Public instance variables of objects can be changed by any method that has a reference to the object.

(If an instance variable is neither public nor private it can be changed by a method that is in the same package. For now, all of our code is in the same package, so the effect is the same as if it were public.)

The main() method uses the default constructor of class MyPoint. This is the constructor you get automatically if you do not define one yourself.


QUESTION 10:

What is the output of the program?
x =   y = 

x = y =