자바의 java.lang 패키지에 속한 Boolean 클래스는 parseBoolean()과 valueOf()라는 두 가지 메서드를 제공합니다.
parseBoolean(String s) − 이 메서드는 String 변수를 매개변수로 받아 boolean 값을 반환합니다. 주어진 문자열이 "true"(대소문자 구분 없음)라면 true를 반환하고, 값이 null이거나 "false" 혹은 다른 어떤 값이라도 false를 반환합니다.
valueOf(String s) − 이 메서드는 String 값을 받아 파싱한 뒤, 주어진 값에 따라 Boolean 클래스의 객체를 반환합니다. 생성자 대신 이 메서드를 사용하는 것이 권장됩니다. 주어진 문자열이 "true"이면 true를, 그 외의 경우에는 false를 반환합니다.
예제 코드
import java.util.Scanner;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
boolean result = Boolean.parseBoolean(str);
System.out.println(result);
boolean result2 = Boolean.valueOf(str);
System.out.println(result2);
}
}실행 결과 1
Enter a string value: true true true
실행 결과 2
Enter a string value: false false false
하지만 위 두 메서드 모두 주어진 문자열의 값이 실제로 "true"인지 검증해 주지는 않습니다. 자바에는 문자열이 Boolean 타입에 해당하는지 판별해 주는 전용 메서드가 별도로 존재하지 않기 때문에, if 문이나 정규 표현식을 직접 활용하여 확인해야 합니다.
예제 1: if 문 활용하기
import java.util.Scanner;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
if(str.equalsIgnoreCase("true") || str.equalsIgnoreCase("false")) {
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
}
}실행 결과 1
Enter a string value: true Given string is a boolean type
실행 결과 2
Enter a string value: false Given string is a boolean type
실행 결과 3
Enter a string value: hello Given string is not a boolean type
예제 2: 정규 표현식 활용하기
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if(matcher.matches()) {
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
}
}실행 결과 1
Enter a string value: true Given string is a boolean type
실행 결과 2
Enter a string value: false Given string is a boolean type
실행 결과 3
Enter a string value: hello Given string is not a boolean type
정리하면, 단순히 문자열을 boolean 값으로 변환하는 것은 parseBoolean()이나 valueOf()만으로 충분합니다. 반면, 입력된 문자열이 유효한 Boolean 값인지 검증해야 하는 경우에는 equalsIgnoreCase()를 이용한 조건문이나 Pattern·Matcher를 활용한 정규 표현식 방식을 사용하는 것이 안전합니다.