Trong bài này, chúng ta sẽ hiểu cách kiểm tra xem một chuỗi là rỗng hay null. Chuỗi là một kiểu dữ liệu chứa một hoặc nhiều ký tự và được đặt trong dấu ngoặc kép (“”).
Dưới đây là một minh chứng về điều tương tự -
Giả sử đầu vào của chúng tôi là -
Input string: null
Đầu ra mong muốn sẽ là -
The string is a null string
Thuật toán
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
Ví dụ 1
Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "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"); } } }
Đầu ra
The string is defined as: null The string is a null string
Ví dụ 2
Ở đây, chúng tôi đóng gói các hoạt động thành các hàm thể hiện lập trình hướng đối tượng.
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); } }
Đầu ra
The string is defined as: null The string is a null string