bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Tutorial
Java•Java Tutorial

Java Logical Operators in Conditions

Logical Operators in Conditions

You can combine or reverse conditions using logical operators . These work together with if , else , and else if to build more complex decisions.

  • && (AND) - all conditions must be true
-(OR) - at least one condition must be true
  • ! (NOT) - reverses a condition (true = false, false = true)

AND ( && )

Use AND ( && ) when both conditions must be true:

a

OR ( || )

Use OR ( || ) when at least one of the conditions can be true:

a

NOT ( ! )

Use NOT ( ! ) to reverse a condition:

a

Real-Life Example

In real programs, logical operators are often used for access control. For example, to get access to a system, there are specific requirements:

You must be logged in, and then you either need to be an admin, or have a high security clearance (level 1 or 2):

Example

boolean isLoggedIn = true;
boolean isAdmin = false;
int securityLevel = 3; // 1 = highest
if (isLoggedIn && (isAdmin || securityLevel <= 2)) {
  System.out.println("Access granted");
} else {
System.out.println("Access denied");
}
// Try changing securityLevel to test different outcomes: // // securityLevel 1 = Access granted // securityLevel 2 = Access granted // securityLevel 3 = Access denied // securityLevel 4 = Access denied // // If isAdmin = true, access is granted.

Previous

Java Nested If

Next

Java Switch

This chapter

Overview
49

Lessons

110m

Read time

1. Java Tutorial2. Java Introduction3. Java Getting Started4. Java Syntax5. Java Statements6. Java Output / Print7. Java Output Numbers8. Java Comments9. Java Variables10. Java Print Variables11. Java Declare Multiple Variables12. Java Identifiers13. Java Constants (final)14. Java Data Types15. Java Numbers16. Java Boolean Data Types17. Java Characters18. Java Data Types Example19. Java Non-Primitive Data Types20. Java var Keyword21. Java Type Casting22. Java Operators23. Java Arithmetic Operators24. Java Assignment Operators25. Java Comparison Operators26. Java Logical Operators27. Java Operator Precedence28. Java Strings29. Java String Concatenation30. Java Numbers and Strings31. Java Special Characters32. Java Math33. Java Booleans34. Java If ... Else35. Java Else36. Java Else If37. Java Short Hand If...Else (Ternary Operator)38. Java Nested If39. Java Logical Operators in Conditions40. Java Switch41. Java While Loop42. Java Do/While Loop43. Java For Loop44. Java Nested Loops45. Java For Each Loop46. Java Break and Continue47. Java Arrays48. Java Arrays Loop49. Java Multi-Dimensional Arrays

On this page

Logical Operators in ConditionsAND ( && )OR ( || )NOT ( ! )Real-Life Example