Code Fix

中級 › NullPointerException の原因と直し方 › パターン4

NullPointerException の原因と直し方

nullに対する操作で発生します。

 1  public class Main {
 2      static class Address { String city = "Tokyo"; }
 3      static class Person { Address address________________; }
                                                     ^
 4      public static void main(String[] args) {
 5          Person p = new Person();
 6          System.out.println(p.address.city);
 7      }
 8  }
Exception in thread "main" java.lang.NullPointerException: Cannot read field "city" because "<local1>.address" is nullexited with code 1

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

NullPointerException の原因と直し方

発生箇所の特定方法と、そもそもnullを持ち回さない設計を扱います。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)