[Go to site: main page, start]

0% found this document useful (0 votes)
24 views13 pages

Java Control Statements Explained

The document discusses various control statements in Java including decision making statements like if, if-else, if-else-if ladder, nested if, and switch statements. It also discusses loop statements like while, for, do-while loops. Decision making statements are used to control program flow based on conditions while loop statements are used to repeatedly execute a block of code. The document provides syntax and examples for each statement type.
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)
24 views13 pages

Java Control Statements Explained

The document discusses various control statements in Java including decision making statements like if, if-else, if-else-if ladder, nested if, and switch statements. It also discusses loop statements like while, for, do-while loops. Decision making statements are used to control program flow based on conditions while loop statements are used to repeatedly execute a block of code. The document provides syntax and examples for each statement type.
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

JAVA

Pranaya
Java Control Statements

The statements that control the execution flow of the program


are known as control statements.

When we try to execute a program, we modify and repeat the


data several times. We need some tools for these modifications
that will control the flow of the program, and perform this type
of task Java Provides control statements.

There are three types of control statement

1- Decision Making statements

Pranaya
* if statements
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement

* switch statement

2- Loop statements
do while loop
while loop
for loop
for-each loop

3- Jump statements ( we will learn it on the next PDF)


break statement
continue statement
if Statement

In Java, the "if" statement is used to evaluate a condition.

Simple if-statement

Use if to specify a block of code to be executed, if a specified condition


is true. Use else to specify a block of code to be executed if the same
condition is false. Use else if to specify a new condition to test, if the
first condition is false.

SYNTAX:

Pranaya
if(condition) {
statement 1; //executes when condition is true
}

Example:

public class one{


public static void main(String[] args) {


int markes=100;
if(markes>33)
{
[Link]("pass");
}
}
}

Output:
pass
The if-else statement
is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-
block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Pranaya
Example

public class ifelseex {


public static void main(String[] args) {


int markes=100;
if(markes<33)
{
[Link]("pass");
}
else
{
[Link]("failed");
}

}
if-else-if :
The if-else-if statement contains the if-statement followed by
multiple else-if statements. In other words, we can say that it is the
chain of if-else statements that creates a decision tree where the
program may enter the block of code where the condition is true.
We can also define an else statement at the end of the chain.
Syntax:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false

Pranaya
}
Example

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
[Link]("city is meerut");
}
else if (city == "Noida") {
[Link]("city is noida");
}
else if(city == "Agra") {
[Link]("city is agra");
}
else {
[Link](city);
}
}
Output: Delhi

Nested if-statement

In nested if-statements, the if statement can contain an if or if-else


statement inside another if or else-if statement.
Syntax.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}

Pranaya
Example

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if([Link]("India")) {
if([Link]("Meerut")) {
[Link]("Your city is Meerut");
}
else if([Link]("Noida")) {
[Link]("Your city is Noida");
}
else {
[Link]([Link](",")[0]);
}
}
else {
[Link]("You are not living in India");
}
}
}
Output:- Delhi

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The


switch statement contains multiple blocks of code called cases and a
single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of the if-else-
if statements. It also enhances the readability of the program.

Points to be noted about the switch statement:

1. The case variables can be int, short, byte, char, or enumeration.


String type is also supported since version 7 of Java
2. Cases cannot be duplicated
3. A default statement is executed when any of the cases doesn't
match the value of the expression. It is optional.

Pranaya
4. The break statement terminates the switch block when the
condition is satisfied.
5. It is optional, if not used the next case is executed.
6. While using switch statements, we must notice that the case
expression will be of the same type as the variable. However, it
will also be a constant value.
Syntax
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }

example

public class switchassn {


public static void main(String[] args) {
String country="nepal";
switch(country)
{
case "india":
[Link]("Capital of india is New Delhi");
break;
case "nepal":
[Link]("capital of nepal is kathmandu");
break;
case "uk":
[Link]("capital of uk is london");

Pranaya
break;
case "usa":
[Link]("capital of usa is Washingtone-Dc");
break;
case "uae":
[Link]("capital of uae is abu dhabi");
break;
case "australia":
[Link]("capital of australia is canberra");
break;
default:
[Link]("There is no information about this name");
}
}
}
Output:
capital of nepal is Kathmandu

Loop Statements

In programming, sometimes we need to execute the block of code


repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a
particular condition.

In Java, we have three types of loops that execute similarly

1. while loop
2. for loop
3. do-while loop

for loop

Pranaya
When you know exactly how many times you want to loop through a
block of code, use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code


block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been
executed.

Example

public class Main {


public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
[Link](i);
}
}
}
Output : 0 1 2 3 4
for-each loop
Java provides an enhanced for loop to traverse the data structures like
array or collections. In the for-each loop.

Syntax:

for(data_type var : array_name/collection_name)


{
//statements
}

Example

