CONTROL STATEMENTS:
IF:
class IfSample
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
40
if(x < y)
[Link]("x is less than y");
x = x * 2;
if(x == y)
[Link]("x now equal to y");
x = x * 2;
if(x > y)
[Link]("x now greater than y");
// this won't display anything
if(x == y)
[Link]("you won't see this");
}
}
Output:
x is less than y
x now equal to y
x now greater than y
IF-ELSE:
if (condition) {
// codes in if block
}
else {
// codes in else block
}
EX:
class Main {
public static void main(String[] args) {
int number = 10;
// checks if number is greater than 0
if (number > 0) {
[Link]("The number is
positive.");
}
// execute this block
// if number is not greater than 0
else {
[Link]("The number is not
positive.");
}
[Link]("Statement outside if...else
block");
}
}
Output
The number is positive.
Statement outside if...else block
IF ELSE IF STATEMENT:
if (condition1) {
// codes
}
else if(condition2) {
// codes
}
else if (condition3) {
// codes
}
.
.
else {
// codes
}
class Main {
public static void main(String[] args) {
int number = 0;
// checks if number is greater than 0
if (number > 0) {
[Link]("The number is
positive.");
}
// checks if number is less than 0
else if (number < 0) {
[Link]("The number is
negative.");
}
// if both condition is false
else {
[Link]("The number is 0.");
}
}
}
Output
The number is 0.
SWITCH STATEMENT:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
public class SwitchVowelExample {
public static void main(String[] args) {
char ch='O';
switch(ch)
{
case 'a':
[Link]("Vowel");
break;
case 'e':
[Link]("Vowel");
break;
case 'i':
[Link]("Vowel");
break;
case 'o':
[Link]("Vowel");
break;
case 'u':
[Link]("Vowel");
break;
case 'A':
[Link]("Vowel");
break;
case 'E':
[Link]("Vowel");
break;
case 'I':
[Link]("Vowel");
break;
case 'O':
[Link]("Vowel");
break;
case 'U':
[Link]("Vowel");
break;
default:
[Link]("Consonant");
}
}
}
OUTPUT-Vowel