How to use if else, for loop, switch case, nested if else statement.



Introducing Control Statements


A flow control statement is used to check a condition whether the condition is true or false, if the condition is true it returns true but if the condition is false it returns false.  for instance a user inputs his or her username, flow control statement can be used to check if the user name is corresponding who is the one in the database it also can be used the shack if number is equals to another number so let's do more example to understand flow control statement.
Flow control statement is also use to make an action to occur in a number of time for example you want to write a program that can display 1 to 10 flow control statement can help you to read through loop and we have different types of flow control statement we have conditional statement and the flow control statement the conditional statements are the if and else statement and switch case statement.
Example of flow control statements are for Loop while loop do while loop.
These statements will be dealt with in more detail further on in this For now we will learn.

about the if and the for loop.

class Example11 {

 public static void main(String args[]) {

 int a,b,c;

 a = 2;

 b = 3;

 c = a - b;

if (c >= 0) System.out.println("c is a positive number");

 if (c < 0) System.out.println("c is a negative number");

 System.out.println();

 c = b - a;

 if (c >= 0) System.out.println("c is a positive number");

 if (c < 0) System.out.println("c is a negative number");

 }

}

Predicted output:

c is a negative number

c is a positive number

The ‘if’ statement evaluates a condition and if the result is true, then the following statement/s are
executed, else they are just skipped (refer to program output). The line System.out.println() simply
inserts a blank line. Conditions use the following comparison operators:
Operator Description

< Smaller than

> Greater than

<= Smaller or equal to, (a<=3) : if a is 2 or 3, then result of comparison is TRUE

>= Greater or equal to, (a>=3) : if a is 3 or 4, then result of comparison is TRUE
The for loop is an example of an iterative code, i.e. this statement will cause the program to repeat a

particular set of code for a particular number of times. In the following example we will be using a

counter which starts at 0 and ends when it is smaller than 5, i.e. 4. Therefore the code following the

for loop will iterate for 5 times.

class Example12 {

 public static void main(String args[]) {

 int count;

 for(count = 0; count < 5; count = count+1)

 System.out.println("This is count: " + count);

 System.out.println("Done!");

 }

}

Predicted Output:

This is count: 0

This is count: 1

This is count: 2

This is count: 3

This is count: 4

Done!

Instead of count = count+1, this increments the counter, we can use count++

The following table shows all the available shortcut operators:

Operator Description Example Description

++ Increment a++ a = a + 1 (adds one from a)

-- Decrement a-- a = a – 1 (subtract one from a)

+= Add and assign a+=2 a = a + 2

-= Subtract and assign a-=2 a = a – 2

*= Multiply and assign a*=3 a = a * 3

/= Divide and assign a/=4 a = a / 4

%= Modulus and assign a%=5 a = a mod 5
s of Code

Whenever we write an IF statement or a loop, if there is more than one statement of code which has

to be executed, this has to be enclosed in braces, i.e. ‘, …. -’

class Example13 {

 public static void main(String args[]) {

 double i, j, d;

 i = 5;

 j = 10;

 if(i != 0) {

 System.out.println("i does not equal zero");

 d = j / i;

 System.out.print("j / i is " + d);

}

 System.out.println();

 }

}

Predicted Output:

i does not equal to zero

j/i is 2

 Test your skills – Example14

Write a program which can be used to display a conversion table, e.g. Euros to Malta Liri, or Metres

to Kilometres.

Hints:

 One variable is required

 You need a loop

The Euro Converter has been provided for you for guidance. Note loop starts at 1 and finishes at 100

(<101). In this case since the conversion rate does not change we did not use a variable, but assigned

Part 2 - Advanced Java Programming

Control Statements - The if Statement

if(condition) statement;

else statement;

Note:

 else clause is optional

 targets of both the if and else can be blocks of statements.

The general form of the if, using blocks of statements, is:

if(condition)

{

statement sequence

}

else

{

statement sequence

}

