中級 › NullPointerException の原因と直し方 › パターン3
NullPointerException の原因と直し方
nullに対する操作で発生します。
1 public class Main { 2 static String find(int n) { 3 if (n > 0) return "found"; 4 return ____; ^ 5 } 6 public static void main(String[] args) { 7 System.out.println(find(-1).length()); 8 } 9 }
Exception in thread "main" java.lang.NullPointerExceptionexited with code 1
空欄を埋めてビルドを通す
nullを返すメソッドは呼び出し側にnullチェックを強制します。空の値を返すほうが安全です。
次の問題