Java Loops Decision
Java Loops Decision
Java Loops Decision
while Loop
In this tutorial, we will learn how to use while and do while loop in Java with
the help of examples.
while (testExpression) {
// body of loop
}
Here,
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
Output
1
2
3
4
5
class Main {
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter a number");
number = input.nextInt();
}
Output
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
In the above program, we have used the Scanner class to take input from the
user. Here, nextInt() takes integer input from the user.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the
total sum is displayed.
Java do...while loop
The do...while loop is similar to while loop. However, the body
of do...while loop is executed once before the test expression is checked. For
example,
do {
// body of loop
} while(textExpression)
Here,
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
Output
1
2
3
4
5
class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
Output 1
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
Enter a number
-8
Sum is 0
Here, the user enters a negative number. The test condition will be false but
the code inside of the loop executes once.
Infinite while loop
If the condition of a loop is always true , the loop runs for infinite times (until
the memory is full). For example,
while (condition) {
// body of loop
}
for loop
while loop
do...while loop
This tutorial focuses on the for loop. You will learn about the other type of
loops in the upcoming tutorials.
Here,
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
}
}
}
Output
Java is fun
Java is fun
Java is fun
Java is fun
Java is fun
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
class Main {
public static void main(String[] args) {
int sum = 0;
int n = 1000;
// for loop
for (int i = 1; i <= n; ++i) {
// body inside for loop
sum += i; // sum = sum + i
}
Output:
Sum = 500500
Here, the value of sum is 0 initially. Then, the for loop is iterated from i = 1 to
1000 . In each iteration, i is added to sum and its value is increased by 1.
When i becomes 1001, the test condition is false and sum will be equal to 0 +
1 + 2 + .... + 1000 .
The above program to add the sum of natural numbers can also be written as
class Main {
public static void main(String[] args) {
int sum = 0;
int n = 1000;
// for loop
for (int i = n; i >= 1; --i) {
// body inside for loop
sum += i; // sum = sum + i
}
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 7, 5, -5};
Output
3
4
5
-5
If we set the test expression in such a way that it never evaluates to false ,
the for loop will run forever. This is called infinite for loop. For example,
int sum = 0;
Here, the test expression , i <= 10 , is never false and Hello is printed
repeatedly until the memory runs out.
2. if...else statement
if (condition) {
// statements
}
Here, condition is a boolean expression. It returns either true or false .
if condition evaluates to true , statements inside the body of if are executed
if condition evaluates to false , statements inside the body of if are skipped
class IfStatement {
public static void main(String[] args) {
Output
number > 0
Here, the condition is checking if number is greater than 0. Since number is
greater than 0, the condition evaluates true .
If we change the variable to a negative integer. Let's say -5.
This is because the value of number is less than 0. Hence, the condition
evaluates to false . And, the body of if block is skipped.
Note: To learn about condition expression, make sure to visit Java Relational
Operators and Java Logical Operators.
class Main {
public static void main(String[] args) {
// create a string variable
String language = "Java";
// if statement
if (language == "Java") {
System.out.println("Best Programming Language");
}
}
}
Output
if (condition) {
// codes in if block
}
else {
// codes in else block
}
Here, the program will do one task (codes inside if block) if the condition
is true and another task (codes inside else block) if the condition is false .
How the if...else statement works?
Worki
ng of Java if-else statements
class Main {
public static void main(String[] args) {
int number = 10;
Output
In the above example, we have a variable named number . Here, the test
expression number > 0 checks if number is greater than 0.
Since the value of the number is 10 , the test expression evaluates to true .
Hence code inside the body of if is executed.
Now, change the value of the number to a negative integer. Let's say -5 .
If we run the program with the new value of number , the output will be:
Here, the value of number is -5 . So the test expression evaluates to false .
Hence code inside the body of else is executed.
Here, if statements are executed from the top towards the bottom. When the
test condition is true , codes inside the body of that if block is executed. And,
program control jumps outside the if...else...if ladder.
If all test expressions are false , codes inside the body of else are executed.
class Main {
public static void main(String[] args) {
int number = 0;
Output
The number is 0.
else {
largest = n3;
}
} else {
else {
largest = n3;
}
}
Output:
switch (expression) {
case value1:
// code to be executed if
// expression is equal to value1
break;
case value2:
// code to be executed if
// expression is equal to value2
break;
...
...
default:
// default statements
}
For example, if the value of the expression is equal to value2 , the code
after case value2: is executed.
If there is no match, the code after default: is executed.
Note: We can do the same functionality using the Java if...else...if ladder.
However, the syntax of the switch statement is cleaner and much easier to
read and write.
class Main {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
Output:
Size: Large
In the above example, we have used the switch statement to find the size.
Here, we have a variable number . The variable is compared with the value of
each case statement.
Since the value matches with case 44, the size variable is assigned with
value Large .
class Main {
public static void main(String[] args) {
int expression = 2;
// matching case
case 2:
System.out.println("Case 2");
case 3:
System.out.println("Case 3");
default:
System.out.println("Default case");
}
}
}
Output
Case 2
Case 3
Default case
import java.util.Scanner;
class Main {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
switch (operator) {
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}
Output 1
Choose an operator: +, -, *, or /: +
Enter first number: 23
Enter second number:
21
23.0+21.0 = 44.0
Output 2
Choose an operator: +, -, *, or /: -
Enter first number: 24
Enter second number:
13
24.0-13.0 = 11.0
Output 3
Choose an operator: +, -, *, or /: *
Enter first number: 12
Enter second number:
6
12.0*6.0 = 72.0
Output 4
Choose an operator: +, -, *, or /: /
Enter first number: 36
Enter second number:
6
36.0/6.0 = 6.0
Output 5
Choose an operator: +, -, *, or /: ?
Enter first number: 12
Enter second number:
23
Invalid operator!
The break statement in Java terminates the loop immediately, and the control
of the program moves to the next statement following the loop.
It is almost always used with decision-making statements (Java if...else
Statement).
Here is the syntax of the break statement in Java:
break;
class Test {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
1
2
3
4
In the above program, we are using the for loop to print the value of i in each
iteration. To know how for loop works, visit the Java for loop. Here, notice the
statement,
if (i == 5) {
break;
}
This means when the value of i is equal to 5, the loop terminates. Hence we
get the output with values less than 5 only.
The program below calculates the sum of numbers entered by the user until
user enters a negative number.
To take input from the user, we have used the Scanner object. To learn more
about Scanner , visit Java Scanner.
import java.util.Scanner;
class UserInputSum {
public static void main(String[] args) {
while (true) {
System.out.print("Enter a number: ");
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
In the above program, the test expression of the while loop is always true .
Here, notice the line,
This means when the user input negative numbers, the while loop is
terminated.
Java break and Nested Loop
In the case of nested loops, the break statement terminates the innermost
loop.
Here, the break statement terminates the innermost while loop, and control
jumps to the outer loop.
We can use the labeled break statement to terminate the outermost loop as
well.
Working of the labeled break statement in
Java
As you can see in the above image, we have used the label identifier to
specify the outer loop. Now, notice how the break statement is used ( break
label; ).
Here, the break statement is terminating the labeled statement (i.e. outer loop).
Then, the control of the program jumps to the statement after the labeled
statement.
Here's another example:
while (testExpression) {
// codes
second:
while (testExpression) {
// codes
while(testExpression) {
// codes
break second;
}
}
// control jumps here
}
In the above example, when the statement break second; is executed,
the while loop labeled as second is terminated. And, the control of the program
moves to the statement after the second while loop.
class LabeledBreak {
public static void main(String[] args) {
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
In the above example, the labeled break statement is used to terminate the
loop labeled as first. That is,
first:
for(int i = 1; i < 5; i++) {...}
Here, if we change the statement break first; to break second; the program will
behave differently. In this case, for loop labeled as second will be terminated.
For example,
class LabeledBreak {
public static void main(String[] args) {
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
i = 3; j = 1
i = 3; j = 2
i = 4; j = 1
i = 4; j = 2
While working with loops, sometimes you might want to skip some statements
or terminate the loop. In such cases, break and continue statements are used.
To learn about the break statement, visit Java break. Here, we will learn about
the continue statement.
Java continue
The continue statement skips the current iteration of a loop
( for , while , do...while , etc).
After the continue statement, the program moves to the end of the loop. And,
test expression is evaluated (update statement is evaluated in case of the for
loop).
Here's the syntax of the continue statement.
continue;
Working
of Java continue Statement
Example 1: Java continue statement
class Main {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
9
10
In the above program, we are using the for loop to print the value of i in each
iteration. To know how for loop works, visit Java for loop. Notice the
statement,
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// if number is negative
// continue statement is executed
if (number <= 0.0) {
continue;
}
sum += number;
}
System.out.println("Sum = " + sum);
input.close();
}
}
Output:
In the above example, we have used the for loop to print the sum of 5 positive
numbers. Notice the line,
Here, when the user enters a negative number, the continue statement is
executed. This skips the current iteration of the loop and takes the program
control to the update expression of the loop.
Note: To take input from the user, we have used the Scanner object. To learn
more, visit Java Scanner.
class Main {
public static void main(String[] args) {
int i = 1, j = 1;
// outer loop
while (i <= 3) {
// inner loop
while(j <= 3) {
if(j == 2) {
j++;
continue;
}
Output
Outer Loop: 1
Inner Loop: 1
Inner Loop: 3
Outer Loop: 2
Outer Loop: 3
In the above example, we have used the nested while loop. Note that we have
used the continue statement inside the inner loop.
if(j == 2) {
j++;
continue:
}
Here, when the value of j is 2, the value of j is increased and
the continue statement is executed.
This skips the iteration of the inner loop. Hence, the text Inner Loop: 2 is
continue label;
Here, the continue statement skips the current iteration of the loop specified
by label .
We can see that the label identifier specifies the outer loop. Notice the use of
the continue inside the inner loop.
Here, the continue statement is skipping the current iteration of the labeled
statement (i.e. outer loop). Then, the program control goes to the next
iteration of the labeled statement.
class Main {
public static void main(String[] args) {
// inner loop
for (int j = 1; j < 5; ++j) {
if (i == 3 || j == 2)
Output:
i = 1; j = 1
i = 2; j = 1
i = 4; j = 1
i = 5; j = 1
In the above example, the labeled continue statement is used to skip the
current iteration of the loop labeled as first .
if (i==3 || j==2)
continue first;
Here, we can see the outermost for loop is labeled as first ,
first:
for (int i = 1; i < 6; ++i) {..}
Hence, the iteration of the outer for loop is skipped if the value of i is 3 or the
value of j is 2.
Note: The use of labeled continue is often discouraged as it makes your code
hard to understand. If you are in a situation where you have to use
labeled continue , refactor your code and try to solve it in a different way to
make it more readable.