java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Java Control Statements and Decision-Making Statements Tutorial for Beginners
Last Updated on: 21st Oct 2025 18:02:43 PM
Welcome to this beginner-friendly tutorial on Control Statements and Decision-Making Statements in Java! Control statements allow you to control the flow of your program, deciding which code runs based on conditions or how many times it runs. Decision-making statements, a key subset, help your program make choices based on conditions.
This tutorial is designed for beginners, with clear explanations and simple, real-world examples. We’ll use code snippets you can run in any Java environment (e.g., Eclipse, IntelliJ, or online compilers like Repl.it). By the end, you’ll understand how to use decision-making statements to make your programs smarter and more interactive. Let’s dive in!
What Are Control Statements?
Control statements determine the order in which your code executes. They’re like traffic signs that guide your program’s flow. Java’s control statements are divided into three categories:
-
Decision-Making Statements (if, if-else, else-if ladder, switch): Choose which code to run based on conditions.
-
Looping Statements (for, while, do-while): Repeat code multiple times (covered in a separate tutorial).
-
Jump Statements (break, continue, return): Alter the flow by skipping or exiting (covered separately).
This tutorial focuses on Decision-Making Statements, which let your program decide what to do based on whether conditions are true or false.
Beginner Tip: Conditions in decision-making statements evaluate to a boolean (true or false), often using relational operators like ==, >, <, etc.
1. Decision-Making Statements
These statements evaluate conditions and execute code based on the result. Java provides four main decision-making constructs:
-
if statement
-
if-else statement
-
else-if ladder
-
switch statement
1.1 The if Statement
The if statement runs a block of code only if a condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
-
condition: A boolean expression (e.g., x > 5).
-
If the condition is false, the code inside the {} is skipped.
Example Code:
public class IfExample {
public static void main(String[] args) {
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote!");
}
System.out.println("Program continues...");
}
}
Output:
You are eligible to vote!
Program continues...
Explanation:
-
The condition age >= 18 is true (since age is 18), so the message is printed.
-
If age were 17, the if block would be skipped.
Real-World Analogy: Like checking if it’s raining before grabbing an umbrella: “If it’s raining, take an umbrella.”
1.2 The if-else Statement
The if-else statement provides an alternative block of code to run when the condition is false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example Code:
public class IfElseExample {
public static void main(String[] args) {
int number = 10;
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
Output:
10 is even.
Explanation:
-
The condition number % 2 == 0 checks if number is divisible by 2 (even).
-
Since 10 is even, the if block runs. If number were 7, the else block would run.
Real-World Analogy: “If it’s sunny, wear sunglasses; else, wear a jacket.”
1.3 The else-if Ladder
The else-if ladder checks multiple conditions in sequence, running the first true block or an optional else block if none are true.
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if all conditions are false
}
Example Code:
import java.util.Scanner;
public class ElseIfExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your score (0-100): ");
int score = scanner.nextInt();
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
scanner.close();
}
}
Sample Run:
Enter your score (0-100): 85
Grade: B
Explanation:
-
The program checks conditions in order, stopping at the first true condition (score >= 80 for 85).
-
If no condition is true, the else block runs.
Real-World Analogy: Like choosing a movie rating: “If score is 90+, it’s awesome; else if 80+, it’s good; else, it’s okay.”
1.4 The switch Statement
The switch statement selects a block of code to execute based on the value of a variable. It’s useful when checking a variable against multiple specific values.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
-
expression: Evaluates to a value (e.g., int, char, String).
-
case: Matches the expression’s value.
-
break: Exits the switch to prevent “fall-through” (running subsequent cases).
-
default: Optional; runs if no case matches.
Example Code:
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a day (1-7): ");
int day = scanner.nextInt();
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day!");
}
scanner.close();
}
}
Sample Run:
Enter a day (1-7): 3
Wednesday
Explanation:
-
The switch checks day against each case. If day is 3, it prints “Wednesday” and break exits the switch.
-
If day is not 1–7, the default block runs.
Real-World Analogy: Like a vending machine: “If you press button 1, get soda; if button 2, get juice; else, show an error.”
Note: Since Java 7, switch also supports String values. Example:
String fruit = "Apple";
switch (fruit) {
case "Apple":
System.out.println("It's an apple!");
break;
case "Banana":
System.out.println("It's a banana!");
break;
default:
System.out.println("Unknown fruit!");
}
2. Combining Decision-Making Statements
You can nest decision-making statements for complex logic. Here’s an example that combines if and switch to determine activity based on age and day.
import java.util.Scanner;
public class CombinedExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter day of week (1-7): ");
int day = scanner.nextInt();
if (age >= 18) {
switch (day) {
case 6:
case 7:
System.out.println("It's the weekend! Go party!");
break;
default:
System.out.println("It's a weekday. Go to work.");
}
} else {
System.out.println("You're a student. Go to school!");
}
scanner.close();
}
}
Sample Run:
Enter your age: 20
Enter day of week (1-7): 6
It's the weekend! Go party!
Explanation:
-
The if checks if age >= 18. If true, the switch checks if it’s a weekend (day 6 or 7).
-
If age < 18, the else block runs.
3. Common Issues and Solutions
-
Problem: Forgetting break in a switch causes “fall-through,” where subsequent cases run.
-
Solution: Always include break unless fall-through is intentional.
-
-
Problem: Invalid condition syntax (e.g., if (x = 5)).
-
Solution: Use == for comparison, not = (which is for assignment).
-
-
Problem: Code block doesn’t run as expected.
-
Solution: Check your condition logic and use System.out.println to debug values.
-
4. Practice Tips
-
Experiment: Try modifying conditions or adding more else-if cases.
-
Test Code: Use an online compiler to run examples.
-
Common Mistake: Don’t confuse = (assignment) with == (equality).
-
Quiz Yourself: What does this print if x = 5?
if (x > 3) {
System.out.println("Big");
} else {
System.out.println("Small");
}
(Answer: “Big”)
Summary
-
Decision-Making Statements:
-
if: Runs code if a condition is true.
-
if-else: Provides an alternative for false conditions.
-
else-if ladder: Checks multiple conditions in sequence.
-
switch: Chooses code based on a variable’s value.
-
-
Key Points: Use break in switch, ensure conditions are boolean, and test your logic.
-
Next Steps: Combine with input/output (e.g., Scanner) or try looping statements next.
You’re now ready to make your Java programs smarter with decision-making! Keep practicing, and happy coding! ![]()
.png)