0% found this document useful (0 votes)
7 views47 pages

JAVA Unit-2

This document provides an overview of control statements in Java, including sequential, conditional, and repetition structures. It details various types of conditional statements such as if, if-else, nested if, and switch statements, as well as unconditional statements like break and return. Additionally, it covers loops in Java, including while, do-while, and for loops, explaining their syntax and usage.

Uploaded by

deoreg1386
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views47 pages

JAVA Unit-2

This document provides an overview of control statements in Java, including sequential, conditional, and repetition structures. It details various types of conditional statements such as if, if-else, nested if, and switch statements, as well as unconditional statements like break and return. Additionally, it covers loops in Java, including while, do-while, and for loops, explaining their syntax and usage.

Uploaded by

deoreg1386
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit-2

Control Statements: Selection statements, iterations and jump statements


Control Statements in Java
• A simple Java program contains a set of statements that generally
contain expressions and end with a semi-colon.
• When we run a Java program, at a time, only one statement is
executed. These statements are called sequential statements.
• The flow of execution takes place from top to bottom.
• There are three main types of flow of execution (control) that occur in
any computer programming. They are:
• Sequential flow
• Conditional or selection
• Repetition or loop
1. Sequential:
Statements execute from top to bottom
one by one.
2. Conditional or selection:
Out of two instructions, only one will be
executed successfully based on the
specified condition.
This is because the condition generates
the result as either true or false.
3. Repetition or loop:
Group of statements repeat whenever the
specified condition is true.
Flow Control Statements in Java
• Flow control statements in Java are those statements that change the
flow of execution and provide better control to the programmer on
the flow of execution in the program.
• These statements are executed randomly and repeatedly.
• Control statements in Java programming are used to write better and
complex programs.
• For example, suppose a situation comes in the program, where we
need to change the order of execution of statements based on
specific conditions or repeat a group of statements until particular
specified conditions are met. This is possible with the help of
conditional control statements or control structures or control
constructs.
• Java supports two kinds of control flow statements:
Conditional statements
Unconditional statements
Conditional Statements in Java
• A program that breaks the sequential flow and jumps to another part of
the code is called branching in java.
• When branching is based on a specific condition, then it is called
conditional branching or conditional statements in Java.
• Java supports the following conditional control flow statement:
if else statement
do while statement
while loop
for loop
for-each loop
switch statement
• The conditional control flow statement uses the boolean expression (either
true or false) for evaluating conditional tests. They evaluate boolean
expressions and execute specific code blocks if conditions are met.
Unconditional Statements in Java

• When the flow of execution jumps to another part of code without


carrying out any conditional test, it is called unconditional statements
or unconditional execution in Java.
• The following unconditional statements are available in Java:
break statement
continue statement
return statement
If Statement
• An if statement in Java is the simplest decision-making
statement that allows to specify alternative paths of
execution in a program. It is also called a conditional
control statement or selection statement in Java.
• The if statement executes a set of statements when a
certain condition is true.
• Syntax
if(Condition)
statement; // statement to be executed if the condition is
true.

or,

