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

Java Control Structures Overview

The document provides an overview of Java control structures, specifically focusing on conditional branches such as if statements, if-else statements, if-else-if statements, and switch statements. It includes syntax and examples for each type of statement, demonstrating how they can be used to control the flow of a program based on conditions. Additionally, various sample programs illustrate practical applications of these control structures.
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)
9 views13 pages

Java Control Structures Overview

The document provides an overview of Java control structures, specifically focusing on conditional branches such as if statements, if-else statements, if-else-if statements, and switch statements. It includes syntax and examples for each type of statement, demonstrating how they can be used to control the flow of a program based on conditions. Additionally, various sample programs illustrate practical applications of these control structures.
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

Computer Programming 2

Module 3: Java Control Structures – Conditional Branches

Conditional Control Structures allows the program to select between the alternatives during the program execution.

They are also called as decision-making statements or selection statements.

Conditional Control Statements


 if statement
 if - else statement
 if - else - if statement
 switch statement

If Statement

It will go inside the block only if the condition is true otherwise, it will not execute the block.

Syntax:

if (condition) {
//statements (if block)
}
//other statements - executed irrespective of the condition

Example:

int number = 23;


if(number > 20) {
[Link]("Number is greater than 20.");
}
If - Else Statement

If the condition is true then, it will execute the if block. Otherwise, it will execute the else block.

Syntax:

if (condition) {
statements (if block)
} else {
statements (else block)
}
Example:

int number = 15;


if(number > 20) {
[Link]("Number is greater than 20.");
} else {
[Link]("Number is less than 20.");
}

If - Else - If Statement

If the condition is true, then it will execute the if block. Otherwise, it will execute the else-if block. Again, if the condition
is not met, then it will move to the else block.

Syntax:

if (condition 1) {
statements (if block)
} else if (condition 2) {
statements (else - if block)
} else {
statements (else block)
}
Example:

int number = 2;
int anotherNumber = 3;
int theOtherNumber = 4;

if(number > anotherNumber){


[Link]("Output.");
} else if(number > theOtherNumber) {
[Link]("Another output.");
} else {
[Link]("The other output.");
}

Switch Statement

Switch statement allows program to select one action among multiple actions during the program execution.

Syntax:

switch (variable or value or expression) {


case :
statements;
break;
case :
statements;
break;

default:
statements;
break;
}
Based on the argument in the switch statement suitable case value will be selected and executed.
If no matching case found, then the default will be executed.
It is optional to write a break statement at the end of each case statement.

Example:

int option = 2;
switch(option){
case 1:
[Link]("Output.");
break;
case 2:
[Link]("Another output.");
break;
default:
[Link]("The other output.");
break;
}
Other program examples

Program #1

import [Link];
public class PositiveOrNegative {
static Scanner scanner = new Scanner([Link]);
public static void main(String[] args) {
int inputNumber;
[Link]("Positive or negative number");
[Link]("Enter a number: ");
inputNumber = [Link]();
if(inputNumber >= 0) {
[Link]("The input number is positive.");
} else {
[Link]("The input number is negative.");
}
}
}
Program #2

import [Link];
public class PositiveOrNegative {
static Scanner scanner = new Scanner([Link]);
public static void main(String[] args) {
int inputNumber;
[Link]("Positive or negative number");
[Link]("Enter a number: ");
inputNumber = [Link]();
if(inputNumber == 0) {
[Link]("The input number is not positive or negative.");
} else if(inputNumber > 0){
[Link]("The input number is positive.");
} else {
[Link]("The input number is negative.");
}
}
}
Program #3

import [Link];
public class ColorEquivalent {
static Scanner scanner = new Scanner([Link]);
public static void main(String[] args) {
int inputNumber;
[Link]("Color Equivalent");
[Link]("Enter a number: ");
inputNumber = [Link]();
switch(inputNumber) {
case 1: case 2: case 3:
[Link]("The equivalent color is red.");
break;
case 4: case 5: case 6:
[Link]("The equivalent color is yellow.");
break;
case 7: case 8: case 9:
[Link]("The equivalent color is blue.");
break;
default:
[Link]("Input error, there is no equivalent color.");
break;
}
}
}
Program #4

