๐๏ธConditionals
๐ก Conditionals in Java ๐จโ๐ป
Conditionals allow executing different code blocks based on conditions. Here are the main conditionals in Java:
๐ if: Executes code if condition is true
The condition is written within the parentheses after the if keyword. It will be evaluated and must resolve to a Boolean true or false.
If true, the block of code following the opening curly brace will execute. If false, the code block is skipped over.
๐ if-else: Executes one block if condition true, another if false
Within the parentheses after if, we specify the condition we want to check. This will evaluate to true or false. If true, the code block after if will run. If false, else code block runs.
๐ else-if: Checks multiple conditions and executes corresponding blocks
๐ switch: Selects one of many code blocks to execute based on a value
The expression is evaluated once and compared to the values provided in each case. If a match is found, the code block for that case is executed.
The key thing to note is the break keyword at the end of each case block. This prevents code from executing for subsequent cases if a match is found.
A default case can be added as a fallback if no other matches. Without break, it would fall through to other cases below.
๐ Ternary: Shorthand for if-else statement
Rules
Condition must evaluate to a boolean value
Code blocks must be enclosed in {} braces
Break is needed in switch to exit the block
Default case is optional in switch
Java uses boolean variables to evaluate conditions. The boolean values true
and false
are returned when an expression is compared or evaluated. For example:
Of course, we don't normally assign a conditional expression to a boolean. Normally, we just use the short version:
Boolean operators
There aren't that many operators to use in conditional statements and most of them are pretty straightforward:
if - else and between
The if, else statement in Java is pretty simple.
And we can also add an else statement after an if, to do something if the condition is not true
The if-else statements don't have to be in several lines with {}, if can be used in one line, or without the {}, for a single line statement.
Although this method might be useful for making your code shorter by using fewer lines, we strongly recommend for beginners not use this short version of statements and always use the full version with {}. This goes for every statement that can be shortened to a single line (for, while, etc).
The ugly side of if
There is another way to write a one-line if - else statement by using the operator ? :
Again, we strongly recommend for beginners not to use this version of if.
== and equals
The operator ==
works a bit differently on objects than on primitives. When we are using objects and want to check if they are equal, the operator ==
will say if they are the same, if you want to check if they are logically equal, you should use the equals
method on the object. For example:
Last updated