Conditional Statements in Java

Soumyadip
The Dev Newbie
2 min readOct 23, 2020

--

Java Conditions

Java supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true.

Use else to specify a block of code to be executed, if the same condition is false.

Use else if to specify a new condition to test, if the first condition is false.

Use switch to specify many alternative blocks of code to be executed.

The If Statement

Use the if statement to specify a block of Java code to be executed if a condition is true. Syntax:

if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}

The else if Statement

Use the else if statement to specify a new condition if the first condition is false. Syntax:

if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
}
else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Ternary Operator

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements. Syntax:

variable = (condition) ? expressionTrue :  expressionFalse;

Switch Statements

Use the switch statement to select one of many code blocks to be executed. Syntax:

switch(expression) {
case x:
// code block when expression equaes to x
break;
case y:
// code block when expression equaes to y
break;
default:
// code block when expression equaes to anything except x or y
}

The break Keyword

When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it’s time for a break. There is no need for more testing.

A break can save a lot of execution time because it “ignores” the execution of all the rest of the code in the switch block.

--

--

Soumyadip
The Dev Newbie

HTML, CSS, Angular and Java amateur at 16 years old. Is also learning UI/UX design as an encore.