자바에 primtive 타입에서 클래스 타입이 들어오면서 (int->Integer, boolean ->Boolean등)
좋아지는 부분도 있지만, 개발자들이 실수하는 코드도 있다.
특히 자바가 아닌 다른 언어에서는 자동으로 지원하지만, 자바는 되지 않는 것들이 바로 이런 경우일 것이다.
자바에서는 boolean 값에 null을 넣을 수 없다. (type mismatch)
boolean a = null;
하지만 아래 boolean과 Boolean을 동시에 사용하면, Boolean으로 변환(autoboxing)이 된다.
다른 언어에서처럼 null에 대해서는 특별히 처리가 안되는 부분이 있다.
코드
@Test
public void test() {
boolean debug = isDebug();
System.out.println(debug);
}
public Boolean isDebug() {
return null;
}
결과
메소드의 리턴 결과에 Boolean 변수를 null을 리턴하면, NPE가 발생한다.
자바에 익숙치 않은 다른 언어 개발자는 null 을 사용하는 경향이 있는 것은
if 문이 숫자 또는 null 에 대한 처리를 하기 때문인 듯하다.
java language spec에 따르면, if문은 반드시 boolean이나 Boolean 이어야 한다.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.9
14.9. The if
Statement
The if
statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.
The Expression must have type boolean
or Boolean
, or a compile-time error occurs.
'java core' 카테고리의 다른 글
java7 -> java8 전환 with spring 3.2 (1) | 2016.07.21 |
---|---|
Set (유일성 보장) 사용시 객체가 구현해야 할 hashcode() (0) | 2016.06.23 |
List와 Set의 교집합(intersection) 구하기 (0) | 2016.04.12 |
[java] 숫자(int)를 문자열(String)로 변경할 때, comma(,)도 같이 표현하고 싶을 때 (0) | 2016.03.07 |
java8 + centos7 이슈 (0) | 2016.01.05 |