OOPs With Java Notes - Chapter-3
OOPs With Java Notes - Chapter-3
Chapter-3
In Java, decision-making is done using control flow statements, which allow you to
conditionally execute code or repeat actions. Java uses decision-making to control code flow.
Programs often need different actions based on conditions.
Java provides statements to handle these Control Flow Statement
scenarios. These statements let you branch If Statement
code execution. This allows for dynamic
If-else Statement
program behaviour. Control flow is essential
If-else Ladder
for creating robust applications.
Nested If-else Statement
Switch
Java control flow manages the order code
Looping Statement
runs. It lets programs make decisions and
For Loop
repeat actions. Control flow statements like 'if'
While Loop
and 'else' choose code blocks. Loops like 'for'
Do While loop
and 'while' repeat code. These tools give
programs flexibility and power. Enhanced For each Loop
Jumping Statement
Break
Control Flow
Con nue
Return
Control flow statements in programming are essential
for managing the execution of code based on specific conditions.
These statements help determine the sequence in which different parts of a program run,
allowing for decision-making, looping, and branching. In Java, several control flow statements
are available, such as if-else, switch, for, while, and do-while, to efficiently manage the workflow
of your application.
Types of Control Flow Statements
o Simple if statement
o if-else statement
o if-else ladder statement
o nested if-else statement
o switch statement
Object Oriented Programming With JAVA
Control
Flow
Jumping
Branching
Break Continue
if
Looping if-else
for
if-else
while ladder
do while switch
1) Simple if statement - In Java, the "if" statement functions similarly to those in many
other programming languages. It allows you to execute a specific block of code when a
predefined condition is satisfied. Here's how the structure of an "if" statement in Java
appears:
Syntax:
if (condition) {
// execute this code
}
Example:
public class MyProg {
public static void main(String[] args) {
int number = 100;
if (number > 0) {
System.out.println("The number is positive.");
}
}
}
Object Oriented Programming With JAVA
Output:
2) if-else statement - The if-else statement provides two potential execution paths in
programming. When the specified condition is true, the code within the "if" block is
executed. If the condition is false, the "else" block runs instead.
Syntax:
if (condition) {
// execute condition is true
} else {
// execute this code if false
}
Example:
public class MyProg {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("Positive Number");
} else {
System.out.println("Negative Number");
}
}
}
Output:
Example:
import java.util.Scanner;
public class MyProg {
public static void main(String[] args) {
int marks;
System.out.print(“Enter the marks”);
Scanner c=new Scanner(System.in);
marks=c.nextInt();
if (marks >= 80) {
System.out.println("Grade: A");
} else if (marks >= 65) {
System.out.println("Grade: B");
} else if (marks >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
}
}
Output:
Object Oriented Programming With JAVA
Syntax:
if (condition1) {
// Executes if condition1 is true
if (condition2) {
// Executes if condition1 and condition2 both is true
}
}
else {
if (condition3) {
// Executes if condition1 false and condition3 is true
}
// Executes if all conditions are false
}
Example:
public class Main {
Object Oriented Programming With JAVA
public static void main(String[] args) {
int age = 20;
int weight = 50;
if (age >= 18) {
if (weight > 50) {
System.out.println("You are eligible to donate blood.");
} else {
System.out.println("Your weight is less than 50 kg.");
}
} else {
System.out.println("You must be at least 18 years old.");
}
}}
Output:
5) switch Statement- The switch statement in Java is a powerful control flow mechanism
designed for checking multiple conditions against specific fixed values. It offers an efficient
alternative to numerous if-else if conditions, enhancing both code readability and
performance.
Syntax:
switch(expression) {
case value1:
// Code to execute if expression is equal to value1
Object Oriented Programming With JAVA
break;
case value2:
// Code to execute if expression is equal to value2
break;
default:
// Code to execute if no cases match
}
Example:
public class MyProg {
public static void main(String[] args) {
int day = 5;
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;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid choice");
}
}
}
Output:
Since Java 14, you can use switch expressions with yield and arrow syntax.
public class MyProg {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
Object Oriented Programming With JAVA
case 3 -> System.out.println("Wednesday");
case 4 -> System.out.println("Thursday");
case 5 -> System.out.println("Friday");
case 6 -> System.out.println("Saturday");
default -> System.out.println("Sunday");
}
}
}
Output:
Looping Statements
Java loops are essential tools that allow developers to execute a block of code
repeatedly until a specified condition is fulfilled. These loops are powerful constructs in Java
programming, enabling the efficient handling of repetitive tasks, thereby enhancing code
organization and readability. By automating repetitive operations, loops not only reduce errors
but also make your code more concise.
we will explore the different types of loops in Java and example to illustrate how to utilize them
effectively. Java offers three primary types of loops:
o for loop
o while loop
o do-while loop
o Enhanced for each loop
for loop
The for loop is an essential tool in programming when the number of iterations is
predetermined. Ideal for instances when you know exactly how many times you want a task or
sequence to repeat, the for loop is structured with three main components: initialization,
condition, and increment/decrement. This construct is perfect for iterating over arrays,
collections, or specific ranges of numbers, providing an efficient way to avoid redundant code.
By using a for loop, you not only enhance code readability but also ensure your code remains
compact and maintainable. Embrace the for loop for more streamlined coding and superior
organization.
Initialization -setting up the starting point
Condition -the condition that must be true for the loop to continue
increment/decrement -how the loop variable changes after each iteration
Syntax:
for (initialization; condition; update) {
// Code to be executed
Object Oriented Programming With JAVA
}
Example:
while loop
The while loop is ideal in programming when the number of iterations cannot be
predetermined. This loop continues to execute as long as a specified condition remains true.
It's perfect for scenarios where you are unsure how many times the loop should run but have
a condition that dictates its continuation.
A while loop remains active as long as a specified condition remains true, making it
ideal for scenarios such as waiting for user input or continuously processing data until a
particular criterion is satisfied. This type of loop is perfect for executing repetitive tasks when
the exact number of iterations is unknown, adding dynamism and flexibility to your program.
Syntax:
Initialization;
while(condition) {
// Code to execute
Iteration;
Object Oriented Programming With JAVA
}
Example:
public class MyProg {
public static void main (String [] args) {
int i = 1;
while (i <= 3) {
System.out.println("Iteration: " + i);
i++;
}
}
}
Output:
do-while loop
The do-while loop is a fundamental programming construct similar to the while loop,
with one key difference: it ensures the loop's body executes at least once before evaluating
the condition. As an exit-controlled loop, the do-while loop checks its condition at the end,
after the loop's body has run. This guarantees that the loop's actions will occur at least once,
even if the condition evaluates as false during the initial iteration.
Syntax:
Initialization;
do {
// Code to execute
Iteration;
Object Oriented Programming With JAVA
} while(condition);
Example:
public class MyProg {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while(i <= 3);
}
}
Output:
To use a for-each loop, you need to specify a temporary variable to hold the current
element's value, followed by a colon and the name of the array or collection. Unlike standard
for loops, there's no need to define a counter, as the for-each loop automatically manages the
iteration over the elements in the array or collection.
During each iteration, the current element's value is assigned to the temporary variable, which
can then be used within the loop. To ensure compatibility, the temporary variable must match
the data type of the elements in the array or collection.
Syntax:
for(dataType variable : collection) {
// Code to execute
}
Object Oriented Programming With JAVA
Example:
public class MyProg {
public static void main(String[] args) {
int[] numbers = {70, 20, 30, 90, 50};
for(int num : numbers) {
System.out.println(num);
}
}
}
Output:
break statement
In Java programming, the break statement is a powerful tool for immediately exiting a
loop or switch statement. When the break command is encountered, the program halts the
execution of the nearest enclosing loop or switch block and proceeds directly to the next
statement following it. This functionality allows for efficient control over the flow of your code,
ensuring that operations cease as soon as specific conditions are met.
continue statement
In Java programming, the continue statement is a control structure that allows you to
skip the current iteration of a loop and proceed directly to the next one. Unlike the break
statement, which completely exits the loop, the continue statement bypasses the remaining
code within the loop for that iteration only, allowing the loop to continue with the following
Object Oriented Programming With JAVA
cycle. This makes continue especially useful in scenarios where you need to skip certain
conditions within the loop without terminating it entirely.
return statement
The return statement serves as a crucial tool for exiting a method and, if desired,
returning a value to the calling method. This statement effectively ends the execution of the
current method, transferring control back to the original calling method.
Syntax:
Output: