{"id":"references-null","slug":"null-and-nullpointerexception","title":"null and NullPointerException","text":"A reference variable can also point at no object at all. Its value is then `null`:\n\n```java\nString nickname = null;\nSystem.out.println(nickname);\nSystem.out.println(\"Nickname: \" + nickname);\n```\n\n```output\nnull\nNickname: null\n```\n\n`null` is a value of its own, written without quotes. Printing it, or joining it to a String with `+`, shows the word `null`. Only reference variables can be `null`: `int count = null;` doesn't compile, because an `int` always holds a number.\n\n### Calling a method on null\n\nA method call needs an object to run on. When the variable is `null` there's none, and the program crashes with a **NullPointerException**:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        Bike bike = null;\n        System.out.println(\"Ready to ride\");\n        bike.ride(10);\n        System.out.println(bike);\n    }\n}\n// ==== Bike.java ====\npublic class Bike {\n    private String color;\n    private int km;\n\n    public Bike(String color, int km) {\n        this.color = color;\n        this.km = km;\n    }\n\n    public void ride(int km) {\n        this.km = this.km + km;\n    }\n\n    public String toString() {\n        return \"The \" + this.color + \" bike, \" + this.km + \" km\";\n    }\n}\n```\n\n```output\nReady to ride\n```\n\n```crash\nException in thread \"main\" java.lang.NullPointerException: Cannot invoke \"Bike.ride(int)\" because \"<local1>\" is null\n\tat Main.main(Main.java:5)\n```\n\nThe message says what the program tried to do, call `ride(int)` on a Bike, and what was null. `<local1>` is a local variable. The compiled program here keeps local variables by number, not by name: `<local0>` is `main`'s parameter `args`, so `<local1>` is `bike`. Many editors compile with the names kept (`javac -g`), and then the message says `\"bike\" is null`. For an instance variable, the message names it, as in `\"this.owner\" is null`. The line number tells you where to look.\n\nNobody writes `Bike bike = null;` and then calls a method on it on purpose. In real programs the null comes from somewhere less obvious:\n\n- **A search that found nothing.** A method that looks for an object often returns `null` when nothing matches.\n- **An instance variable that was never set.** An instance variable of a class type starts as `null` and stays that way until the constructor or a method gives it an object. A missing `this.` in the constructor (module 18) leaves it `null` too.\n- **An array element that was never filled.** `new Bike[3]` makes an array of three `null`s, not three bikes.\n\nThe crash happens where the null is used, which can be far from where it came from. So after reading the message, ask where that variable was supposed to get its object.\n\n### Checking for null\n\nWhen a variable may be `null`, check it before calling its methods. `==` and `!=` tell whether a reference is `null`:\n\n```java\nimport java.util.ArrayList;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<Bike> bikes = new ArrayList<>();\n        bikes.add(new Bike(\"blue\", 120));\n        bikes.add(new Bike(\"red\", 45));\n\n        Bike found = find(bikes, \"red\");\n        if (found != null) {\n            found.ride(5);\n            System.out.println(found);\n        }\n\n        Bike missing = find(bikes, \"yellow\");\n        if (missing == null) {\n            System.out.println(\"No yellow bike\");\n        }\n    }\n\n    public static Bike find(ArrayList<Bike> bikes, String color) {\n        for (Bike bike : bikes) {\n            if (bike.getColor().equals(color)) {\n                return bike;\n            }\n        }\n        return null;\n    }\n}\n// ==== Bike.java ====\npublic class Bike {\n    private String color;\n    private int km;\n\n    public Bike(String color, int km) {\n        this.color = color;\n        this.km = km;\n    }\n\n    public String getColor() {\n        return this.color;\n    }\n\n    public void ride(int km) {\n        this.km = this.km + km;\n    }\n\n    public String toString() {\n        return \"The \" + this.color + \" bike, \" + this.km + \" km\";\n    }\n}\n```\n\n```output\nThe red bike, 50 km\nNo yellow bike\n```\n\n- `find` returns the first bike of the color, or `null` when the loop finds none. Returning `null` is a common way to say \"not found\", and then every caller has to check for it.\n- `found` points at the red bike in the list, not at a copy of it, so `found.ride(5)` rides the bike in the list.\n\nA null check can share a condition with a test on the object, because `&&` looks at its right side only when its left side is `true`. In `if (bike != null && bike.getColor().equals(\"red\"))`, `getColor()` is never called on `null`. In the same way, `||` looks at its right side only when its left side is `false`.\n","task":"`Coat.java` is ready, and the method `find` returns the coat with the given ticket number, or `null` when no coat has it. The program reads a ticket number and hands out the coat, but it crashes when the ticket isn't found. Check what `find` returned before using it, and when it's `null`, print `No coat with ticket` and the number. With the input `7` the program prints `Here is your gray wool coat`, and with the input `5` it prints:\n\n```\nNo coat with ticket 5\n```\n","kind":"code","seed":"// ==== Main.java ====\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<Coat> coats = new ArrayList<>();\n        coats.add(new Coat(12, \"red raincoat\"));\n        coats.add(new Coat(7, \"gray wool coat\"));\n        coats.add(new Coat(31, \"green parka\"));\n\n        Scanner scanner = new Scanner(System.in);\n        int ticket = Integer.valueOf(scanner.nextLine());\n        Coat coat = find(coats, ticket);\n        System.out.println(\"Here is your \" + coat.getDescription());\n    }\n\n    public static Coat find(ArrayList<Coat> coats, int ticket) {\n        for (Coat coat : coats) {\n            if (coat.getTicket() == ticket) {\n                return coat;\n            }\n        }\n        return null;\n    }\n}\n\n// ==== Coat.java ====\npublic class Coat {\n    private int ticket;\n    private String description;\n\n    public Coat(int ticket, String description) {\n        this.ticket = ticket;\n        this.description = description;\n    }\n\n    public int getTicket() {\n        return this.ticket;\n    }\n\n    public String getDescription() {\n        return this.description;\n    }\n}\n","solution":"// ==== Main.java ====\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        ArrayList<Coat> coats = new ArrayList<>();\n        coats.add(new Coat(12, \"red raincoat\"));\n        coats.add(new Coat(7, \"gray wool coat\"));\n        coats.add(new Coat(31, \"green parka\"));\n\n        Scanner scanner = new Scanner(System.in);\n        int ticket = Integer.valueOf(scanner.nextLine());\n        Coat coat = find(coats, ticket);\n        if (coat == null) {\n            System.out.println(\"No coat with ticket \" + ticket);\n        } else {\n            System.out.println(\"Here is your \" + coat.getDescription());\n        }\n    }\n\n    public static Coat find(ArrayList<Coat> coats, int ticket) {\n        for (Coat coat : coats) {\n            if (coat.getTicket() == ticket) {\n                return coat;\n            }\n        }\n        return null;\n    }\n}\n\n// ==== Coat.java ====\npublic class Coat {\n    private int ticket;\n    private String description;\n\n    public Coat(int ticket, String description) {\n        this.ticket = ticket;\n        this.description = description;\n    }\n\n    public int getTicket() {\n        return this.ticket;\n    }\n\n    public String getDescription() {\n        return this.description;\n    }\n}\n","hints":["For the ticket 5, `find` returns `null`, and `coat.getDescription()` then has no coat to run on. Check first: `if (coat == null) { ... } else { ... }`.","When it's `null`, print `\"No coat with ticket \" + ticket`. Otherwise print the line that's already there."],"tests":[{"name":"Test 1","stdin":"5\n","expect":"No coat with ticket 5","hidden":false},{"name":"Test 2","stdin":"7\n","expect":"Here is your gray wool coat","hidden":false},{"name":"Test 3","stdin":"12\n","expect":"Here is your red raincoat","hidden":true},{"name":"Test 4","stdin":"31\n","expect":"Here is your green parka","hidden":true},{"name":"Test 5","stdin":"0\n","expect":"No coat with ticket 0","hidden":true}],"require":[{"pattern":"(==|!=)\\s*null\\b|\\bnull\\s*(==|!=)","message":"Check whether `find` returned `null`, with `coat == null` or `coat != null`, before calling a method on it."}],"forbid":[],"more":[{"task":"A profile shows its nickname when it has one, and the full name otherwise. The program crashes on Tom, who never set a nickname: his `nickname` is still `null`, not the empty String `\"\"`. Read the crash message, then fix `Profile.java` so the program prints:\n\n```\nMia\nTom Berg\n```\n","kind":"code","seed":"// ==== Profile.java ====\npublic class Profile {\n    private String name;\n    private String nickname;\n\n    public Profile(String name) {\n        this.name = name;\n    }\n\n    public void setNickname(String nickname) {\n        this.nickname = nickname;\n    }\n\n    public String getDisplayName() {\n        if (this.nickname.isEmpty()) {\n            return this.name;\n        }\n        return this.nickname;\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Profile maria = new Profile(\"Maria Lopez\");\n        maria.setNickname(\"Mia\");\n        Profile tom = new Profile(\"Tom Berg\");\n        System.out.println(maria.getDisplayName());\n        System.out.println(tom.getDisplayName());\n    }\n}\n","solution":"// ==== Profile.java ====\npublic class Profile {\n    private String name;\n    private String nickname;\n\n    public Profile(String name) {\n        this.name = name;\n    }\n\n    public void setNickname(String nickname) {\n        this.nickname = nickname;\n    }\n\n    public String getDisplayName() {\n        if (this.nickname == null) {\n            return this.name;\n        }\n        return this.nickname;\n    }\n}\n\n// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Profile maria = new Profile(\"Maria Lopez\");\n        maria.setNickname(\"Mia\");\n        Profile tom = new Profile(\"Tom Berg\");\n        System.out.println(maria.getDisplayName());\n        System.out.println(tom.getDisplayName());\n    }\n}\n","hints":["The message says `\"this.nickname\" is null`: the constructor never gives `nickname` a value, so for Tom it's still `null`, and `isEmpty()` has no String to run on.","Ask whether there's a nickname at all: `if (this.nickname == null)`. (Giving `nickname` a starting value of `\"\"` in the constructor would work too.)"],"tests":[{"name":"The program","stdin":"","expect":"Mia\nTom Berg","hidden":false},{"name":"Test 2","stdin":"","call":"Profile p = new Profile(\"Ana Silva\");\nSystem.out.println(p.getDisplayName());\np.setNickname(\"Nana\");\nSystem.out.println(p.getDisplayName());\n","expect":"Ana Silva\nNana","hidden":true},{"name":"Test 3","stdin":"","call":"Profile p = new Profile(\"Li Wei\");\np.setNickname(\"Wei\");\nSystem.out.println(p.getDisplayName());\n","expect":"Wei","hidden":true}],"require":[],"forbid":[]},{"task":"A small car park keeps its spots in an array: `spots[0]` is spot 1, `spots[1]` is spot 2, and so on, and an empty spot is `null`. `Car.java` is ready. In `Main`, write a method `printSpots(Car[] spots)` that prints every spot, with the plate of the car in it or `free`. The check runs:\n\n```java\nCar[] spots = new Car[4];\nspots[0] = new Car(\"KLM-204\");\nspots[2] = new Car(\"XT-9981\");\nprintSpots(spots);\n```\n\nand expects:\n\n```\nSpot 1: KLM-204\nSpot 2: free\nSpot 3: XT-9981\nSpot 4: free\n```\n","kind":"code","seed":"// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Car[] spots = new Car[4];\n        spots[0] = new Car(\"KLM-204\");\n        spots[2] = new Car(\"XT-9981\");\n        printSpots(spots);\n    }\n\n    // Write the printSpots method here.\n}\n\n// ==== Car.java ====\npublic class Car {\n    private String plate;\n\n    public Car(String plate) {\n        this.plate = plate;\n    }\n\n    public String getPlate() {\n        return this.plate;\n    }\n}\n","solution":"// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Car[] spots = new Car[4];\n        spots[0] = new Car(\"KLM-204\");\n        spots[2] = new Car(\"XT-9981\");\n        printSpots(spots);\n    }\n\n    public static void printSpots(Car[] spots) {\n        for (int i = 0; i < spots.length; i++) {\n            if (spots[i] == null) {\n                System.out.println(\"Spot \" + (i + 1) + \": free\");\n            } else {\n                System.out.println(\"Spot \" + (i + 1) + \": \" + spots[i].getPlate());\n            }\n        }\n    }\n}\n\n// ==== Car.java ====\npublic class Car {\n    private String plate;\n\n    public Car(String plate) {\n        this.plate = plate;\n    }\n\n    public String getPlate() {\n        return this.plate;\n    }\n}\n","hints":["Loop over the indexes, `for (int i = 0; i < spots.length; i++)`, so you know each spot's number: `i + 1`.","Check `spots[i] == null` before calling `getPlate()`: on an empty spot the call would crash. Put `(i + 1)` in parentheses in the printed line, or `+` joins the digits as text."],"tests":[{"name":"Test 1","stdin":"","call":"Car[] spots = new Car[4];\nspots[0] = new Car(\"KLM-204\");\nspots[2] = new Car(\"XT-9981\");\nprintSpots(spots);\n","expect":"Spot 1: KLM-204\nSpot 2: free\nSpot 3: XT-9981\nSpot 4: free","hidden":false},{"name":"Test 2","stdin":"","call":"Car[] spots = new Car[2];\nprintSpots(spots);\n","expect":"Spot 1: free\nSpot 2: free","hidden":true},{"name":"Test 3","stdin":"","call":"Car[] spots = new Car[3];\nspots[0] = new Car(\"AB-12\");\nspots[1] = new Car(\"CD-345\");\nspots[2] = new Car(\"EF-6789\");\nprintSpots(spots);\n","expect":"Spot 1: AB-12\nSpot 2: CD-345\nSpot 3: EF-6789","hidden":true},{"name":"Test 4","stdin":"","call":"Car[] spots = new Car[5];\nspots[4] = new Car(\"ZZ-1\");\nprintSpots(spots);\n","expect":"Spot 1: free\nSpot 2: free\nSpot 3: free\nSpot 4: free\nSpot 5: ZZ-1","hidden":true}],"require":[{"pattern":"(==|!=)\\s*null\\b|\\bnull\\s*(==|!=)","message":"Check each spot with `== null` or `!= null` before calling a method on it."}],"forbid":[]}]}