import [Link];
public class InchesToCentimeters {
static Scanner scanner = new Scanner([Link]);
public static void main(String[] args) {
final double CENTIMETERS_PER_INCH = 2.54;
double inches;
double centimeters;

[Link]("Inches to Centimeters");
try {
[Link]("Enter value in inches: ");
inches = [Link]();
if(inches <= 0) {
[Link]("Zero or negative input is not allowed.");
} else {
centimeters = inches * CENTIMETERS_PER_INCH;
[Link]("Output is " + [Link]("%,.2f" ,centimeters) + ".");
}
} catch(Exception e) {
[Link]("Invalid input, letters or special symbols in inches are not allowed.");
}
}
}
Program #5

import [Link].*;
public class AreaOfTheRectangle {
static Scanner console = new Scanner([Link]);
public static void main(String[] args) {
double length;
double width;
double area;

[Link]("Area of the Rectangle");


try {
[Link]("Enter length: ");
length = [Link]();
if(length <= 0) {
[Link]("Input error, zero or negative length is not allowed.");
} else {
try {
[Link]("Enter width: ");
width = [Link]();
if(width <= 0) {
[Link]("Input error, zero or negative width is not allowed.");
} else {
area = length * width;
[Link]("The area is " + [Link]("%,.2f", area) + ".");
}
} catch(Exception e) {
[Link]("Invalid input, letters or special symbols in width are not allowed.");
}
}
} catch(Exception e) {
[Link]("Invalid input, letters or special symbols in length are not allowed.");
}
}
}
Program #6

import [Link].*;
public class AreaOfTheRectangle {
static Scanner console = new Scanner([Link]);
public static void main(String[] args) {
double length;
double width;
double area;

[Link]("Area of the Rectangle");


[Link]("Enter length: ");
if(([Link]()) == true) {
length = [Link]();
if(length <= 0) {
[Link]("Input error, zero or negative length is not allowed.");
} else {
[Link]("Enter width: ");
if(([Link]()) == true) {
width = [Link]();
if(width <= 0) {
[Link]("Input error, zero or negative width is not allowed.");
} else {
area = length * width;
[Link]("The area is " + [Link]("%,.2f", area) + ".");
}
} else {
[Link]("Invalid input, letters or special symbols in width are not allowed.");
}
}
} else {
[Link]("Invalid input, letters or special symbols in length are not allowed.");
}
}
}
Program #7

import [Link];
public class ColorEquivalent {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int inputNumber;

[Link]("Color Game");
try {
[Link]("Enter a number: ");
inputNumber = [Link]();
switch(inputNumber) {
case 1: case 2:
[Link]("The equivalent color is red.");
break;
case 3: case 4:
[Link]("The equivalent color is yellow.");
break;
case 5: case 6:
[Link]("The equivalent color is blue.");
break;
default:
[Link]("Input error, please input from 1 to 6 only.");
break;
}
} catch(Exception e) {
[Link]("Invalid input, letters or special symbols in input number are not allowed.");
}
}
}
Quick review

Control structures alter the sequential flow of control.

Selection structures incorporate decisions in a program.

Including a semicolon before the statement in a one-way selection creates a semantic error. In this case, the action of the if
statement is empty.

There is no stand-alone else statement in Java programming language. Every else has a related if.

An else is paired with the most recent if that has not been paired with any other else.

A sequence of statements enclosed between braces, { and }, is called a compound statement or block of statements. A
compound statement is treated as a single statement.

A switch structure is used to handle multiple selections.

The expression in a switch statement must evaluate to an integral value.

A switch statement executes according to the following rules:

When the value of the expression is matched against a case value, the statements execute until either a break
statement is found or the end of the switch structure is reached.

If the value of the expression does not matched any of the case values, the statements following the default
label execute. If the switch structure has no default label, and if the value of the expression does not match any of the
case values, the entire switch statement is skipped.

A break statement causes an immediate exit from the switch structure.


References:

Java programming: From program analysis to program design by: D. S. Malik


[Link]
[Link]

Common questions

Powered by AI

In the 'PositiveOrNegative' program examples, the handling of zero differs, dividing the logic into more explicit conditions. In one version, zero is checked with 'if(inputNumber >= 0)', treating zero as positive, while the other version uses 'else if(inputNumber == 0)', specifically categorizing zero as neither positive nor negative. This affects the output by providing a more nuanced response to zero inputs, offering a third category for the user's understanding . The latter approach reflects better clarity by acknowledging zero's ambiguity, enhancing logical precision in program output .

