For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Control statements in Java manage how a program is executed. It is a fundamental concept that any Java programmer must understand. They are one of the first things taught to a beginner joining any Java course.
In this tutorial, we will delve into control statements in Java with examples to better understand the concept.
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.
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".
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.
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".
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.
In Java, control statements are crucial for how a program is executed. They let you make choices, repeat code snippets, and change the way statements normally follow one another in order.
Java supports conditional statements like if-else and switch to execute code depending on conditions. You can repeat code blocks using looping statements like for, while, and do-while. The internal flow of loops and switch statements can be managed with jump statements like break and continue. You can develop dynamic, interactive programs that effectively handle various circumstances and conditions using these control statements.
You can check out courses on Java from upGrad to learn more.
1. What is the difference between an if-else statement and a switch statement?
You can use the if-else statement to examine a single condition 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 result of an expression.
2. When is a while loop preferable to a for loop?
When you need to iterate across a collection or array or when you know the number of iterations in advance, a for loop is typically employed. On the other hand, a while loop is used when a specified condition must be met and the number of iterations is unknown.
3. How does a loop function with the continue statement?
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.