Skip to main content

Command Palette

Search for a command to run...

5) Conditional Operators in Java

Expressions that enable us further control on our Java programs

Updated
•1 min read•View as Markdown
5) Conditional Operators in Java
A

Product-oriented Software Engineer with a solid understanding of web programming fundamentals and software development methodologies such as agile and scrum.

Conditional operators are used to perform decision-making operations within expressions. Java provides different operators for various conditional checks.

Types of Conditional Operators in Java

Relational (Comparison) Operators

These operators compare two values and return a boolean (true or false).

  • == equal operator. 5 == 5 // true

  • != not equal to. 5 != 3 // true

  • > greater than. 5 > 3 // true

  • < less than. 5 < 10 // true

  • >= greater than or equal to. 5 >= 5 // true

  • <= less than or equal to. 5 <= 8 // true

Logical Operators

Logical operators combine multiple conditions or invert boolean values.

Operator Description Example Result

&& Logical AND (true if both are true). (5 > 3) && (8 > 6) // true

|| Logical OR (true if either is true). (5 > 3) || (6 > 8) // true

! Logical NOT (inverts boolean value). !(5 == 5) // false

Ternary Operator (? :)

The ternary operator is a shorthand for if-else. It takes three operands:

condition ? expression1 : expression2;

  • If the condition is true, expression1 is returned.

  • If the condition is false, expression2 is returned.

int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";

System.out.println(result);  // Output: Adult

Learning Java

Part 6 of 26

In this series, I will break down the task of learning java into smaller actionable steps and work on them topic by topic while trying to provide observability into my learning process.

Up next

6) Arrays In Java

Efficient way of representing a list of items in Java