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

Java Control Structures Explained

Uploaded by

Roo Anu
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 views4 pages

Java Control Structures Explained

Uploaded by

Roo Anu
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

Control Structures in Java

1. conditional statements in Java


 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
 Use switch to specify many alternative blocks of code to be executed

if Statement
 Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax:
if (condition) {
// block of code to be executed if the condition is true
}

else Statement
Use the else statement to specify a block of code to be executed if the condition is false.

Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

else if Statement
Use the else if statement to specify a new condition if the first condition is false.

Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Short Hand If...Else (Ternary Operator)


There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.
It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else
statements:

Syntax:
variable = (condition) ? expressionTrue : expressionFalse;

Example
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
[Link](result);

1 Prepared by Sisira Palihakkara


Switch Statements
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:

Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in this chapter

break Keyword
 When Java reaches a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing inside the block.

2. Loop statements in Java

Loops can execute a block of code as long as a specified condition is reached.


 while Loop
 do/while Loop

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:
int i = 0;
while (i < 5) {
[Link](i);
i++;
}

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
}

2 Prepared by Sisira Palihakkara


while (condition);

Example:
int i = 0;
do {
[Link](i);
i++;
}
while (i < 5);

for Loop
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:
for (int i = 0; i < 5; i++) {
[Link](i);
}

for-each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

Syntax:
for (type variableName : arrayName) {
// code block to be executed
}

Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
[Link](i);
}

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets:

String[] cars;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.

3 Prepared by Sisira Palihakkara


Array Length
To find out how many elements an array has, use the length property:

Java Break statement


The break statement can also be used to jump out of a loop.

Example:
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
[Link](i);
}

Java Continue statement


The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the
next iteration in the loop.

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
[Link](i);
}

******

4 Prepared by Sisira Palihakkara

Common questions

Powered by AI

The break statement in Java is used to terminate a loop, effectively ending its execution and transferring control to the statement immediately following the loop . On the other hand, the continue statement skips the current iteration of the loop and immediately jumps to the next iteration, but without terminating the loop itself .

In switch statements, the 'break' keyword is used to terminate a case block, preventing the execution from 'falling through' to subsequent cases . In loop structures, 'break' exits the loop entirely, transferring control to the statement following the loop, thus providing a mechanism for premature loop exit when a certain condition is met .

The ternary operator in Java enhances code readability and efficiency by condensing a simple if-else statement into a single line. It reduces the number of lines needed and makes the code more concise, which is aesthetically cleaner and often easier to read. This syntax, 'variable = (condition) ? expressionTrue : expressionFalse;', allows quick assignments based on conditions, improving efficiency both in writing and in execution simplicity .

Conditional structures like if-else and switch statements enhance strategic decision-making by enabling complex logic flow through automated branching decisions. If-else statements offer flexible conditions, suitable for branching paths that change according to intricate Boolean evaluations. Switch statements simplify multi-condition evaluations into accessible, readable formats, allowing clear, efficient routing based on constant values, thus optimizing decision-making processes in varied scenarios .

While loops check the condition before executing the loop body, which means the loop may not run at all if the condition is initially false. They are ideal for conditions where pre-execution validation is necessary . In contrast, do/while loops execute the loop body once before the condition is checked, ensuring that the loop runs at least once regardless of the condition, suitable for executing a block of code that requires at least one execution like input validation prompts .

The switch statement simplifies code readability by handling multiple conditional branches more neatly than multiple if-else statements. Each case in a switch is explicit and clearly delineated, reducing clutter and making it easier to follow logic paths . Moreover, switch statements can be optimized by the Java compiler into a lookup table for certain constructs, potentially enhancing performance with constant time complexity as opposed to the linear time complexity of if-else chains.

Arrays in Java enhance memory management by allowing the storage of multiple values in a single variable, thereby reducing the overhead associated with managing numerous discrete variables. This approach utilizes memory more efficiently through contiguous storage, which speeds up access as elements can be indexed and accessed sequentially . Arrays provide systematic memory allocation, which facilitates effective management and iteration over collections of data without individual variable declarations.

The 'for' loop is used when the precise number of iterations is known prior to loop execution, making it ideal for incremental iteration with specific control over index behavior . In contrast, the 'for-each' loop is used for iterating through elements within a collection or array without the need for an index, simplifying the code and minimizing potential errors from manual index handling . The 'for-each' is particularly advantageous for read-only operations on collections where the order is not manipulated.

In the for loop structure in Java, the initialization expression is executed once to establish iteration start, typically initializing a loop control variable. The condition expression is evaluated before each loop iteration, and if true, the loop body executes; otherwise, the loop terminates. The increment expression processes after the loop body execution and often adjusts the loop variable to prepare for the next iteration, thereby precisely managing the loop's execution flow .

Omitting the 'default' case in a switch statement may lead to undefined behavior when none of the case conditions match the switch expression, as no code gets executed for unmatched values. This can impact program robustness, especially in handling unexpected inputs or cases, leading to potential logical errors or incomplete executions. Providing a simple action within 'default' enhances the program's ability to handle all input controls effectively .

You might also like