이 기사에서는 문자열이 비어 있는지 또는 null인지 확인하는 방법을 이해합니다. String은 하나 이상의 문자를 포함하고 큰따옴표(" ")로 묶인 데이터 유형입니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Input string: null
원하는 출력은 -
The string is a null string
알고리즘
Step 1 - START Step 2 - Declare a string namely input_string. Step 3 - Define the values. Step 4 - Using an if-loop, compute input_string == null. If true, the string is null, else the string is not null. Step 5 - Display the result Step 6 - Stop
예시 1
여기에서 모든 작업을 'main' 기능 아래에 묶습니다.
public class Demo {
public static void main(String[] args) {
String input_string = null;
System.out.println("The string is defined as: " +input_string);
if (input_string == null) {
System.out.println("\nThe string is a null string");
}
else if(input_string.isEmpty()){
System.out.println("\nThe string is an empty string");
} else {
System.out.println("\nThe string is neither empty nor null string");
}
}
} 출력
The string is defined as: null The string is a null string
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
public class Demo {
static void isNullEmpty(String input_string) {
if (input_string == null) {
System.out.println("\nThe string is a null string");
}
else if(input_string.isEmpty()){
System.out.println("\nThe string is an empty string");
} else {
System.out.println("\nThe string is neither empty nor null string");
}
}
public static void main(String[] args) {
String input_string = null;
System.out.println("The string is defined as: " +input_string);
isNullEmpty(input_string);
}
} 출력
The string is defined as: null The string is a null string