Java supports two control statements:
if (condition)
statement;
Here condition is a Boolean expression. If the condition is true then the statement right after the "if" statement will be executed otherwise java compiler will bypass that statement and move to the other statements.
Syntax of switch:
switch (variable name)
{
case 1:
statement 1;
.
.
.
statement n;
break;
case 2:
statement 1;
.
.
.
statement n;
break;
.
.
.
.
case n;
statement(s);
break;
default:
statement;
}
Here "variable name" shows the variable whom you want to compare with the values defined by "case(s)". If you are comparing numeric values then simply write them after writing "case" and then colon. Once you have done, write your statement(s) you want to execute. You must have noticed the "break" statement. It is used to get out of the "switch" body and prevents other statements to be executed directly.
Another new statement "default" is used here. It is used at the end of the switch body. Suppose if all the cases you defined above do not mach with the value of the variable you are comparing then the statement right after "default" will be executed.
- If statement
- Switch statement
if (condition)
statement;
Here condition is a Boolean expression. If the condition is true then the statement right after the "if" statement will be executed otherwise java compiler will bypass that statement and move to the other statements.
Syntax of switch:
switch (variable name)
{
case 1:
statement 1;
.
.
.
statement n;
break;
case 2:
statement 1;
.
.
.
statement n;
break;
.
.
.
.
case n;
statement(s);
break;
default:
statement;
}
Here "variable name" shows the variable whom you want to compare with the values defined by "case(s)". If you are comparing numeric values then simply write them after writing "case" and then colon. Once you have done, write your statement(s) you want to execute. You must have noticed the "break" statement. It is used to get out of the "switch" body and prevents other statements to be executed directly.
Another new statement "default" is used here. It is used at the end of the switch body. Suppose if all the cases you defined above do not mach with the value of the variable you are comparing then the statement right after "default" will be executed.
To see a program click here!
No comments:
Post a Comment