Java If … Else

Java If … Else

if and else statements are used in Java to make decisions based on conditions. They allow the program to execute different blocks of code depending on whether a condition is true or false.


Basic Syntax


 


🧠 Example


 


if Statement Only

Sometimes you may only need an if without else:


 


if ... else if ... else

Used when there are multiple conditions to check.


 


 Nested if (if inside another if)


 


 Short If (Ternary Operator)

A shorter way to write an if-else statement.



 


⭐ Full Example


 


📌 Summary

StructureUse Case
ifExecutes only when condition is true
if...elseRuns one of two code blocks
else ifMultiple conditions
Nested ifDecision inside another decision
Ternary ?:Short version of if/else

You may also like...