Java Control Statements Part 1
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
Java’s Selection statements:
These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.
When we need to execute a set of statements based on a condition then we need to use control flow statements. For example, if a number is greater than zero then we want to print “Positive Number” but if it is less than zero then we want to print “Negative Number”. In this case we have two print statements in the program, but only one print statement executes at a time based on the input value. We will see how to write such type of conditions in the java program using control statements.
In this tutorial, we will see four types of control statements that you can use in java programs based on the requirement: In this tutorial we will cover following conditional statements:
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
If statement
If statement consists a condition, followed by statement or a set of statements as shown below:
if(condition){
Statement(s);
}
The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.
Example of if statement
public class IfStatementExample {
public static void main(String args[]){
int num=70;
if( num < 100 ){
/* This println statement will only execute,
* if the above condition is true
*/
System.out.println("number is less than 100");
}
}
}
Output:
number is less than 100
Nested if statement in Java
When there is an if statement inside another if statement then it is called the nested if statement.
The structure of nested if looks like this:
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the conditions( condition_1 and condition_2) are true.
Example of Nested if statement
public class NestedIfExample {
public static void main(String args[]){
int num=70;
if( num < 100 ){
System.out.println("number is less than 100");
if(num > 50){
System.out.println("number is greater than 50");
}
}
}
}
Output:
number is less than 100
number is greater than 50
This is how an if-else statement looks:
if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if the condition is false.
Example of if-else statement
public class IfElseExample {
public static void main(String args[]){
int num=120;
if( num < 50 ){
System.out.println("num is less than 50");
}
else {
System.out.println("num is greater than or equal 50");
}
}
}
Output:
num is greater than or equal 50
if-else-if statement is used when we need to check multiple conditions. In this statement we have only one “if” and one “else”, however we can have multiple “else if”. It is also known as if else if ladder. This is how it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as soon as the condition is met, the corresponding set of statements get executed, rest gets ignored. If none of the condition is met then the statements inside “else” gets executed.
Example of if-else-if
public class IfElseIfExample {
public static void main(String args[]){
int num=1234;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");
}
}
}
Output:
Its a four digit number
Here we will write two java programs to find the largest among three numbers. 1) Using if-else..if 2) Using nested If
public class JavaExample{
public static void main(String[] args) {
int num1 = 10, num2 = 20, num3 = 7;
if( num1 >= num2 && num1 >= num3)
System.out.println(num1+" is the largest Number");
else if (num2 >= num1 && num2 >= num3)
System.out.println(num2+" is the largest Number");
else
System.out.println(num3+" is the largest Number");
}
}
Output:
20 is the largest Number
public class JavaExample{
public static void main(String[] args) {
int num1 = 10, num2 = 20, num3 = 7;
if(num1 >= num2) {
if(num1 >= num3)
/* This will only execute if conditions given in both
* the if blocks are true, which means num1 is greater
* than num2 and num3
*/
System.out.println(num1+" is the largest Number");
else
/* This will only execute if the condition in outer if
* is true and condition in inner if is false. which
* means num1 is grater than num2 but less than num3.
* which means num3 is the largest
*/
System.out.println(num3+" is the largest Number");
}
else {
if(num2 >= num3)
/* This will execute if the condition in outer if is false
* and inner if is true which means num3 is greater than num1
* but num2 is greater than num3. That means num2 is largest
*/
System.out.println(num2+" is the largest Number");
else
/* This will execute if the condition in outer if is false
* and inner if is false which means num3 is greater than num1
* and num2. That means num3 is largest
*/
System.out.println(num3+" is the largest Number");
}
}
}
Output:
20 is the largest Number
In this we will write two java programs, first java programs checks whether the specified number is positive or negative. The second program takes the input number (entered by user) and checks whether it is positive or negative and displays the result.
→ If a number is greater than zero then it is a positive number
→ If a number is less than zero then it is a negative number
→ If a number is equal to zero then it is neither negative nor positive.
Lets write this logic in a Java Program.
In this program we have specified the value of number during declaration and the program checks whether the specified number is positive or negative. To understand this program you should have the basic knowledge of if-else-if statement in Core Java Programming.
public class Demo
{
public static void main(String[] args)
{
int number=109;
if(number > 0)
{
System.out.println(number+" is a positive number");
}
else if(number < 0)
{
System.out.println(number+" is a negative number");
}
else
{
System.out.println(number+" is neither positive nor negative");
}
}
}
Output:
109 is a positive number
Here we are using Scanner to read the number entered by user and then the program checks and displays the result.
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
number = scan.nextInt();
scan.close();
if(number > 0)
{
System.out.println(number+" is positive number");
}
else if(number < 0)
{
System.out.println(number+" is negative number");
}
else
{
System.out.println(number+" is neither positive nor negative");
}
}
}
Output:
Enter the number you want to check:-12
-12 is negative number
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");
//The input provided by user is stored in num
Scanner input = new Scanner(System.in);
num = input.nextInt();
/* If number is divisible by 2 then it's an even number
* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Output 1:
Enter an Integer number:
78
Entered number is even
Output 2:
Enter an Integer number:
77
Entered number is odd
1.1. Switch Case statement in Java with example
Switch case statement is used when we have number of options (or choices) and we may need to perform a different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression){case constant://Java code;case constant://Java code;default://Java code;}
Switch Case statement is mostly used with break statement even though it is optional. We will first see an example without break statement and then we will discuss switch case with break
A Simple Switch Case Example
public class SwitchCaseExample1 {public static void main(String args[]){int num=2;switch(num+2){case 1:System.out.println("Case1: Value is: "+num);case 2:System.out.println("Case2: Value is: "+num);case 3:System.out.println("Case3: Value is: "+num);default:System.out.println("Default: Value is: "+num);}}}
Output:
Default: Value is: 2
Explanation: In switch I gave an expression, you can give variable also. I gave num+2, where num value is 2 and after addition the expression resulted 4. Since there is no case defined with value 4 the default case got executed. This is why we should use default in switch case, so that if there is no catch that matches the condition, the default block gets executed.
Switch Case Flow Diagram
First the variable, value or expression which is provided in the switch parenthesis is evaluated and then based on the result, the corresponding case block is executed that matches the result.
Break statement in Switch Case
Break statement is optional in switch case but you would use it almost every time you deal with switch case. Before we discuss about break statement, Let’s have a look at the example below where I am not using the break statement:
public class SwitchCaseExample2 {public static void main(String args[]){int i=2;switch(i){case 1:System.out.println("Case1 ");case 2:System.out.println("Case2 ");case 3:System.out.println("Case3 ");case 4:System.out.println("Case4 ");default:System.out.println("Default ");}}}
Output:
Case2Case3Case4Default
In the above program, we have passed integer value 2 to the switch, so the control switched to the case 2, however we don’t have break statement after the case 2 that caused the flow to pass to the subsequent cases till the end. The solution to this problem is break statement
Break statements are used when you want your program-flow to come out of the switch body. Whenever a break statement is encountered in the switch body, the execution flow would directly come out of the switch, ignoring rest of the cases
Let’s take the same example but this time with break statement.
Example with break statement
public class SwitchCaseExample2 {public static void main(String args[]){int i=2;switch(i){case 1:System.out.println("Case1 ");break;case 2:System.out.println("Case2 ");break;case 3:System.out.println("Case3 ");break;case 4:System.out.println("Case4 ");break;default:System.out.println("Default ");}}}Output:
Case2Now you can see that only case 2 had been executed, rest of the cases were ignored.
Why didn’t I use break statement after default?
The control would itself come out of the switch after default so I didn’t use it, however if you still want to use the break after default then you can use it, there is no harm in doing that.Few points about Switch Case
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order based on the requirement.
2) You can also use characters in switch case. for example –
public class SwitchCaseExample2 {public static void main(String args[]){char ch='b';switch(ch){case 'd':System.out.println("Case1 ");break;case 'b':System.out.println("Case2 ");break;case 'x':System.out.println("Case3 ");break;case 'y':System.out.println("Case4 ");break;default:System.out.println("Default ");}}}
3) The expression given inside switch should result in a constant value otherwise it would not be valid.
For example:Valid expressions for switch:
switch(1+2+23)switch(1*2+3%4)Invalid switch expressions:
switch(ab+cd)switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.
Java Program to check Vowel or Consonant using Switch Case
The alphabets A, E, I, O and U (smallcase and uppercase) are known as Vowels and rest of the alphabets are known as consonants. Here we will write a java program that checks whether the input character is vowel or Consonant using Switch Case in Java.
Example: Program to check Vowel or Consonant using Switch Case
In this program we are not using break statement with cases intentionally, so that if user enters any vowel, the program continues to execute all the subsequent cases until
Case 'U'
is reached and thats where we are setting up the value of a boolean variable to true. This way we can identify that the alphabet entered by user is vowel or not.import java.util.Scanner;class JavaExample{public static void main(String[ ] arg){boolean isVowel=false;;Scanner scanner=new Scanner(System.in);System.out.println("Enter a character : ");char ch=scanner.next().charAt(0);scanner.close();switch(ch){case 'a' :case 'e' :case 'i' :case 'o' :case 'u' :case 'A' :case 'E' :case 'I' :case 'O' :case 'U' : isVowel = true;}if(isVowel == true) {System.out.println(ch+" is a Vowel");}else {if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))System.out.println(ch+" is a Consonant");elseSystem.out.println("Input is not an alphabet");}}}Output 1:
Enter a character :AA is a VowelOutput 2:
Enter a character :PP is a ConsonantOutput 3:
Enter a character :9Input is not an alphabet
Java Program to Make a Calculator using Switch Case
In this Program we are making a simple calculator that performs addition, subtraction, multiplication and division based on the user input. The program takes the value of both the numbers (entered by user) and then user is asked to enter the operation (+, -, * and /), based on the input program performs the selected operation on the entered numbers using switch case.
Example: Program to make a calculator using switch case in Java
import java.util.Scanner;public class JavaExample {public static void main(String[] args) {double num1, num2;Scanner scanner = new Scanner(System.in);System.out.print("Enter first number:");/* We are using data type double so that user* can enter integer as well as floating point* value*/num1 = scanner.nextDouble();System.out.print("Enter second number:");num2 = scanner.nextDouble();System.out.print("Enter an operator (+, -, *, /): ");char operator = scanner.next().charAt(0);scanner.close();double output;switch(operator){case '+':output = num1 + num2;break;case '-':output = num1 - num2;break;case '*':output = num1 * num2;break;case '/':output = num1 / num2;break;/* If user enters any other operator or char apart from* +, -, * and /, then display an error message to user**/default:System.out.printf("You have entered wrong operator");return;}System.out.println(num1+" "+operator+" "+num2+": "+output);}}
Output:
Enter first number:40Enter second number:4Enter an operator (+, -, *, /): /40.0 / 4.0: 10.01.1. For loop in Java with example
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java we have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use “for loop” in Java.
Syntax of for loop:
for(initialization; condition ; increment/decrement){statement(s);}
Flow of Execution of the for Loop
As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program.
First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
Example of Simple For loop
class ForLoopExample {public static void main(String args[]){for(int i=10; i>1; i--){System.out.println("The value of i is: "+i);}}}
The output of this program is:
The value of i is: 10The value of i is: 9The value of i is: 8The value of i is: 7The value of i is: 6The value of i is: 5The value of i is: 4The value of i is: 3The value of i is: 2
In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operationInfinite for loop
The importance of Boolean expression and increment/decrement operation co-ordination:
class ForLoopExample2 {public static void main(String args[]){for(int i=1; i>=1; i++){System.out.println("The value of i is: "+i);}}}This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the Boolean expression: i>1) so it would never return false. This would eventually lead to the infinite loop condition. Thus it is important to see the co-ordination between Boolean expression and increment/decrement operation to determine whether the loop would terminate at some point of time or not.
Here is another example of infinite for loop:
// infinite loopfor ( ; ; ) {// statement(s)}
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 {public static void main(String args[]){int arr[]={2,11,45,9};//i starts with 0 as array index starts with 0 toofor(int i=0; i<arr.length; i++){System.out.println(arr[i]);}}}Output:
211459
Enhanced For loop
Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.
Let’s take the same example that we have written above and rewrite it using enhanced for loop.
class ForLoopExample3 {public static void main(String args[]){int arr[]={2,11,45,9};for (int num : arr) {System.out.println(num);}}}
Output:
211459Note: In the above example, I have declared the num as int in the enhanced for loop. This will change depending on the data type of array. For example, the enhanced for loop for string type would look like this:
String arr[]={"hi","hello","bye"};for (String str : arr) {System.out.println(str);}
Java Program to find Sum of Natural Numbers
The positive integers 1, 2, 3, 4 etc. are known as natural numbers. Here we will see three programs to calculate and display the sum of natural numbers.
public class Demo {
public static void main(String[] args) {
int num = 10, count = 1, total = 0;
while(count <= num)
{
total = total + count;
count++;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55
public class Demo {
public static void main(String[] args) {
int num = 10, count, total = 0;
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num, count, total = 0;
System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
total = total + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+total);
}
}
Output:
Enter the value of n:
20
Sum of first 20 natural numbers is: 210
We will write three java programs to find factorial of a number. 1) using for loop 2) using while loop 3) finding factorial of a number entered by user. Before going through the program, lets understand what is factorial: Factorial of a number n is denoted as n!
and the value of n!
is: 1 * 2 * 3 * … (n-1) * n
public class JavaExample {
public static void main(String[] args) {
//We will find the factorial of this number
int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:
Factorial of 5 is: 120
The Fibonacci sequence is a series of numbers where a number is the sum of previous two numbers. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Here we will write three programs to print fibonacci series 1) using for loop 2) using while loop 3) based on the number entered by user
public class JavaExample {
public static void main(String[] args) {
int count = 7, num1 = 0, num2 = 1;
System.out.print("Fibonacci Series of "+count+" numbers:");
for (int i = 1; i <= count; ++i)
{
System.out.print(num1+" ");
/* On each iteration, we are assigning second number
* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}
Output:
Fibonacci Series of 7 numbers:0 1 1 2 3 5 8