if(Condition)
{
statements; // statements to be executed if the condition
is true.
}
Types of Selection Statements in Java
import java.util.Scanner;
public class Test {
• Java language also supports public static void main(String[] args) {
several types of selection // Create an object of Scanner class to take inputs for three subjects.
statements, that are as
Scanner sc = new Scanner(System.in);
follows: System.out.println("Enter your physics marks:");
One way if statements int phyMark = sc.nextInt();
System.out.println("Enter your chemistry marks:");
Two-way if-else statements int chemMark = sc.nextInt();
Nested if statements System.out.println("Enter your maths marks:");

Multi-way if-else statements int mathsMark = sc.nextInt();


float total = phyMark + chemMark + mathsMark;
Switch statements float myPer = total/3;

Conditional expressions System.out.println("Your percentage: " +myPer);


if(myPer >= 85.0) // Here, if the specified condition is true, the
below statement will execute.
System.out.println("Grade A"); } }
Use of Logical Operators in If Statement : &&,||,!
public class Test {
public class Test { public static void main(String[] public class Test {
public static void main(String[] args) args) public static void main(String[] args)
{ { {
int x = 20, y = 40, z = 50; int x = 20, y = 10;
int x = 20, y = 10, z = 40; boolean value;
if((y > x) && (y < z))
System.out.println("y is greater than x but smaller boolean value; if(value = (x == 20) && (y != 20))
than z"); System.out.println(value);
if(value = (x > y) || (y < z))
if((x < y) && (y < z)) System.out.println(value); }
System.out.println("z is greater than x, y");
if(value = (x > y) || (y > z))
if((x < y) && (y < z)) System.out.println(value);
System.out.println("x is smaller than y, z");
if(value = (x < y) || (y < z))
}
} System.out.println(value);
if(value = (x < y) || (y > z))
System.out.println(value);
} }
If else in Java
• An if else in Java is a two-way
conditional statement that decides
the execution path based on whether
the condition is true or false.
• Syntax of If else Statement
if(boolean expression or condition) {
statement1; // statement to be
executed if the condition is true.
}
else {
statement2; // statement to be
executed if the condition is false.
}
Example
System.out.println("Enter the marks of English ");
import java.util.Scanner; int engMarks = sc.nextInt();
public class Test { System.out.println("Enter the marks of Computer ");
int compMarks = sc.nextInt();
public static void main(String[] args)
// Find out the total marks of five subjects.
{ float totalMarks = phyMarks + chemMarks + mathsMarks + engMarks +
compMarks;
// Create an object of Scanner class to take input. System.out.println("Total marks in five subjects: " +totalMarks);
Scanner sc = new Scanner(System.in); float myPer = totalMarks /5;
System.out.println("My percentage: " +myPer);
System.out.println("Enter the marks of Physics ");
int phyMarks = sc.nextInt(); // Checking percentage to find grade using if else statement.
if(myPer >= 80) {
System.out.println("Enter the marks of Chemistry ");
System.out.println("Grade A");
int chemMarks = sc.nextInt(); }

System.out.println("Enter the marks of Maths "); else {


System.out.println("Grade B");
int mathsMarks = sc.nextInt(); }
}
}
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
// Create an object of Scanner class.
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to check Buzz number:");
int num = sc.nextInt();
// Checking buzz number using if else statement.
if((num % 10 == 0) || (num % 7 == 0)) {
System.out.println(num+ " is a Buzz number ");
}
else {
System.out.println(num+ " is not a Buzz number");
}
}
}
Nested If Statements in Java
• If an “if statement” is declared inside another if, or public class Test {
if-else statement, it is called nested if statements public static void main(String[] args) {
in Java. The inner if statement can also have
another if statement. int x = 20, y = 30, z = 10;
if(x == 20) {
• Syntax
// First inner if statement inside outer if statement.
// Outer if statement.
if(y < 50) {
if(condition) { System.out.println("ABC"); }
// Inner if statement defined in outer if else // Second inner if-else statement inside outer if statement.
statement. if(z > 30)
if(condition) System.out.println("DEF");
statement1; } else

// Else part of outer if statement. System.out.println("PQR");


}
else {
// Outer else block.
statement2;
else {
} System.out.println("XYZ"); } } }
If else If Ladder Statements in Java

• The if else if ladder in Java is a multi-way


