Search This Blog

If you have any problem or question please write in the comments. We will try to solve and send you the solution. Not just that we will also post your problems solution on our blog.

Sunday, 12 June 2011

Control/decision making statements of java

Java supports two control statements:

  • If statement 
  • Switch statement
You can make easily with the help of these statements Syntax of "if" statement is:

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