Master boolean logic, conditional statements, and enumerated types in Java to create more sophisticated program flow and improve code readability.
Boolean logic and enums are fundamental concepts in Java programming that help us express conditions and define fixed sets of values.
Boolean expressions evaluate to either true
or false
. They form the basis for conditional logic in Java.
// Simple boolean expressions boolean isAdult = age >= 18; boolean hasPermission = user.isAdmin() || user.hasAccess("resource");
Compound expressions combine multiple boolean expressions using logical operators:
&&
(AND): true only if both operands are true||
(OR): true if at least one operand is true!
(NOT): inverts the value of its operand// Compound expression with AND and OR boolean canAccessFile = isAuthenticated && (isOwner || hasReadPermission);
In Java, logical operators &&
and ||
use short-circuit evaluation. This means the second operand is only evaluated if necessary.
// Short-circuit to avoid NullPointerException if (user != null && user.hasPermission("admin")) { // Second part only evaluated if user is not null performAdminAction(); }
When comparing objects, use the equals()
method rather than ==
which compares references, not content.
String name1 = "John"; String name2 = new String("John"); // Incorrect: compares references boolean isSameReference = (name1 == name2); // false // Correct: compares content boolean isSameContent = name1.equals(name2); // true
Conditional statements use boolean expressions to control program flow:
// Simple if statement if (temperature > 30) { System.out.println("It's hot outside!"); } // if-else statement if (score >= 70) { System.out.println("Passed"); } else { System.out.println("Failed"); } // Nested conditionals if (temperature > 30) { if (isRaining) { System.out.println("Hot and rainy"); } else { System.out.println("Hot and dry"); } }
Enums provide a way to define a fixed set of constants, making code more readable and type-safe.
// Defining an enum public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } // Using an enum public class Schedule { public void setMeeting(String title, DayOfWeek day) { switch (day) { case MONDAY: System.out.println("Meeting scheduled for Monday: " + title); break; case FRIDAY: System.out.println("Meeting scheduled for Friday: " + title); break; default: System.out.println("Meeting scheduled for " + day + ": " + title); } } }