Thursday, August 4, 2011

Basic if , if-else, switch statements

if Statement

Syntax:

if (condition)
{
...
java statements;
...
}

Example:

// == results in a Boolean value true or false
if (RandomNumber % 2 == 0)
{
System.out.println("Even");
}


If-Else Statement

Syntax:

if (condition)
{
java_statements_for_true_condition;
}
else
{
java_statements_for_false_condition;
}

Example :

if (a % 2 == 0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}

You can eliminate the else statement when using the Boolean variable.

Example:

Typical if-else statement:

if (hungry)
{
System.out.printIn (" Go find food !! ")
}
else
{
System.out.printIn (" Continue working !! ")
}

Alternatively to eliminate the else statement by using the not operator

if (!hungry)
{
System.out.printIn (" Continue working !! ")
}

Switch Conditional Statement

Syntax:

switch (expression) {
case value1:
statements_for_value1;
break;
case value2:
statements_for_value2;
break;
case value3:
statements_for_value3;
break;
default:
statements_for_any_other_value;
}

Example:
switch (n)
{
Case 1:
System.out.printIn("I miss you!!");
break;
Case 2:
System.out.printIn("I care for you!!");
break;
Case 3:
System.out.printIn("I love you!!");
break;
default:
System.out.printIn("Best friends forever!!");
}

No comments:

Post a Comment