For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Imagine a program like a road trip. Without any directions, it would just travel in a straight line from start to finish. But what if you need to make a decision, repeat a certain route, or take a detour? For that, you need Control Statements in Java.
These statements are the traffic signals, loops, and forks in the road for your code. Control flow Statements in Java are the fundamental tools that allow you to direct the execution path of your program, making it dynamic and intelligent. This guide will break down the three main types, decision-making, looping, and branching—to give you full control over your code.
Advance your Java programming expertise with our Software Engineering courses and elevate your learning to the next level.
Control statements are used in Java to manage a program's execution flow. Based on specific conditions or criteria, they decide which parts of the code should be run and when. Java offers several control statements.
Here are the eight essential types of control statements in Java:
The if-else control statement allows us to perform different actions based on evaluating a condition. If the condition is true, the code within the if block is executed; otherwise, the code within the else block (if present) is executed. This enables us to control the flow of our program based on specific conditions.
Example:
public class main {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is non-positive.");
}
}
}
In this example, we have an int variable called number initialized with a value of 10.
We use the if-else control statement to check whether the number is greater than 0. If the condition (number > 0) evaluates to true, the code within the if block is executed, which in this case prints "The number is positive." to the console.
If the condition evaluates to false, indicating that number is not greater than 0, the code within the else block is executed, which prints "The number is non-positive." to the console.
When you run this program, it will output "The number is positive." since the value of number is indeed greater than 0.
Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand.
The switch control statement provides a way to execute different blocks of code based on the value of a variable. It offers a cleaner alternative to using multiple if-else statements when comparing against multiple possible values.
Example:
public class main {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day " + day + " is " + dayName + ".");
}
}
In this example, we have an int variable called day initialized with a value of 3. We also declare a String variable called dayName to store the corresponding name of the day.
We use the switch control statement to match the value of day with different cases. Each case represents a specific value that day could take. When a case matches the value of day, the corresponding block of code is executed.
In this example, when day is 3, the code within the case 3: block is executed, which assigns the value "Wednesday" to dayName. The break; statement is used to exit the switch block once the corresponding case is executed.
If none of the cases match the value of day, the code within the default: block is executed. In this example, if day is any value other than 1-7, the value "Invalid day" is assigned to dayName.
Finally, we print the value of day and dayName using the System.out.println() statement.
When you run this program, it will output "Day 3 is Wednesday.", indicating that the value of day is 3 and the corresponding day name is "Wednesday".
Also Read: JDK in Java: Comprehensive Guide to JDK, JRE, and JVM
The for loop is commonly used when we know the number of iterations in advance or want to iterate over a specific range of values. It provides a concise way to control the iteration process with the initialization, condition, and iteration components all in one line.
Example:
public class main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
This example has a for loop that iterates from 1 to 5. The loop consists of three parts: initialization (int i = 1), condition (i <= 5), and iteration (i++).
Inside the loop, we print the value of i using the System.out.println() statement. The loop will execute five times, printing the value of i from 1 to 5.
As long as a particular condition is true, it repeatedly runs a block of code. Each cycle begins with a condition check.
Example:
public class main {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
}
}
In this example, a while loop executes a block of code repeatedly as long as the condition (count <= 5) evaluates to true. Inside the while loop, we print the value of count and then increment it. The loop will iterate five times, printing the value of count from 1 to 5.
The condition is verified after the code block has been executed, similar to the "while" statement. As a result, the code block is always run at least once.
Example:
public class main {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count <= 5);
}
}
This example has a do-while loop, similar to the while loop. The code block is executed first, then the condition (count <= 5) is checked. If the condition is true, the loop continues to iterate. The loop will execute at least once, regardless of whether the condition is true or false. In this case, it will iterate five times, printing the value of count from 1 to 5.
Also Read: Control Statements in Java: Types, Flowcharts, and Code Examples
It is used to end the current iteration of a loop or switch statement and the entire loop or switch early.
Example:
public class main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("Value: " + i);
}
}
}
This example has a for loop that iterates from 1 to 10. Inside the loop, we check if the value of i equals 5. If the condition is true, the break statement is encountered, and the loop is immediately terminated. As a result, the loop will only execute up to the value of 4, and "Value: 5" will not be printed.
It is employed to go directly to the subsequent iteration of a loop while skipping the current iteration.
Example:
public class main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Value: " + i);
}
}
}
This example has a for loop that iterates from 1 to 5. Inside the loop, we check if the value of i is equal to 3. If the condition is true, the continue statement is encountered, and the remaining code in the loop is skipped for that iteration. As a result, when i is 3, the loop continues to the next iteration, and "Value: 3" is not printed. The loop continues for the remaining iterations, printing "Value: 1", "Value: 2", "Value: 4", and "Value: 5".
Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
The return statement allows us to terminate the execution of a method and provide a value back to the caller. It is commonly used to return a result or a specific value from a method for further computations or output.
Example:
public class main {
public static void main(String[] args) {
int result = sum(5, 7);
System.out.println("Sum: " + result);
}
public static int sum(int a, int b) {
int sum = a + b;
return sum;
}
}
In this example, we have a sum method that takes two integers as parameters (a and b). Inside the method, we calculate the sum of the two numbers and store it in the sum variable.
The return statement is used to return the calculated sum from the method back to the caller. In this case, we return the value of sum.
In the main method, we call the sum method and pass the values 5 and 7 as arguments. The returned value from the sum method is assigned to the result variable.
Finally, we print the value of the result, which will be the sum of 5 and 7, resulting in the output: "Sum: 12".
These control statements offer versatility and let you make programs that can effectively manage various conditions. You may manage the execution flow and strengthen the responsiveness and scalability of your programs by employing the right control statements.
Also Read: File Handling in Java: How to Work with Java Files?
Control Statements in Java are the fundamental building blocks of any meaningful program. They are the tools that transform a simple, top-to-bottom script into a dynamic and intelligent application that can make decisions and repeat actions.
Mastering the different Control flow Statements in Java—from if-else and switch to loops and jump statements—is what gives you, the programmer, the power to direct your program's logic. It's an essential skill for writing efficient, powerful, and robust Java code.
To take your skills to the next level, you can check out courses on Java from upGrad.
Control Statements in Java are essential programming constructs that dictate the flow of execution in a program. Instead of running code line-by-line from top to bottom, these statements allow a developer to alter the sequence. You can make decisions, repeat actions, and jump to different parts of your code based on specific conditions. These Control flow Statements in Java are the "brains" of an application, enabling it to respond dynamically to different data and user inputs. Without them, programs would be simple, linear scripts incapable of handling complex logic, making them a foundational topic covered extensively in upGrad's Java programming courses.
Absolutely. Control flow Statements in Java can be broadly classified into three main categories, each serving a distinct purpose in managing the program's execution path:
Understanding these categories is a key first step in mastering Control Statements in Java.
The if statement is the most fundamental of all Control Statements in Java. It is used to evaluate a single Boolean condition (true or false). If the condition evaluates to true, the block of code inside the if statement is executed. If the condition is false, the block is skipped, and the program continues with the next line of code after the if block. This is a core concept in Control flow Statements in Java for executing code conditionally.
Example:
Java
int score = 85;
// This if statement checks if the score is greater than 80.
if (score > 80) {
System.out.println("Congratulations! You passed with a high score.");
// This line only runs because the condition (85 > 80) is true.
}
System.out.println("Program finished.");
The if-else-if ladder is a powerful construct among Control Statements in Java that allows for testing a series of conditions in sequence. It starts with an if statement, followed by any number of else if statements, and concludes with an optional else block. The program checks the conditions from top to bottom. As soon as a condition evaluates to true, its corresponding code block is executed, and the rest of the ladder is skipped. If none of the conditions are true, the final else block is executed. This structure is one of the most common Control flow Statements in Java for handling multiple, mutually exclusive conditions.
Example:
Java
int grade = 78;
if (grade >= 90) {
System.out.println("Excellent! You got an A.");
} else if (grade >= 80) {
System.out.println("Very Good! You got a B.");
} else if (grade >= 70) {
System.out.println("Good. You got a C."); // This block executes as 78 >= 70 is true.
} else if (grade >= 60) {
System.out.println("Fair. You got a D.");
} else {
System.out.println("Unfortunately, you failed.");
}
When you're working with Control Statements in Java, the choice between if-else and switch depends on the condition you are evaluating.
You can use the if-else statement to examine a single condition or a range of complex logical conditions (e.g., age > 18 && hasLicense == true) and run various code blocks depending on whether it is true or false.
On the other hand, the switch statement enables you to choose which of numerous code blocks to run depending on the value of a single variable or expression (like a byte, short, char, int, String, or an enum). It is often cleaner and more efficient than a long if-else-if ladder when you are comparing a single value against multiple constant possibilities. Understanding when to use each is crucial for writing effective Control flow Statements in Java.
A nested if statement is simply an if or if-else statement placed inside another if or else block. This pattern is one of the more complex Control Statements in Java and is used to test for a condition that depends on another condition being true. Essentially, you create a layered decision-making process. The inner if statement is only evaluated if the outer if condition is met. While powerful, it's important to use these Control flow Statements in Java carefully, as excessive nesting (more than 2-3 levels deep) can make code difficult to read and debug, a principle emphasized in upGrad's software development curriculum.
Example:
Java
int age = 25;
boolean hasTicket = true;
// Outer if statement
if (hasTicket) {
System.out.println("Ticket verified.");
// Inner (nested) if statement
if (age >= 18) {
System.out.println("Access granted to the event.");
} else {
System.out.println("Access denied. You must be 18 or older.");
}
} else {
System.out.println("Access denied. Please purchase a ticket.");
}
Choosing the right loop is a common consideration when using Control Statements in Java.
A for loop is typically employed when you need to iterate across a collection or array or when you know the exact number of iterations in advance (e.g., "do this 10 times"). Its structure—initialization, condition, and increment/decrement—is designed for counter-based loops.
On the other hand, a while loop is used when a specified condition must be met and the number of iterations is unknown beforehand. It continues to execute as long as its condition remains true. For example, you might use a while loop to read from a file until you reach the end, or to process user input until the user types "quit." This flexibility makes it an indispensable tool among Control flow Statements in Java.
The do-while loop is a variation of the while loop and an important part of the set of Control Statements in Java. Its defining feature is that it is an exit-controlled loop. This means the condition is checked after the loop's body is executed. Consequently, the code inside a do-while loop is guaranteed to run at least once, regardless of whether the condition is initially true or false.
This contrasts with the while loop, which is an entry-controlled loop. It checks the condition before executing the body, so if the condition is initially false, the loop's body will never run. This key difference makes the do-while loop one of the more specialized Control flow Statements in Java, perfect for situations like menu-driven programs where you need to display the options at least once.
Example:
Java
int count = 5;
// The body of this loop will execute once, printing "Count is: 5"
// Then, the condition (5 < 5) is checked, which is false, and the loop terminates.
do {
System.out.println("Count is: " + count);
count++;
} while (count < 5);
The enhanced for loop, also known as the for-each loop, was introduced in Java 5 to simplify iterating over arrays and collections. It is one of the most convenient Control Statements in Java for this purpose. Instead of requiring you to initialize a counter, define a condition, and manually increment the counter, the for-each loop automatically traverses each element in the collection or array one by one. This makes the code cleaner, more readable, and less prone to errors (like off-by-one errors). While you lose fine-grained control over the index, these Control flow Statements in Java are ideal when you simply need to access each element in a sequence from beginning to end.
Example:
Java
// Traditional for loop
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Simplified using enhanced for loop
System.out.println("--- Using for-each ---");
for (int number : numbers) {
System.out.println(number);
}
10. How does a loop function with the continue statement, a crucial part of Control Statements in Java?
Use the continue command to go to the next iteration of a loop and skip the remaining statements in the current iteration. It enables you to continue executing a loop while avoiding a portion of its code based on a condition. When the continue statement is encountered inside a loop, the program immediately stops executing the current iteration's code and moves to the update statement (in a for loop) or the condition check (in while or do-while loops) for the next iteration. It's a key tool among the jump-based Control flow Statements in Java.
Example:
Java
// This loop will print odd numbers from 1 to 10.
for (int i = 1; i <= 10; i++) {
// If 'i' is even, skip this iteration and continue to the next one.
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
11. What is the role of the 'break' keyword in both switch and loop-based Control flow Statements in Java?
The break keyword is a versatile jump statement and one of the most critical Control Statements in Java. It has two primary uses:
This ability to immediately exit a block makes break one of the most powerful Control flow Statements in Java for handling exit conditions.
Omitting the break statement in a switch case leads to a behavior called fall-through. This is a special feature of these Control Statements in Java. When a case matches and its block is executed, if there is no break at the end, the program will "fall through" and continue executing the code in the next case block, regardless of whether that next case's value matches. Execution continues until a break statement is found or the switch block ends. While this is sometimes used intentionally to handle multiple cases with the same code, it is a very common source of bugs for new programmers learning about Control flow Statements in Java.
Example:
Java
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday"); // Matches here, prints "Tuesday".
// No break, so it falls through!
case 3:
System.out.println("Wednesday"); // Also prints "Wednesday".
break;
default:
System.out.println("Another day");
}
// Output will be:
// Tuesday
// Wednesday
The default case in a switch statement acts as a catch-all block. It is an optional part of these Control Statements in Java that executes if none of the other case values match the expression's value. It is functionally similar to the final else block in an if-else-if ladder. Using a default case is considered good practice for robust Control flow Statements in Java, as it allows you to handle unexpected or invalid values gracefully instead of having the switch statement do nothing.
Example:
Java
char grade = 'F';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Good!");
break;
case 'C':
System.out.println("Passable.");
break;
default:
// This block runs because 'F' does not match 'A', 'B', or 'C'.
System.out.println("Invalid grade or needs improvement.");
break;
}
Yes, you can. The ability to use String objects in switch statements is a relatively modern addition to the Control Statements in Java. This feature was introduced in Java 7. Before Java 7, switch statements were limited to primitive types like int, char, byte, short, and enums. The introduction of String support made many Control flow Statements in Java much cleaner, as developers no longer needed to write cumbersome if-else-if chains to compare strings. The upGrad curriculum ensures that students learn both traditional and modern Java features to write effective code.
Example (requires Java 7 or later):
Java
String browser = "Chrome";
switch (browser) {
case "Chrome":
System.out.println("Starting Chrome browser...");
break;
case "Firefox":
System.out.println("Starting Firefox browser...");
break;
default:
System.out.println("Unsupported browser.");
break;
}
Nested loops are loops placed inside the body of another loop. This structure is a common pattern in Control Statements in Java and is particularly useful for working with two-dimensional data structures, like matrices (2D arrays), or for creating patterns. The outer loop controls the rows, and the inner loop controls the columns. For each single iteration of the outer loop, the inner loop completes its entire sequence of iterations. It's important to be mindful of performance when using these Control flow Statements in Java, as the total number of executions is the product of the outer loop's iterations and the inner loop's iterations.
Example (printing a 3x3 grid):
Java
// Outer loop for rows
for (int i = 1; i <= 3; i++) {
// Inner loop for columns
for (int j = 1; j <= 3; j++) {
System.out.print("(" + i + "," + j + ") ");
}
// Newline after each row is complete
System.out.println();
}
/*
Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
*/
The return statement is a powerful jump statement used to exit from a method. It is one of the most definitive Control Statements in Java because it immediately terminates the current method and returns control to the caller. The return statement can do two things:
It's a fundamental part of all Control flow Statements in Java for managing method execution and data flow.
Example:
Java
public int findFirstNegativeNumber(int[] numbers) {
for (int num : numbers) {
if (num < 0) {
// As soon as a negative number is found, exit the method and return it.
return num;
}
}
// If the loop finishes without finding a negative number, return a default value.
return 0;
}
The ternary operator (? :) is a condensed, inline version of an if-else statement. It is the only conditional operator in Java that takes three operands, making it a unique tool among Control Statements in Java. The structure is condition ? value_if_true : value_if_false. It evaluates the condition; if true, it returns the first value, and if false, it returns the second value. While it makes code shorter, these Control flow Statements in Java should be used for simple assignments and not for complex logic, as they can quickly become unreadable.
Example:
Java
// Using if-else
int score = 75;
String result;
if (score >= 60) {
result = "Pass";
} else {
result = "Fail";
}
// Using the ternary operator for the same logic
String resultTernary = (score >= 60) ? "Pass" : "Fail";
System.out.println(resultTernary); // Prints "Pass"
In most modern Java Virtual Machines (JVMs), the performance difference between a well-written if-else-if ladder and a switch statement is often negligible for a small number of conditions. However, for a larger number of cases, switch can be more performant. This is because the compiler can optimize switch statements using a "jump table" or "lookup table" (tableswitch or lookupswitch in bytecode), which allows it to jump directly to the correct case in O(1) or O(log n) time. An if-else-if ladder, on the other hand, performs a sequence of comparisons, which can be slower (O(n) in the worst case). This optimization is a key reason why switch is a preferred choice among Control Statements in Java for many-condition scenarios, a topic covered in depth during upGrad's advanced Java modules. Still, readability should always be the primary concern when choosing between these Control flow Statements in Java.
Labeled break and continue are advanced forms of jump statements. These Control Statements in Java allow you to specify which loop to break out of or continue in a nested loop scenario. A standard break or continue only affects the innermost loop it is in. By applying a label to an outer loop, you can use break label; or continue label; to transfer control to that specific labeled loop. These specialized Control flow Statements in Java are not used very often because they can make code harder to follow, but they are useful in certain complex algorithms, such as searching within a 2D matrix.
Example (using labeled break to exit all loops):
Java
search: // This is a label for the outer loop
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == 2 && j == 3) {
System.out.println("Element found at (" + i + "," + j + ")");
break search; // Exits the outer loop (labeled 'search')
}
}
}
System.out.println("Search finished.");
Writing clean and efficient code with Control Statements in Java is crucial for software maintainability. Here are some best practices that are highly recommended:
Following these guidelines for Control flow Statements in Java will help you write professional, readable, and robust applications.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free
Author|900 articles published
Recommended Programs