If the conditional expression is true, the target of the if will be executed; otherwise, if it exists,

the target of the else will be executed. At no time will both of them be executed. The conditional

expression controlling the if must produce a boolean result.
Nested if

The main thing to remember about nested ifs in Java is that an else statement always refers to the

nearest if statement that is within the same block as the else and not already associated with an

else. Here is an example:

if(i == 10) {

if(j < 20) a = b;

if(k > 100) c = d;

else a = c; // this else refers to if(k > 100)

}

else a = d; // this else refers to if(i == 10)

Guessing Game v.3

// Guess the letter game, 3rd version.

class Guess3 {

public static void main(String args[])

throws java.io.IOException {

char ch, answer = 'K';

System.out.println("I'm thinking of a letter between A

and Z.");

System.out.print("Can you guess it: ");

ch = (char) System.in.read(); // get a char

if(ch == answer) System.out.println("** Right **");

else {

System.out.print("...Sorry, you're ");

// a nested if

if(ch < answer) System.out.println("too low");

else System.out.println("too high");

}

}

}

else if(x==3)

System.out.println("x is three");

else if(x==4)

System.out.println("x is four");

else

System.out.println("x is not between 1 and 4");

}

}

}

The program produces the following output:

x is not between 1 and 4

x is one

x is two

x is three

x is four

x is not between 1 and 4

Ternary (?) Operator

Declared as follows:

Exp1 ? Exp2 : Exp3;

Exp1 would be a boolean expression, and Exp2 and Exp3 are expressions of any type other than

void. The type of Exp2 and Exp3 must be the same, though. Notice the use and placement of the

colon. Consider this example, which assigns absval the absolute value of val:

absval = val < 0 ? -val : val; // get absolute value of val

Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval

will be assigned the negative of that value (which yields a positive value).
switch Statement (case of)

The switch provides for a multi-way branch. Thus, it enables a program to select among several

alternatives. Although a series of nested if statements can perform multi-way tests, for many

situations the switch is a more efficient approach.

switch(expression) {

case constant1:

statement sequence

break;

case constant2:

statement sequence

break;

case constant3:

statement sequence

break;

...

default:

statement sequence

}

 The switch expression can be of type char, byte, short, or int. (Floating-point expressions,

for example, are not allowed.)

 Frequently, the expression controlling the switch is simply a variable.

 The case constants must be literals of a type compatible with the expression.

 No two case constants in the same switch can have identical values.

 The default statement sequence is executed if no case constant matches the expression.

The default is optional; if it is not present, no action takes place if all matches fail. When a

match is found, the statements associated with that case are executed until the break is

encountered or, in the case of default or the last case, until the end of the switch is reached.
The following program demonstrates the switch.

// Demonstrate the switch.

