Objects.isNull(Object obj) : 매개값이 null일 경우 true를 리턴

 

Objects.isnonNull(Object obj) : 매개값이 null이 아닐 경우 true를 리턴

 

< requireNonNull() >

- requireNonNull(T obj) 

: not null → true

: null → NullPointerException

- requireNonNull(T obj, String message)

: not null → true

: null → NullPointerException(message)

- requireNonNull(T obj, Supplier<String>msgSupplier)

: not null → true

: null → NullPointerException(msgSupplier.get())

 

널(null) 여부 조사

package sec04.exam01_objects_YJ;

import java.util.Objects;

public class NullExample {
	public static void main(String[] args) {
		String str1 = "코스모";
		String str2 = null;
		
		System.out.println(Objects.requireNonNull(str1)); //requireNonNull() : true(not null)일 경우, 필드의 값 리턴
		//System.out.println(Objects.requireNonNull(str2)); //NullPointerException 발생
		
		try {
			String name = Objects.requireNonNull(str2);
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}

		try {
			String name = Objects.requireNonNull(str2, "이름이 없습니다.");
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}
		
		try {
			String name = Objects.requireNonNull(str2, ()-> "람다식 이용 이름이 없습니다. 출력");
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
코스모
null
이름이 없습니다.
람다식 이용 이름이 없습니다. 출력

+ Recent posts