中級 › 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
空欄を埋めてビルドを通す
参照型フィールドの既定値はnullです。使う前に必ずnewで実体を作ります。
次の問題