Break , Continue & Goto in Java
Break in Java
In Java, the break statement is used to exit or “break” out of a loop or a switch statement. It’s commonly used when a certain condition is met, and you want to immediately exit the loop or switch statement, regardless of whether the loop’s condition is still true or not.
Basic Structure
while (condition) {
// Some code…
if (condition_to_exit_loop) {
break; // Exit the loop
}
// More code…
}
Scenario: Write a Java program to search for a specific laptop in a list of laptops. If the brand “Apple” laptop is found, print a message saying “Yes, we want an Apple company laptop” and then exit the loop using a break statement.
Break Statement in Java
public class Main {
public static void main(String[] args) {
String[] laptops = { “Window”, “Samsung”, “Apple”, “Dell”, “Asus” };
for (String laptop : laptops) {
if (laptop.equals(“Apple”)) {
System.out.println(“Yes, we want an ” + laptop + ” company laptop”);
break;
}
}
}
}
Output:
Yes, we want an Apple company laptop
Code Explanation
String[] laptops = { “Window”, “Samsung”, “Apple”, “Dell”, “Asus” };
● This line creates an array named laptops with the data type String that contains five string values: “Window”,
“Samsung”, “Apple”, “Dell”, and “Asus”.
for (String laptop : laptops)
● This line starts a for-each loop that goes through each item in the laptops array. For each iteration, the current
item is stored in the variable laptop.
1. The laptop is “Window”. The condition laptop.equals(“Apple”) is false, so the loop continues to the next item.
2. The laptop is “Samsung”. The condition laptop.equals(“Apple”) is false, so the loop continues to the next item.
3. The laptop is “Apple”. The condition laptop.equals(“Apple”) is true, so the code inside the if statement runs: It
prints “Yes, we want an Apple company laptop”. The break statement stops the loop.
Loop Ends:
The loop stops because of the break statement, and no further items are checked.
if (laptop.equals(“Apple”))
Inside the loop, this line checks if the current laptop is equal to “Apple”. If yes, then it will execute the code under the curly braces {}.
System.out.println(“Yes, we want an ” + laptop + ” company laptop”);
break;
If the current laptop is “Apple”, it prints the message “Yes, we want an Apple company laptop” to the console, and the break statement stops the loop immediately.
Output:
Yes, we want an Apple company laptop
Continue in Java
In Java, the continue keyword is used within loops (such as for, while, do-while, and for-each) to skip the current iteration of the loop and continue with the next iteration. It allows you to skip certain iterations based on a condition without exiting the loop entirely.
Basic Structure
for (/* initialization */; /* condition */; /* update */) {
// code block
if (/* condition to skip current iteration */) {
// Skip the remaining code in the loop for the current iteration
continue;
}
// code block continues if the continue statement is not executed
}
Continue Statement
Scenario: Write a Java program to search for a specific laptop in a list of laptops. If the brand “Apple” laptop is found, print a message saying, “We don’t want an Apple company laptop” and then continue to the next brand using a continue statement.
Continue Statement in Java
public class Program {
public static void main(String[] args) {
String[] laptops = { “Windows”, “Samsung”, “Apple”, “Dell”, “Asus” };
for (String laptop : laptops) {
if (laptop.equals(“Apple”)) {
System.out.println(“We don’t want an ” + laptop + ” company laptop”);
continue;
} else {
System.out.println(“Give me the price of ” + laptop + ” company laptop”);
}
}
}
}
Output: We don’t want an Apple company laptop
Code Explanation
Class Definition: public class Program
Defines a public class named Program. In Java, each program typically starts with a class definition.
Main Method: public static void main(String[] args)
This method is the entry point of the Java program. It’s called automatically when the program runs. String[] args allows command-line arguments to be passed, though they aren’t used in this example.
Array Declaration: String[] laptops = { “Windows”, “Samsung”, “Apple”, “Dell”, “Asus” };
Initializes an array of strings called laptops with values representing different laptop brands.
Enhanced For-Loop: for (String laptop : laptops)
Iterates over each element in the laptops array, assigning the value of each element to the variable laptop in each loop iteration. This is similar to the foreach loop in C#.
Conditional Check: if (laptop.equals(“Apple”))
Checks if the laptop variable is equal to “Apple”. In Java, equals() is used for string comparison instead of == (which compares object references).
Print Statement (If Block): System.out.println(“We don’t want an ” + laptop + ” company laptop”);
If the laptop is “Apple”, this line outputs: “We don’t want an Apple company laptop”.
Continue Statement: continue;
Skips the rest of the loop’s body for the current iteration and moves to the next element in the array.
Else Block:
If the laptop is not “Apple”, the program moves to the else block.
Print Statement (Else Block): System.out.println(“Give me the price of ” + laptop + ” company laptop”);
For laptops other than “Apple”, this line outputs: “Give me the price of [brand] company laptop”.
This structure allows the program to check each laptop brand and output different messages based on whether it matches “Apple”.
Output:
We don’t want an Apple company laptop
The Difference Between Break and Continue
Break | Continue |
---|---|
In the Break statement if the condition is true the code will break and exit | In the continue statement, it will run even after the condition is true for all values in the array |
For Example : Imagine you’re playing a board game and you decide to quit the game in the middle. You stop playing and leave. | For Example: Now imagine you’re playing the same game, but this time, if you don’t like one of your turns, you skip it and move to the next round. |
Goto in Java
In Java, there is no direct equivalent of the goto statement as seen in C#. The use of goto in other languages like C# is generally discouraged due to the potential for creating confusing and hard-to-maintain code. However, you can achieve similar behavior using loops, methods, and control flow statements like break, continue, and labeled blocks.
Using Labeled Blocks in Java
In Java, you can use labeled blocks to mimic the behavior of goto. A labeled block allows you to break out of nested loops or perform controlled jumps within the same method.
Basic Structure
label: {
// code block
// Jumping using break statement
break label;
}
Labeled Block Example in Java
Scenario: Write a Java program to count from 1 to 3 using an if statement. Use a labeled block to jump back to the beginning of the code if the counter is less than 3. When the counter is equal to 3, the code will end.
Labeled Block Implementation in Java
public class Main {
public static void main(String[] args) {
int counter = 0;
start: {
while (true) {
System.out.println(“Current count: ” + counter);
if (counter < 3) {
counter++;
continue start; // Mimics the behavior of goto
} else {
break start; // Exit the labeled block
}
}
}
}
}
Output:
Current count: 0
Current count: 1
Current count: 2
Current count: 3
Code Explanation
int counter = 0;
This line declares an integer variable named counter and initializes it to 0.
start: {
This defines a labeled block named start. The subsequent code inside the block can use break or continue to jump to specific parts within the block.
while (true) {
System.out.println(“Current count: ” + counter);
This loop will run indefinitely until it’s explicitly broken. The System.out.println statement prints the current value of counter to the console.
if (counter < 3) {
counter++;
continue start; // Mimics the behavior of goto
} else {
break start; // Exit the labeled block
}
The if statement checks if the counter is less than 3. If true, it increments the counter by 1 and uses continuestart to jump back to the beginning of the labeled block. If the counter reaches 3, break start is used to exit the block, effectively ending the loop.
Output Explanation
● The output will display the current count from 0 to 3, similar to how the goto statement would function in C#:
Current count: 0
Current count: 1
Current count: 2
Current count: 3
Tasks:
1: Using break in Loops
Scenario:
Write a Java program to iterate over an array of fruit names. If the fruit “Mango” is found, print a message “Mango found, stopping the search” and then exit the loop using the break statement.
Requirements:
1. Create an array of fruit names such as “Apple”, “Banana”, “Mango”, “Orange”.
2. Iterate over the array using a for-each loop.
3. Use a break statement to exit the loop when “Mango” is found.
2: Using continue in Loops
Scenario:
Write a Java program to iterate through a list of integers and print only the even numbers. Use the continue statement to skip odd numbers.
Requirements:
1. Create an array of integers, for example {1, 2, 3, 4, 5, 6, 7, 8, 9}.
2. Iterate over the array using a for loop.
3. Use a continue statement to skip printing the odd numbers.
3: Combining break and continue
Scenario:
Write a Java program that searches through an array of car brands. If the brand is “Tesla”, print “Tesla found, skipping it”. If the brand is “Ford”, print “Found Ford, stopping the search” and use break to exit the loop.
Requirements:
1. Create an array of car brands like “Toyota”, “Tesla”, “Ford”, “Honda”.
2. Iterate over the array using a for-each loop.
3. If the brand is “Tesla”, skip the rest of the current iteration using continue.
4. If the brand is “Ford”, stop the loop using break.
4: Using Labeled Blocks with break and continue
Scenario:
Write a Java program that uses a labeled block to simulate a nested loop and jumps back to the outer block using continue and break.
Requirements:
1. Create two loops: an outer loop (counts from 1 to 3) and an inner loop (counts from 1 to 5).
2. Use a labeled block to control the flow.
3. If the outer loop value is 2, skip the rest of the inner loop and return to the outer loop using continue.
4. If the outer loop value is 3, exit both loops using break.
Course Video
YouTube Reference :
The break
statement terminates the nearest enclosing loop or switch
statement, transferring control to the statement immediately following the terminated statement.
Within loops, break
can be used to exit the loop prematurely when a specific condition is met, effectively stopping further iterations.
The continue
statement skips the current iteration of a loop and proceeds with the next iteration, effectively bypassing the remaining code within the loop for that iteration.
While break
exits the loop entirely, continue
skips the rest of the current iteration and proceeds to the next iteration of the loop.
No, Java reserves the keyword goto
but does not implement it. Instead, Java provides labeled statements with break
and continue
for flow control.
Yes, the tutorial is free for all learners on Iqra Technology Academy.
The tutorial covers Java loop control statements, including break
, continue
, and the reserved goto
keyword.
It is designed for beginners learning Java programming and control flow statements.
The tutorial is concise and can be completed in a few hours, depending on practice time.