Nearby lessons

19 of 125

Java - if and if-else

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

if and if-else is a core concept of the Java language. This lesson explains if and if-else with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

if and if-else

Example01
JCode Cell
1if (condition) {
2 // runs when condition is true
3} else {
4 // runs when condition is false
5}

if and if-else

Example02
JCode Cell
1class IfDemo {
2 public static void main(String[] args) {
3 int marks = 75;
4 if (marks >= 40) {
5 System.out.println("Pass");
6 } else {
7 System.out.println("Fail");
8 }
9 }
10}
Output
Pass
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1