JAVA Unit-2
JAVA Unit-2
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:");
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. .....