Chapter:Classes - Strings are immutable - Exercises

From Juneday education
Jump to: navigation, search

Exercises on immutable Strings

Q1

What is printed from this small snippet?

String name = "Anton";
name.toUpperCase();
System.out.println(name);

Expand using link to the right to see a suggested solution/answer.

"Anton" is printed. toUpperCase() doesn't change the string, it creates a new one

Q2

Change the snippet above so that it prints ANTON instead, with the help of toUpperCase().

Expand using link to the right to see a suggested solution/answer.

Suggestion: System.out.println(name.toUpperCase());

Q3

A private instance variable of type reference to String exists in a class Passport. The variable is called passportNumber. A public instance method passportNumber() returns a reference to the variable. Can code from a different class change the value of the passportNumber instance variable of any Passport object?

Expand using link to the right to see a suggested solution/answer.

No, even if code in other classes can get a reference to the instance variable, it cannot change it. Strings are immutable, and since the variable is private, no code can re-assign it to a new String either.

Q4

You want to make a class immutable. How would you change the changeColor() method? The only constructor for the class is included.

// The only constructor
public SomeClass(Color c) {
  this.color = c;
}
// The method to change color:
public void changeColor(Color c) {
  this.color = c;
}

Expand using link to the right to see a suggested solution/answer.

This is one solution, make the method return a new instance with the new color as argument to the only constructor:

public SomeClass changeColor(Color c){
  return new SomeClass(c); // don't change the object, return a reference to a new one instead!
}

Links

Further reading

Where to go next

Next page is: Java_Classes_Wrapping_it_up

« PreviousBook TOCNext »