class SwitchDemo {

public static void main(String args[]) {

int i;

for(i=0; i<10; i++)

switch(i) {

case 0:

System.out.println("i is zero");

break;

case 1:

System.out.println("i is one");

break;

case 2:

System.out.println("i is two");

break;

case 3:

System.out.println("i is three");

break;

case 4:

System.out.println("i is four");

break;

default:

System.out.println("i is five or more");
}
}

The output produced by this program is shown here:

i is zero

i is one

i is two

i is three

i is four

i is five or more

i is five or more

i is five or more

i is five or more

i is five or more

The break statement is optional, although most applications of the switch will use it. When

encountered within the statement sequence of a case, the break statement causes program flow to

exit from the entire switch statement and resume at the next statement outside the switch.

However, if a break statement does not end the statement sequence associated with a case, then all

the statements at and following the matching case will be executed until a break (or the end of the

switch) is encountered. For example,

// Demonstrate the switch without break statements.

class NoBreak {

public static void main(String args[]) {

int i;

for(i=0; i<=5; i++) {

switch(i) {

case 0:

System.out.println("i is less than one");

case 1:

System.out.println("i is less than two");

case 2:

System.out.println("i is less than three");

case 3:

System.out.println("i is less than four");

case 4:

System.out.println("i is less than five");


System.out.println();

}

}

}

Output:

i fis less than one

i is less than two

i is less than three

i is less than four

i is less than five

i is less than two

i is less than three

i is less than four

i is less than five

i is less than three

i is less than four

i is less than five

i is less than four

i is less than five

i is less than five

Execution will continue into the next case if no break statement is present.

You can have empty cases, as shown in this example:

switch(i) {

case 1:

case 2:

case 3: System.out.println("i is 1, 2 or 3");

break;

case 4: System.out.println("i is 4");

break;

}
JAVA for Beginners

Riccardo Flask 45 | P a g e

Nested switch

switch(ch1) {

case 'A': System.out.println("This A is part of outer

switch.");

switch(ch2) {

case 'A':

System.out.println("This A is part of inner

switch");

break;

case 'B': // ...

} // end of inner switch

break;

case 'B': // ...

 Mini-Project – Java Help System (Help.java)

Your program should display the following options on screen:

Help on:

1. if

2. switch

Choose one:

To accomplish this, you will use the statement

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.print("Choose one:

Next, the program obtains the user’s selection

choice = (char) System.in.read();

Once the selection has been obtained, the display the syntax for the selected statement
switch(choice) {

case '1':

System.out.println("The if:\

System.out.println("if(condition)

System.out.println("else statement;");

break;

case '2':

System.out.println("The switch:\

System.out.println("switch(

System.out.println(" case

System.out.println(" statement

System.out.println(" break;");

System.out.println(" // ...");

System.out.println("}");

break;

default:

System.out.print("Selection not found.");

}

Complete Listing

/*

Project 3-1

A simple help system.

*/

class Help {

public static void main(String args[])

throws java.io.IOException {

char choice;

System.out.println("Help on:");

System.out.println(" 1. if");

System.out.println(" 2. switch");

System.out.print("Choose one: ");

choice = (char) System.in.read();

System.out.println("\n");

switch(choice) {

case '1':

System.out.println("The if:\n");

System.out.println("if(condition) statement;");

System.out.println("else statement;");

break;

case '2':

System.out.println("The switch:\n");

System.out.println("switch(expression) {");

System.out.println(" case constant:");

System.out.println(" statement sequence");

System.out.println(" break;");

System.out.println(" // ...");

System.out.println("}");

break;

default:

System.out.print("Selection not found.");

}

}

}
ginners

Riccardo Flask 48 | P a g e

Sample run:

Help on:

1. if

2. switch

Choose one: 1

The if:

if(condition) statement;

else statement;

The for Loop

Loops are structures used to make the program repeat one or many instructions for ‘n’ times as

specified in the declaration of the loop.

The for Loop can be used for just one statement:

for(initialization; condition; iteration) statement;

or to repeat a block of code:

for(initialization; condition; iteration)

{

statement sequence

}

 Initialization = assignment statement that sets the initial value of the loop control variable,

(counter)

 Condition = Boolean expression that determines whether or not the loop will repeat

 Iteration = amount by which the loop control variable will change each time the loop is

repeated.

 The for loop executes only/till the condition is true

Example: using a ‘for’ loop to print the square roots of the numbers between 1 and 99. (It also

displays the rounding error present for each square root).

// Show square roots of 1 to 99 and the rounding error.

class SqrRoot {

public static void main(String args[]) {

double num, sroot, rerr;

for(num = 1.0; num < 100.0; num++) {

sroot = Math.sqrt(num);

System.out.println("Square root of " + num +

" is " + sroot);

// compute rounding error

rerr = num - (sroot * sroot);

System.out.println("Rounding error is " + rerr);

System.out.println();

}

}

}

‘For’ loop counters (loop control variables) can either increment or decrement,

// A negatively running for loop.

class DecrFor {

public static void main(String args[]) {

int x;

for(x = 100; x > -100; x -= 5)

System.out.println(x);

Comments