[Link] class Calculation {


[Link] static void main(String[] args) {

Pranaya
3.// TODO Auto-generated method stub
[Link][] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
[Link](String name:names) {
[Link](name);
8.}
9.}
10. }

Output:
Printing the content of the array names:

Java
C
C++
Python
JavaScript

While Loop

The while loop loops through a block of code as long as a specified


condition is true:
Syntax
while (condition)
{
// code block to be executed
}
Example

public class Main {


public static void main(String[] args) {
int i = 0;
while (i < 5) {

Pranaya
[Link](i);
i++;
}
}
}

Output: 0 1 2 3 4

Note: Do not forget to increase the variable used in the condition,


otherwise the loop will never end!

Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it
will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);

Example

public class whileex {


public static void main(String[] args) {


int a=0;
do
{
[Link]("nice");

Pranaya
a++;
}
while(a<=3);

Output: nice
nice
nice
nice

Thank
y !
o u
Pranaya !

Common questions

Powered by AI

Control statements, including loop statements and decision-making statements, inter-relate by collectively managing the logical flow and reusability of code blocks in a Java program. Decision-making statements like if-else and switch decide which code block to execute based on conditions. Loop statements, such as while, do-while, and for, allow repeated execution of code blocks as long as a condition remains true. Together, they enable a programmer to implement complex logic and repetitive processes efficiently and flexibly, ensuring that a program can adapt dynamically to varying inputs and states .

The nested if-else statement in Java allows you to place an if or if-else statement inside another if or else-if statement. This structure is used when you have multiple conditions that need hierarchical testing, providing a way to test a condition only after another condition is determined to be true. On the other hand, the if-else-if ladder is used when you have multiple discrete conditions to evaluate independently; it creates a decision tree where each condition is checked sequentially until a true condition is found, or execution reaches an optional 'else' block .

A do-while loop is more appropriate than a while loop in scenarios where the code block needs to execute at least once regardless of whether the loop condition is true initially. This includes situations where initial data processing or initialization must occur before checking any conditions, such as asking for user input until valid data is received or processing elements of a list where the presence of elements is uncertain initially. The do-while loop ensures that the code block executes before any condition is evaluated .

The for-each loop in Java offers simplicity and readability when iterating over collections or arrays. Unlike a traditional for loop, it eliminates the need for an explicit counter or index variable, reducing the risk of errors related to off-by-one mistakes or incorrect index references. The loop abstracts away the complexity of accessing each element by automatically iterating through the elements of an array or collection, making the code more concise and easier to understand .

In Java, loop structures manage repetition differently based on their syntax and execution control. The 'while' loop evaluates the condition before executing the block of code, meaning if the condition is false initially, the block may not execute at all. Conversely, the 'do-while' loop guarantees that the block of code executes at least once because the condition is evaluated after the block execution. The 'for' loop is used when the number of iterations is known beforehand; it initializes a counter, checks a condition, and increments the counter in a single compact line, facilitating clear iteration management .

The primary advantage of a switch statement over an if-else-if ladder is enhanced readability and simplified syntax, particularly when dealing with multiple conditions that compare a single variable against various constant values. The switch statement segments cases clearly, reducing the potential for errors and making code easier to read. Additionally, switch statements can be more optimal in performance when compiled, especially in situations involving a large number of comparisons .

The default case in a Java switch statement acts as a catch-all path that executes when none of the defined cases match the switch expression. Its importance lies in handling unexpected values or unanticipated conditions gracefully, ensuring that the program can provide an appropriate response or error handling. This enhances robustness by preventing unintended behaviors that could occur if the switch expression did not match any predefined case values. Without a default case, a switch may exit without executing any code if no match is found, potentially leading to logical errors or omitted responses in the program's logic .

If a break statement is not used within a Java switch case, the control falls through to subsequent cases until it encounters a break or reaches the end of the switch block. This behavior, known as "fall through," can lead to unintended execution of multiple cases and incorrect program logic if not explicitly desired by the programmer. It can impact program flow by executing code blocks intended for different conditions, leading to logical errors that can be difficult to debug .

To convert an if-else statement into a switch statement effectively, each conditional expression within the if-else blocks should evaluate a single variable against distinct constant values, which is a requirement for switch cases. Adjustments in data types might be necessary since switch statements generally support integers, characters, enums, and strings as the variable types. Logical structure changes would include reorganizing conditions into case blocks and ensuring appropriate handling with break statements to mimic the mutual exclusivity of if-else conditions. A default case could also be added to handle cases not explicitly covered, akin to the final else block .

It is crucial to ensure the variable in a Java while loop condition is updated appropriately to prevent infinite loops. If the condition variable is not updated within the loop, the condition might always evaluate to true, causing the loop to run indefinitely, potentially leading to a program crash or unresponsive behavior. Proper updating of the condition variable ensures the loop can end under the correct conditions, maintaining program control flow and resource efficiency .

You might also like