Revealing a common mistake with Strings – Objects, Immutability, Switch Expressions, and Pattern Matching

46. Revealing a common mistake with Strings

Everybody knows that String is an immutable class. In Java Coding Problems, First Edition, Chapter 2, Problem 48, we have even dissected how this class works and what are the consequences of its immutability.Even so, we are still prone to accidentally write code that ignores the fact that String is immutable. Check out this code:

String str = “start”;
str = stopIt(str);
public static String stopIt(String str) {
  str.replace(str, “stop”);                      
  return str;
}

Somehow, it is logical to think that the replace() call has replaced the text start with stop and now str is stop. This is the cognitive power of words (replace is a verb that clearly induces the idea that the text was replaced). But, String is immutable! Oh … we already know that! This means that replace() cannot alter the original str. There are many such silly mistakes that we are prone to accidentally do, so pay extra attention to such simple things, since they can waste your time in debugging stage.The solution is obvious and self-explanatory:

public static String stopIt(String str) {
  str =  str.replace(str, “stop”);                      
  return str;
}

Or, simply:

public static String stopIt(String str) {
  return str.replace(str, “stop”);                               
}

Don’t forget that String is immutable!

47. Using the enhanced NullPointerException

Take your time to dissect the following trivial code and try to identify the parts that are prone to cause a NullPointerException:

public final class ChainSaw {
  private static final List<String> MODELS
    = List.of(“T300”, “T450”, “T700”, “T800”, “T900”);
  private final String model;
  private final String power;
  private final int speed;
  public boolean started;
  private ChainSaw(String model, String power, int speed) {
    this.model = model;
    this.power = power;
    this.speed = speed;
  }
  public static ChainSaw initChainSaw(String model) {
    for (String m : MODELS) {
      if (model.endsWith(m)) {  WARNING 3!
        return new ChainSaw(model, null,  WARNING 5!
          (int) (Math.random() * 100));
      }
    }
    return null;  WARNING 1,2!
  }
  public int performance(ChainSaw[] css) {
    int score = 0;
    for (ChainSaw cs : css) {  WARNING 3!
      score += Integer.compare(
        this.speed, cs.speed);  WARNING 4!
    }
    return score;
  }
  public void start() {
    if (!started) {
      System.out.println(“Started …”);
      started = true;
    }
  }
  public void stop() {
    if (started) {
      System.out.println(“Stopped …”);
      started = false;
    }
  }       
  public String getPower() {
    return power;  WARNING 5!
  }
  @Override
  public String toString() {
    return “ChainSaw{” + “model=” + model
      + “, speed=” + speed + “, started=” + started + ‘}’;
  }      
}

You’ve noticed the warnings? Of course, you did! There are 5 major scenarios behind the most NullPointerException (NPE) and each of them is present in the previous class. Before JDK 14, an NPE doesn’t contain detailed information about the cause. Look at this exception:

Exception in thread “main” java.lang.NullPointerException
    at modern.challenge.Main.main(Main.java:21)

This message is just a starting point for the debugging process. We don’t know the root cause of this NPE or which variable is null. But, starting with JDK 14 (JEP 358), we have really helpful NPE messages. For example, in JDK 14+, the previous message looks as follows:

Exception in thread “main” java.lang.NullPointerException: Cannot invoke “modern.challenge.Strings.reverse()” because “str” is null
    at modern.challenge.Main.main(Main.java:21)

The highlighted part of the message gives us important information about the root cause of this NPE. Now, we know that the str variable is null, so no need to debug further. We can just focus on how to fix this issue.Next, let’s tackle each of the 5 major root causes of NPEs.

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2024 nickshade Please read our Terms and Privacy Policy. We also use Cookies.