decision structure that is used to decide
among three or more actions.
• The general syntax for if-else if ladder
statements in Java are as follows:
if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
statement3;
...
else
statement4;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
• Q1: Can we use multiple “else” blocks in an if-else
{ statement?
// Create an object of Scanner class to take the input. • Q2: What happens if no condition in the if-else ladder is
true?
Scanner sc = new Scanner(System.in);
• Q3: Is there any limit to using “else-if” conditions many
System.out.println("Enter your age:"); times?
int age = sc.nextInt(); • Q4: Can we use the “if-else” statement to compare strings?
// Applying if else if ladder statements.
if (age < 18)
System.out.print("Child");
else if ((age >= 18) && (age <= 60))
System.out.print("Adult");
else if (age <= 60)
System.out.print("Senior");
else
System.out.print("Invalid age");
}
}
• Q1: Can we use multiple “else” blocks in an if-else statement?
A: No, an if-else statement can have only one “else” block, which is
executed when all previous conditions are false.
• Q2: What happens if no condition in the if-else ladder is true?
A: In such cases, the code inside the “else” block will execute by default.
• Q3: Is there any limit to using “else-if” conditions many times?
A: There is no specific limit, but many “else-if” conditions can lead to code
complexity and reduced readability.
• Q4: Can we use the “if-else” statement to compare strings?
A: Yes, we can use “if-else” statement to compare strings using the
equals() method or other string comparison techniques in Java.
Loops in Java
• Suppose that we need to display the
• Loops in Java are the processes string “Hello world” a hundred times.
that execute a block of statements
repeatedly until a termination • It would be a tedious and boring task
condition is met. to have to write statement a hundred
times:
• loops to execute the same block of
statements repeatedly. Each • resolve this problem?
execution of the loop is int count = 0;
called iteration in Java.
while (count < 100)
• We can execute the block of
statements any number of times, {
from zero to infinite number, System.out.println("Welcome to
depending on the requirement. Java!");
count++;
}
Loop Control Structure in Java
• a loop in a program consists of two
parts:
Control statement
Body of the loop
• The function of control statement is to
test certain conditions and then
perform the repeated execution of
statements contained in the body of
loop.
• A control structure can be classified
into two types depending on the
position of control statement in the
loop. They are as follows:
Entry-controlled loop
Exit-controlled loop
• Steps to process loops in Java • Types of Loops in Java
• There are four steps to process • There are generally three types of
loops in Java that are as follows: loops in Java that are as follows:
Setting and initialization of a Simple loops
counter.
Nested loops
Execution of statements in the
body of loop. Infinite loops
Evaluate for a specified condition
for the execution of loop.
Incrementing the counter.
Nested Loops in Java
• Like conditional statements, a loop public class Test {
structure can be nested one inside the public static void main(String[] args)
other. Loops placed inside another
loop are called nested loops in Java. {
• Nested loops allow us to loop over for(int x = 1; x <= 10; x++) {
two variables. The outside loop is for(int y = 1; y <= 10; y++) {
called outer loop, and the inside loop
is called inner loop. Each time the System.out.printf( "%4d", x * y);
outer loop iterates, the inner loop }
iterates until its condition is satisfied.
System.out.println();
}
}
}
Infinite Loops in Java

• If a loop repeats forever, it is int n = 1;


called infinite loops in Java. while(n > 0)
It is also known as endless
{
loops because the specified
condition always becomes System.out.println(n);
true and the body of loop is // n never changes.
executed repeatedly, without }
end.
or
while(condition);
Types of Loop (Iteration) Statements in Java
• Java language provides three
types of loop statements for
performing loop operations.
They are:
while loop
do-while loop
for loop
While Loop in Java
• The while loop in Java is the most
fundamental loop statement that
repeats a statement or series of
statements as long as the specified
conditional expression evaluates to
true.
• Syntax of While Loop
Initialization;
while(test condition)
{
// Loop body
Statement(s);
Increment/Decrement;
}
public class WhileLoopEx {
public static void main(String[] args)
public class WhileLoopEx {
{
public static void main(String[] args)
int num = 1;
{
int sum = 0;
int i = 1; // initialization while (num <= 10) {
while(i <= 4) if (num % 2 == 0) {
{ sum += num;
System.out.println("Hello World!"); }

i++; num++;
}
}
System.out.println("Sum of even numbers between
} 1 and 10: " +sum);
} }
}
public class MultiplicationTable {
public class NestedWhileLoopsExample {
public static void main(String[] args)
public static void main(String[] args)
{
{
int row = 1;
// Initialization of outer while loop,
// Outer while loop for rows
int outerLoop = 1;
while (row <= 10)
// Outer while loop
{
while (outerLoop <= 3)
int column = 1;
{
// Initialization of inner while loop
// Inner while loop for columns
int innerLoop = 1;
while (column <= 10)
// Inner while loop
{
while (innerLoop <= 3)
int result = row * column;
{
System.out.print(result + "\t");
System.out.println("Outer loop iteration: " + outerLoop + ", Inner loop
iteration: " + innerLoop); column++;
innerLoop++; }
} // inner while loop ends here. System.out.println(); // Move to the next row after printing all
columns
outerLoop++;
row++;
} // outer while loop ends here.
}
}
}
}
}
Do While Loop • Syntax of Do While Loop
• A do while loop in Java is a variant Initialization;
form of while loop. It is the same do {
as a while loop, except that it
executes the body of the loop first // Loop body;
and then evaluates the loop Statement(s);
continuation condition.
Increment/decrement;
• The do while loop always executes
its body at least once before the }
test evaluates because its test while (test conditional expression);
conditional expression is at the
bottom of the loop. It is especially
useful when we want to execute a
certain block of code at least once,
regardless of whether the loop
condition is initially true or false.
public class Test { public class StarPatternEx {
public static void main(String[] args) public static void main(String[] args)
{ {
int row, column; // Nested Do-While loop to print a pattern
System.out.println("Multiplication Table \n"); int i = 1;
row = 1; // Initialization. // Outer do while statement.
do { do {
column = 1; int j = 1;
do{ // Inner do while statement.
int x = row * column; do {
System.out.printf("%4d", + x); System.out.print("* ");
column = column + 1; j++;
}while(column <= 5); }
System.out.println("\n"); while (j <= i); // Inner do while loop ends here.
row = row + 1; System.out.println();
} while(row <= 5); i++;
} } while (i <= 5); // Outer do while loop ends here.
} }
}
Difference between while loop and do-while loop

• The difference between while loop and do-while loop in Java is as follows:
1. In the case of while loop, the first test condition is verified and then
executes the statements inside the while block.
In the case of do-while loop, the first statements inside do block are
executed and then the test condition is verified.
2. If the test condition is false for the first time, then block of statement
executed zero times.
If the test condition is false for the first time, then the block of statement
executed at least once time.
3. In the while syntax, while statement is at the top. In the do-while syntax,
while statement is at the bottom.
For Loop in Java
• Syntax of For Loop
• The for loop in Java is an for(initialization; test-condition; iteration
entry-controlled loop (increment/decrement)) {
structure that executes a
set of statements a fixed // Loop body
number of times. It is Statement(s); // statements to be
perfect for those scenarios executed.
where we know the exact
number of iterations }
needed to accomplish a Or,
task. for (i = initialValue; i < endValue; i++) {
• The for statement provides // Loop body
a more concise syntax for
creating loops. It executes a Statement(s);
block of statements as long }
as the condition is true.
public class FactorialEx { public class IteratingArray {
public static void main(String[] args) public static void main(String[] args)
{ {
int number = 5; // Create an array of five numbers.
int factorial = 1; int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 1; i <= number; i++) {
factorial *= i; // Iterate over an array and calculate the
} sum
System.out.println("Factorial of " + for (int i = 0; i < numbers.length; i++) {
number + " is: " + factorial); sum += numbers[i];
} }
} System.out.println("Sum of array
elements: " + sum);
}
}
Infinite For loop Example Program
public class Test {
public static void main(String[] args)
{
int i = 1;
int sum = 0;

for(; ;) {
sum = sum + i * i * i;
i++;
if(i >= 5) break; // If the i value exceeds 5,
then come out of this loop.
}
System.out.println("Sum: " +sum);
}
}
public class Test { public class Test {
public static void main(String[] args) public static void main(String[] args)
{ {
int i, j; int x = 1, sum = 0;
for(i = 1, j = 5; i <= 5; i++, j--) for(x = 1; x < 20 && sum < 20; x++)
{
{
sum = sum + x;
System.out.println(i+ "\t" +j);
}
}
System.out.println("Sum: " +sum);
}
}
}
}
Nested For Loops for patterns
public class PatternEx { public class PatternEx { public class PatternEx {
public static void main(String[] args) public static void main(String[] args) { public static void main(String[]
{ args)
System.out.println("Displaying {
System.out.println("Displaying a right alphabet pattern: ");
triangle pattern of numbers: "); int i, j, k = 1;
// Outer for loop. for(i = 1; i <= 5; i += 2)
// Outer for loop.
for(int i = 65; i <= 69; i++) { {
for(int i = 1; i <= 5; i++) for(j = 5; j >= 1; j--)
{ // Inner for loop. {
// Inner for loop. for(int j = 65; j <= i; j++) { if(j > i)
for(int j = 1; j <= i; j++) { char ch = (char)j; System.out.print(" ");
else
System.out.print(j+ " "); System.out.print(ch+ " "); System.out.print(k++ +" ");
} } }
System.out.println(" "); System.out.println();
System.out.println(" ");
} }
} }
}
} } }
}
For Each Loop in Java
• The for each loop in Java (also referred to as • Syntax of Java For Each Loop
enhanced for loop) is an extended feature of for(data_type identifier : expression)
Java language that was introduced with the
J2SE 5.0 release. {
• This feature is specially designed to retrieve // Code block to be executed for each
elements of the array efficiently rather than element.
using array indexes.
}
• Java for-each loop can also be used to
retrieve elements of a collection. A collection
represents a group of elements as integer • data_type represents the data type of
values, strings, or objects. elements in the collection or object used;
• Enhanced for loop repeatedly executes a • Identifier specifies the name of an
group of statements for each element of the iteration variable that receives elements
collection. It can execute as many times as a from a collection, one at a time, from
number of elements in the collection. beginning to end;
• expression is an object of
java.lang.Iterable interface or an array.
// Create an array of three elements. public class SearchTest {
int numarr[] = {10, 20, 30}; public static void main(String[] args)
{
// Applying for loop to iterate over elements. // Creating an array object of 8 elements.
for(int i = 0; i <= 3; i++) int nums[] = { 1, 8, 3, 7, 5, 6, 10, 4 };
{ int val = 10;
if(numarr[i] > 5 && numarr[i] < 40) boolean found = false;
System.out.println("Selected value: " +numarr[i]);
} // Searching for an element value 10 from an array using Java for each
loop.
for(int x : nums) {
// This code is equivalent to the following code:
if(x == val) {
int numarr[] = {10, 20, 30};
found = true;
break;
// Applying for each loop to iterate over elements.
}
for(int i : numarr)
}
{
if(found)
if(i > 5 && i < 40)
System.out.println("Value found!");
System.out.println("Selected value: " +i);
}
}
}
• Advantages of For-Each Loop Over • Limitations of For Each Loop
Traditional For Loop
• In Java, the for each loop is designed
• The syntax of the for-each loop is very for read-only access to elements. If we
simple and concise, resulting in more try to modify it during the iteration,
concise code compared to traditional loops. we may get to runtime exceptions.
• The for-each loop enhances code • The for each loop is not suitable when
readability as compared to the traditional we need to access elements by index.
for loop in Java.
• It may not be suitable in certain
• As there is no explicit use of indices, the situations, such as looping backward
for-each loop helps avoid common errors, or skipping certain elements.
such as “IndexOutOfBoundException”.
• With the for each loop, we can easily
iterate over elements in arrays and
collections without the need to manage
indices explicitly.
• The enhanced for loop makes the code
more concise and easier to understand.
When to Use For Each Loop in Java
• Calculating the sum, average, or other aggregate values of an array of
numbers.
• Searching for specific elements in a collection.
• Printing or displaying elements to the user.
• Copying elements from one collection to another.
• Filtering elements based on certain criteria.
• Use for each loop with custom objects if the collection contains
instances of the custom class.
• Use the enhanced for loop if you need the guarantee order of
elements in the collection, like list.
Switch Statement in Java
• Syntax to Switch Statement
switch(integer expression)
• A switch statement in Java is
{
a conditional control case value-1:
statement (or multi-way // statement sequence
decision statement) that break;
executes one statement from .....
multiple conditions. .....

• It uses the result of an case value-n:


// statement sequence
expression to evaluate which
break;
statements to execute. It is default:
an alternative to if-else-if // default statement sequence
ladder statement. }
statement-x;
public class SwitchTest3 {
public static void main(String[] args)
{
int num = 20;
switch(num) {
// Case statement without break statements.
case 10: System.out.println("Ten");
case 20: System.out.println("Twenty");
case 30: System.out.println("Thirty");
case 40: System.out.println("Forty");
default: System.out.println("Default statement");
}
}
}
case 'C':
public class SwitchStringTest { public class NestedSwitchEx { switch(collegeYear) //
public static void main(String[] args) Inner switch. {
public static void main(String[] args) {
{ case 3:
String gameLevel = "Intermediate"; System.out.println("Java, Python,
// E - ECE, C - CS, I - Information
int level = 0; Technology. Data structure");
switch(gameLevel) { char branch = 'E'; break;
int collegeYear = 3; }
case "Beginner": level = 1; break;
break; case 'I':
switch(branch) {
switch(collegeYear) {
case "Intermediate": level = 2; case 'E': case 3:
break; switch(collegeYear) // Inner System.out.println("EDC, Java,
switch
case "Expert": level = 3; Data structure, Microprocessor");
{
break; case 3: break;
default: level = 0; }
System.out.println("Microcontroller, break;
break; Power Electronics, Analog circuit,
Digital circuit"); default:
} System.out.println("Invalid
break;
System.out.println("Your game level is: " } selection");
+level); break;
break;
} } }}
}
jump Statement in Java
• Java supports three types of • Break Statement
jump statements: break, • A break statement in Java is used
continue, and return. to break a loop or switch
• These statements transfer statement. When a break
control of execution to another statement encounters inside a
part of the program. loop statement, the loop
immediately ends at a specified
condition.
public class BreakExample2 {
public static void main(String[] args)
{
// Outer for loop.
for(int i = 1; i <= 3; i++)
{
// Inner for loop.
for(int j = 0; j <= 3; j++) {
if(i == 2 && j == 2)
break; // Using break statement inside for loop.
System.out.println(i+" "+j);
}
}
}
}
Continue Statement in Java
• When the continue statement
encounters, subsequent
statements in the loop skips (i.e.
not executed) at a specified
condition, and the control of
execution continues with the
next repetition of the loop.
• Continue statement in Java do
not break out of the loop
entirely. It just jumps back to the
beginning of the loop by
skipping the rest of code in the
loop body for the next iteration.
public class ContinueUse {
public static void main(String[] args)
{ • Real-time Use of “Continue”
for(int i = 10; i >= 1; i--) Statement
{ (1) Skipping Odd Numbers:
if(i > 5) (2) Skipping Unwanted Elements in
Collections:
continue; // It will skip the rest
statement and go back in the for
loop.
System.out.println(i + " ");
}
}
}
Labelled Loop in Java public class LabelledLoopEx2 {
• In Java, we can give a label to a loop. When we public static void main(String[] args) {
place a label before any loop, it is called labelled // Outer loop.
loop in Java.
outer: for(int i = 1; i < 3; i++) {
• A label is a valid variable name (or identifier) in
Java that represents the name of the loop to System.out.println("i: " +i);
where the control of execution should jump. // Inner loop.
• Syntax: int j = 1;
labelname: while(j < 3) {
for(initialization; test-condition; incr/decr) { System.out.println("j: " +j);
// code to be executed. int x = i + j;
} if(x > 2)
or, break outer;
labelname: for(initialization; test-condition; j++;
incr/decr) {
} }
// code to be executed.
System.out.println("Jumping out of both labelled
} loops"); } }
Advantages of Labeled Loop in Java
• Labeled loops enhance the level • Labeled Loops vs Unlabeled Loops
of control over loop execution,
making complex scenarios more In comparison to unlabeled loops,
manageable. labeled loops add an extra layer of
• Properly labeled loops can make control and can handle more complex
the code more readable and situations. However, in simple
self-explanatory. scenarios, using labeled loops might
introduce unnecessary complexity.
• Labeled loops enable us to break
out multiple nested loops
simultaneously.

You might also like