Omitting break statements in a switch-case construct causes 'fall-through' behavior, where multiple cases execute sequentially after a matching case unless a break is encountered. This can lead to unintended executions of cases, subtle bugs, and logic errors in programs. When control starts with a matching case, it proceeds to execute all subsequent cases until a break or the end of the switch is reached, altering intended program flow . Including break statements ensures that only the matching case's statements are executed before exiting the switch structure .

Compound statements, or blocks, are sequences of statements enclosed within braces '{ }', allowing multiple statements to be treated as a single unit. They improve readability by providing a clear structure and scope for executing related commands together within control structures like loops and conditionals. For instance, when multiple actions need to be performed if a condition is true, using a block reduces ambiguity and enhances maintainability. Compound statements also enable the encapsulation of complex logic into defined sections, making the code easier to follow and debug .

Decision-making statements like 'if' and 'switch' in Java significantly influence control flow by guiding which code segments execute based on conditions or expressions. 'If' statements enable specific actions based on boolean expressions, allowing branching logic for condition checks ('if', 'if-else', 'if-else-if'). For instance, a program can decide to execute additional validation if a user's input exceeds a threshold. Meanwhile, 'switch' statements simplify selections among many discrete options, such as mapping numeric input to corresponding outputs. Each optimizes code by minimizing redundancies and enhancing logical flow .

Placing an extraneous semicolon immediately after the condition in Java's one-way selection ('if') introduces semantic errors by creating an empty statement. This causes the 'if' condition block to be bypassed regardless of truth value, leading to unexpected program behavior since the intended block of statements inside the condition is never executed. The impact is significant as the program may execute statements outside the intended conditional scope, leading to logical flaws and malfunction. Such errors are difficult to detect because they do not cause syntax errors, allowing compilation without warnings .

The 'ColorEquivalent' switch statement in Java uses integral expressions to determine program flow based on predefined case values. This includes evaluating the 'inputNumber' against specific integer cases to decide which color equivalent to print. The requirement for integral expressions ensures the switch statement's simplicity and efficiency, reducing computational overhead. By limiting expressions to discrete values like integers, the switch statement quickly matches expression results to case values, facilitating rapid decisions without complex evaluation, thereby promoting performance and simplicity in execution .

The try-catch mechanism in Java enhances program robustness by handling potential runtime exceptions, allowing the program to continue executing or terminate gracefully instead of crashing. This is particularly useful in handling user input, where invalid input such as letters instead of numbers can cause exceptions. By using a try block to detect erroneous input and a catch block to handle exceptions, developers can provide meaningful error messages and prevent the program from terminating unexpectedly .

Distinguishing zero from positive or negative values is critical in real-world software applications for accuracy and precision. In financial software, zero distinguishes between a balanced account and outstanding credits or debits, influencing transaction validation and reporting. In scientific calculations, zero can signify equilibrium states or nullifying factors in equations, affecting results and experiment interpretations. Therefore, precise categorization of zero versus non-zero ensures clarity and correctness in data modeling, decision-making, and outcomes, impacting significant applications where accuracy is paramount .

The 'if-else-if' statement in Java tests multiple conditions sequentially until one is true. Unlike the simple 'if' or 'if-else' structures, it allows for multiple conditions to be checked in a single structure without nesting multiple if statements. The flow starts with the first condition; if true, it executes the corresponding block. If false, it moves on to the next condition and evaluates it. This continues until a true condition is found or the 'else' block executes if none are true. It is advantageous as it simplifies readability and avoids deeply nested code by consolidating multiple condition checks into one structured flow .

Validating numerical input in Java is crucial for ensuring program reliability and preventing runtime errors. Inputs are prone to errors such as non-numeric characters or unexpected symbols, which can lead to exceptions and program crashes if not handled. The use of validation techniques, such as checking input types and using try-catch blocks, allows programs to handle invalid inputs gracefully, provide user feedback, and maintain robust operation. Neglecting input validation can result in erroneous data processing, security vulnerabilities, and a poor user experience .

You might also like