Control Statements
Control Statements
CONTROL STATEMENTS
Control statements:
Control statements in Java allow you to manage the flow of execution within a program. They enable
decision-making, looping, and altering the flow based on certain conditions.
The main categories of control statements in Java are:
1.Decision-Making Statements
2.Switch Statements
3.Looping Statements
4.Jump Statements
CONTROL STATEMENTS
These conditional statements work with different types of values based on the conditions provided.
CONTROL STATEMENTS
1) if Statement:
The if statement in Java is a basic control structure used to execute a block of code only if a specified condition
evaluates to true. If the condition is false, the block of code inside the if statement is skipped.
Condition: A boolean expression that returns either true or false. If the condition is true, the code inside the if block is
executed. If it is false, the code is ignored.
Working of if Statement:
Key Points:
4.Single block execution: Only the code inside the if block is executed if the condition is true.
2.Condition must evaluate to boolean: The condition in the if statement must be a boolean expression (true or false).
3.Curly braces: Curly braces {} are used to define the block of code that should be executed if the
condition is true. They can be omitted if there is only one statement, but it’s generally a good practice
to always use them to avoid mistakes.
CONTROL STATEMENTS
Syntax:
if (condition)
{
// code to execute if condition is true
}
1. Checking Equality:
int x = 100;
if (x == 100)
{
System.out.println("x is equal to 100.");
}
The condition x == 100 checks if the value of x is equal to 100. Since it is, the message "x is equal to 100" is printed.
The condition age >= 20 && age <= 30 checks if the age is between 20 and 30. Since the age is 25, the condition
evaluates to true and the message "You are in your 20s" is printed.
CONTROL STATEMENTS
2) if-else Statement
The if-else statement in Java is a control flow structure that allows you to execute one block of code if a condition is
true and another block if the condition is false. It is used to handle two alternative paths of execution based on a
condition.
Condition: A boolean expression that evaluates to either true or false.
If the condition is true, the block of code inside the if statement is executed.
If the condition is false, the block of code inside the else statement is executed.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
You can combine conditions using logical operators (&&, ||, etc.) inside an if-else statement.
3) if-else-if Ladder
The if-else-if ladder in Java allows you to test multiple conditions sequentially. If one of the conditions is true, its
corresponding block of code is executed, and the rest of the ladder is skipped. If none of the conditions are true, the
else block (if present) is executed.
Key Points:
Sequential evaluation: The conditions are evaluated one after the other. Once a condition is found to be true, the
corresponding block is executed, and the rest of the ladder is skipped.
else block is optional: You can omit the else block if you only want to handle specific cases and don't need to
handle the scenario where none of the conditions are true.
Efficient use: The if-else-if ladder is useful when there are multiple conditions to check, such as determining a
grade, checking age ranges, or comparing values.
CONTROL STATEMENTS
How It Works:
•The program first checks condition1. If it is true, the corresponding block of code is executed, and the rest of the else-if
blocks are skipped.
•If condition1 is false, the program checks condition2, and so on.
•If none of the conditions are true, the else block (if present) is executed.
CONTROL STATEMENTS
Explanation:
If age is less than 13, the program prints "Child".
If age is between 13 and 19, it prints "Teenager".
If age is between 20 and 59, it prints "Adult".
Otherwise, the program prints "Senior Citizen".
For age = 25, the program will print "Adult".
CONTROL STATEMENTS
Explanation:
4) Nested if Statement
The nested if statement in Java is used when there are multiple layers of conditions to evaluate, meaning an if
statement is placed inside another if or else block. This allows you to check multiple conditions in a hierarchical or
layered manner, where one condition depends on another.
Explanation:
The outer if checks if the student passed with a score of 50 or higher.
If the student passed, the nested if statements determine the grade based on the score.
If marks>=90, the grade is A, if marks>=80, the grade is B, and for other passing scores, the grade is C.
If marks is below 50, the student failed.
CONTROL STATEMENTS
Switch Statements:
The switch statement in Java is used to execute one block of code among many choices, based on the value of an
expression. The switch expression can be of different types (integers, characters, strings, etc.), and the corresponding
case that matches the value of the expression will be executed.
Key Points:
Primitive types: int, char, byte, short, etc., are supported in switch.
String: You can use String values in switch from Java 7 onward.
enum: Use enum constants in switch to handle sets of constant values.
Wrapper classes: Wrapper types like Integer, Character, etc., can be used thanks to auto-unboxing.
Enhanced switch: From Java 12, switch expressions allow returning values and support a cleaner arrow syntax.
The switch statement provides an efficient way to write readable, structured code, especially when handling multiple
possible values for a variable.
CONTROL STATEMENTS
Explanation:
In this example, the day variable holds the value 3, so the code in the block for case 3 will execute,
printing "Wednesday".
If no match is found (e.g., day = 7), the default block is executed.
CONTROL STATEMENTS
Explanation:
•Here, the char variable grade is checked against the different cases. Since grade is 'B', the program prints "Good!".
•If the value doesn’t match any of the cases, the default block executes.
CONTROL STATEMENTS
Explanation:
In this case, the switch expression is a String variable. If fruit is "Apple", the program prints
"Apples are red or green."
Using switch with String types is useful when there are multiple string options and you want to avoid
repeated if-else comparisons.
CONTROL STATEMENTS
Example:
Integer number = 10;
switch (number)
{
case 5:
System.out.println("Number is 5.");
break;
case 10:
System.out.println("Number is 10.");
break;
default:
System.out.println("Unknown number.");
}
Explanation:
In this example, number is an Integer object. Due to auto-unboxing, the switch statement automatically converts it into
its primitive int type, allowing it to be used in the switch expression.
CONTROL STATEMENTS
Syntax:
switch (expression)
{
case value1 -> statement1;
case value2 -> statement2;
default -> statement3;
}
CONTROL STATEMENTS
Example:
int day = 3;
String dayName = switch (day)
{
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid day";
};
System.out.println(dayName);
Explanation:
The new syntax allows switch to return a value (e.g., dayName), making the code more concise and readable.
Instead of break, the -> operator is used, and there is no fall-through behavior in this new form.
The expression is evaluated, and the result is directly assigned to dayName.
CONTROL STATEMENTS
Explanation:
The var keyword allows Java to infer the type of day based on the assigned value (int in this case).
The switch statement works exactly the same way as it does with explicit type declarations.
CONTROL STATEMENTS
Explanation:
Looping Statements:
In Java, loops allow repetitive execution of a block of code while a condition is true. The three
primary looping constructs in Java are:
while loop: Used when the condition must be checked before execution.
do-while loop: Used when the block must execute at least once, as the condition is
checked after execution.
CONTROL STATEMENTS
1. for Loop
A for loop is useful for iterating over a sequence or a range of values.
Syntax:
for (initialization; condition; update) {
// code to be executed
}
Example:
public class ForLoopExample
{
public static void main(String[] args) {
// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
}
}
Explanation:
•Initialization (int i = 1): Variable i is initialized to 1.
•Condition (i <= 5): The loop executes as long as i is less than or equal to 5.
•Update (i++): i is incremented by 1 after each iteration
CONTROL STATEMENTS
2. while Loop
The while loop is used when the number of iterations is not predetermined.
Syntax:
while (condition) {
// code to be executed
}
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5)
{
System.out.println("Number: " + i);
i++; // Increment the counter
}
}
}
Explanation:
The condition (i <= 5) is checked before entering the loop.
The loop runs until i exceeds 5.
CONTROL STATEMENTS
3. do-while Loop
The do-while loop guarantees that the block is executed at least once.
Syntax:
do {
// code to be executed
} while (condition);
Example:
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
// Print numbers from 1 to 5
do {
System.out.println("Number: " + i);
i++; // Increment the counter
} while (i <= 5);
}
}
Explanation:
•The block is executed once before the condition (i <= 5) is checked.
CONTROL STATEMENTS
Nested Loops
Loops can also be nested for more complex scenarios.
Example: Printing a multiplication table
public class NestedLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { // Outer loop
for (int j = 1; j <= 5; j++) { // Inner loop
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
CONTROL STATEMENTS
Practice Questions:
Java CON I0 I.Equal Or NOT EQUAL
Java CON I0 2:ODD OR EVEN
Java CON I0 3.Divisible
Java CON I0 4 : pass or fail
Java CON I0 5.find min
Java CON I0 6.Find max
Java CON I0 7.POS Or Neg or Zero
Java CON I0 8 Divisible By 3,5
Java CON I0 9.X and Y axis Problem
Java CON I0 10.Vowels or Consonants
CONTROL STATEMENTS
Practice Questions:
java CON L1 1 Leap Year
java CON.L1.2 Day, of, week
java CON.L1 3.Month Name
java CON L1 4.Uppercase or Lowercase
java CON L1 6 Gross Salary
java CON L1 5.Alphabet or Number or special Character
java CON.L1 7.calculate grade
java CON.L1 8 Arithmetic Operations
java CON L1.9 Electricity BILL
java CON.L1 10.triangle or not
CONTROL STATEMENTS
Practice Questions:
Java CON L2 Equilateral or Isosceles or Scalene
Java CON L2 Triangle Validation
Java CON L2 Find min of 3 numbers
Java CON L2 Find maximum of 3 number
Java CON L2 Find the largest of 4 numbers
Java CON L2 3 in Ascending order
Java CON L2 Arrange 4 numbers in descending order
Java CON L2 Time is valid or not
Java CON L2 DATE_VALID
CONTROL STATEMENTS
Practice Questions:
JAVA_LOOP L0_1.EVEN Numbers
JAVA_LOOP L0_2.Sum of First N odd number
JAVA_LOOP L0_3.Sum of even numbers
JAVA_LOOP L0_4.Sum divisible by 3 or 5 in range
JAVA_LOOP L0_5.FACTORIAL
JAVA_LOOP L0_6.Power Problem
JAVA LOOP L0_7.Multiplication
JAVA_LOOP L0_8.max,min,sum and average of the given n numbers
CONTROL STATEMENTS
Practice Questions:
JAVA_LOOP_LI_1Perfect Square
JAVA_LOOP_LI_2.perfect cube
JAVA_LOOP_LI_3.To make a perfect square
JAVA_LOOP_LI_4.powfunction
JAVA_LOOP_L1_5.Quotient
JAVA_LOOP_LI_6.Multiplication
JAVA_LOOP_LI_7.TRIANGULAR NUMBER
JAVA_LOOP_LI_8.Alphabet
JAVA_LOOP_LI_9.fibonacci series
JAVA_LOOP_L1_10.Skip iteration
CONTROL STATEMENTS
Practice Questions:
JAVA_LOOP_L2_1.Trailing Zeros
JAVA_LOOP_L2_2.alt_2_3_power
JAVA_LOOP_12_3.mul_div_by_2_series
JAVA_LOOP_L2_4.Pentagonal number
JAVA_LOOP_L2_5.Proth number
JAVA_LOOP_L2_6.Co-ordinate from origin
JAVA_LOOP_L2_7.Remaining Days
JAVA_LOOP_L2_8.Completed Days
JAVA_LOOP_L2_9.Elapsed Time
JAVA_LOOP_L2_10.DATE DIFFERENCE
THANK YOU