Explain Conditional statements in Java with examples.
Conditional statements are mostly used in decision-making scenarios which means these
statements take a decision on the basis of some conditions. The conditional statements are
also referred as branching statements because the program takes a decision based on the
result of the assessed condition.
if statement
if-else statement
if-else-if ladder
nested if statement
Switch Statement
if Statement:
The Java if statement tests the condition. It executes the if block if condition is true. If the
given condition is satisfied it will execute the true block statement only
Example Program:
class IfExample
{
public static void main(String[] args)
{
//defining an 'age' variable
int age=18;
//checking the age
if(age>18)
{
System.out.print("You are eligible to vote");
}
}
}
Output:
21
You are eligible to vote
if-else Statement:
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed. It will execute either true block statement or false block
statements.
Example Program:1
class IfExample
{
public static void main(String[] args)
{
int age=20; //defining an 'age' variable
if(age>18) //checking the age
{
System.out.print("You are eligible to vote");
}
else
{
System.out.println(“You are not eligible to vote”);
}
}
}
Output:
25
You are not eligible to vote
if-else-if ladder Statement:
The if-else-if ladder statement executes one condition from multiple statements. If the first
condition is satisfy it will execute the statement otherwise it will execute the next condition.
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Example Program:
import java.util.Scanner;
class if-else-if ladder
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a percentage");
float per = sc.nextFloat();
if(per>=70)
{
System.out.println("Distinction");
}
else if(per>=60)
{
System.out.println("First Class");
}
else if(per>=50)
{
System.out.println("Second Class");
}
else if(per>=40)
{
System.out.println("Pass");
}
else
{
System.out.println("Failed");
}
}
}
Output:
Enter a percentage:
62
First Class
Nested if statement:
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}
Example program:
public class NestedIfExample2
{
public static void main(String[] args)
{
int age=25; //Creating two variables for age and weight
int weight=48;
if(age>=18) //applying condition on age and weight
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
}
Output:
16
You are not eligible to donate blood
Switch Statement:
The Java switch statement executes one statement from multiple
conditions. It is like if-else-if ladder statement. The switch statement works with byte, short,
int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since
Java 7, you can use strings in the switch statement.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
………
default:
code to be executed if all cases are not matched;
}
Example program:
class WeekDays
{
public static void main(String s[])
{
int day = 2;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
break;
}
}
}
Out put:
Tuesday
Explain about Iteration/ looping statements statements
For Loop:
Iteration statements are used to execute a particular set of instructions repeatedly until a
particular condition is met or for a fixed number of iterations.
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of
the for loop are executed,
• and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false,
the loop terminates.
Example: Display numbers from 1 to 5
class Main
{
public static void main(String[] args)
{
int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println(i);
}
}
}
Output:
1 2 3 4 5
Ex: 2---Display Sum of n Natural Numbers
class NaturalNumbers
{
public static void main(String[] args)
{
int sum = 0;
int n = 1000;
for(int i = 1; i <= n; ++i)
{
sum += i;
}
System.out.println("Sum = " + sum);
}
}
Output:
Sum=500500
While Loop:
The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not
fixed, it is recommended to use the while loop.
Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example: Sum of Positive Numbers Only
import java.util.Scanner;
class WhileLoop
{
public static void main(String[] args)
{
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int number = input.nextInt();
while (number >= 0)
{
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
}
Output:
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
do-while Loop:
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iterations is not fixed and you must have to execute the
loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop,
the do-while check the condition at the end of loop body. The Java do-while loop is
executed at least once because condition is checked after loop body.
Syntax:
Do
{
//code to be executed / loop body
//update statement
}
While (condition);
In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
Example Program:
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}
Output:
10
For-each loop in Java:
The Java for-each loop or enhanced for loop is introduced since J2SE 5.0.
It provides an alternative approach to traverse the array or collection in Java.
It is mainly used to traverse the array or collection elements.
The advantage of the for-each loop is that it eliminates the possibility of bugs and
makes the code more readable.
It is known as the for-each loop because it traverses each element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements in
reverse order.
you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.
For-each is another array traversing technique like for loop, while loop, do-while
loop introduced in Java5.
1. It starts with the keyword for like a normal for-loop.
2. Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a colon,
which is then followed by the array name.
3. In the loop body, you can use the loop variable you created rather than using an
indexed array element.
4. It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList).
Syntax:
for (type var : array)
{
statements using var;
}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
For-each loop Example: Traversing the collection elements
import java.util.*;
class ForEachExample2
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>(); //Creating a list of elements
list.add("Vimal");
list.add("Sonoo");
list.add("Sameena");
for(String s:list) //traversing the list of elements using for-each loop
{
System.out.println(s);
}
}
}
Output:
Vimal n
Sonoo
Sameena
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 50, 80, 95, 99, 49,56,98 };
int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int max = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > max)
{
max = num;
}
}
return max;
}
}
Output:
The highest score is 99
Explain about the jumping Statements/ control statements with example.
Jump Statements in Java
Introduction:
Jump statements are control statements that transfer execution control
from one point to another point in the program. There are two Jump statements that are
provided in the Java programming language:
1. Break statement.
2. Continue statement.
Or
The execution of a Java program is done in sequential order. Looping statements like for,
while, and do-while are used to execute a set of statements repeatedly. If such an
execution were to continue, it would go on forever. This can be prevented by adding
appropriate terminating conditions to the loop or by implementing jump statements. A
jump statement helps transfer the control of a program from one line of the code to
another and skip the ones in between.
1.Break Statement:
In java, the break statement is used to terminate the execution of the
nearest looping statement or switch statement. The break statement is widely used with
the switch statement, for loop, while loop, do-while loop.
Syntax:
break;
When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop. here is an example:
For( )//
{
For( ) For ( )
{ {
break;
break; }
} }
Example Program:
import java.io.*;
class Break
{
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
5
Example: 2
public class Break2
{
public static void main(String args[])
{
int i = 3;
switch(i)
{
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("Other");
}
}
}
Output :
Three
Goto:
The goto keyword is a commonly used jump statement in C/C++. However, Java
uses break statements to perform the same function as goto. Labels can be used to identify
blocks of code in Java. Any valid identifier followed by a semicolon represents a label.
We can break out of a labelled block by mentioning the label name after the break
keyword.
Example: Nested loop
public class Goto
{
public static void main(String[] args)
{
outer: // label for outer loop
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j == 2)
break outer;
System.out.println(" value of j = " + j);
}
} // end of outer loop
} // end of main()
}
Output:
0
1
2
Example:2
class MyClass
{
public static void main( String args[] )
{
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
break label; // exits the loop when it reaches 3
}
System.out.println(i);
}
}
}
Output:
0
1
2
Continue statement:
Continue is a jump statement used when a loop’s current iteration is
to be skipped. It allows the control to temporarily exit the loop and ignore the remaining
statements that follow. After this jump, the control immediately moves with the next
iteration of the same loop.
public class Continue
{
public static void main(String args[])
{
For( )
for (int i = 10; i > 0 ;i--) {
{
if (i%2 == 0) continue;
continue;
System.out.print(i+ " ");
}
}
}
}
Output:
9 7 5 3 1
Return statement:
The return keyword is used to transfer a program’s control from a
method back to the one that called it. Since the control jumps from one part of the
program to another, return is also a jump statement.
public class Return
{
public static int add(int a, int b) // parameter//
{
int sum = a+b;
return sum;
}
public static void main(String[] args)
{
int x = 5, y = 10;
int sum = add(x, y);
System.out.println("Sum of a and b: " + sum);
}
}
Output:
Sum of a and b : 15
Note:
Qns.
What is the difference between the break and continue statement?
A break statement terminates its loop and resumes execution out of it. On the other hand,
a continue statement temporarily exits the loop and resumes with the next iteration.
Qns.
Is goto used in Java?
Unlike C/C++, Java does not use goto as a jump statement, but still considers it a
keyword. This means that it cannot be used as an identifier. The use of goto in Java makes
the code complex and difficult to understand. Hence, the break statement handles the
function of goto in a simpler way.