Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Logical Operators บน String ใน Java

ใน Java **ไม่สามารถใช้ Logical Operators (&&, ||, !) กับ String โดยตรงได้** ต้องเปรียบเทียบด้วย Methods

ตัวอย่างจากต้นฉบับ (ใช้กับ int ไม่ใช่ String)

public class LogicalOperatorsDemo {
    public static void main(String[] args) {
        int a = 45, b = 32, c = 87, d = 1;
        
        // Logical operators กับตัวเลข
        if ((a > b) && (b == c)) {
            d = a + b + c;
            System.out.println("The sum is " + d);
        } else {
            System.out.println("The conditions haven't been fulfilled");
        }
    }
}

Output

The first variable is 45
The second variable is = 32
The third variable is = 87
The conditions haven't been fulfilled

การเปรียบเทียบ String อย่างถูกต้อง

การดำเนินการผิด (Compile Error/Logic Error)ถูกต้อง
Equalsstr1 == str2str1.equals(str2) หรือ Objects.equals(str1, str2)
Not Equalsstr1 != str2!str1.equals(str2)
And (&&)str1 && str2condition1 && condition2 (conditions ต้องเป็น boolean)
Or (||)str1 || str2condition1 || condition2
Not (!)!str1!condition

ตัวอย่าง: Logical Operations กับ String Conditions

public class StringLogicalOps {
    public static void main(String[] args) {
        String username = "admin";
        String password = "secret123";
        String role = "ADMIN";
        
        // AND: ทั้งสองเงื่อนไขต้อง true
        boolean isValidUser = username.equals("admin") && password.equals("secret123");
        System.out.println("Valid user: " + isValidUser); // true
        
        // OR: อย่างน้อยหนึ่งเงื่อนไข true
        boolean isAdminOrModerator = role.equals("ADMIN") || role.equals("MODERATOR");
        System.out.println("Is admin or mod: " + isAdminOrModerator); // true
        
        // NOT: กลับค่า boolean
        boolean isNotGuest = !role.equals("GUEST");
        System.out.println("Not guest: " + isNotGuest); // true
        
        // Complex condition
        boolean hasAccess = (username.equals("admin") || username.equals("root"))
                         && password.length() >= 8
                         && !password.contains(" ");
        System.out.println("Has access: " + hasAccess); // true
        
        // Null-safe with Objects.equals (Java 7+)
        String input = null;
        boolean safeCheck = Objects.equals(input, "test"); // false, ไม่ NullPointerException
        System.out.println("Null safe: " + safeCheck);
    }
}

String Methods ที่คืน Boolean (ใช้ในเงื่อนไข)

Methodคำอธิบาย
equals(Object)เท่ากันทุกตัวอักษร (case-sensitive)
equalsIgnoreCase(String)เท่ากันไม่สนใจ case
startsWith(String)ขึ้นต้นด้วย...
endsWith(String)ลงท้ายด้วย...
contains(CharSequence)ประกอบด้วย...
matches(String regex)Match regex pattern
isEmpty()ความยาว 0 (Java 6+)
isBlank()ว่างหรือ whitespace เท่านั้น (Java 11+)

Pattern: Validate String Input

public boolean isValidEmail(String email) {
    if (email == null || email.isBlank()) return false;
    
    // Simple regex (production ใช้ library)
    String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
    return email.matches(emailRegex);
}

public boolean isStrongPassword(String password) {
    if (password == null || password.length() < 8) return false;
    
    boolean hasUpper = password.chars().anyMatch(Character::isUpperCase);
    boolean hasLower = password.chars().anyMatch(Character::isLowerCase);
    boolean hasDigit = password.chars().anyMatch(Character::isDigit);
    boolean hasSpecial = password.chars().anyMatch(c -> "!@#$%^&*".indexOf(c) >= 0);
    
    return hasUpper && hasLower && hasDigit && hasSpecial; // Logical AND
}

สรุป

  • Logical operators (&&, ||, !) ทำงานกับ **boolean expressions** เท่านั้น
  • String ต้องใช้ methods (equals, contains, matches ฯลฯ) สร้าง boolean conditions
  • ใช้ Objects.equals(a, b) สำหรับ null-safe comparison
  • รวม conditions ด้วย && (AND), || (OR), ! (NOT)