Showing posts with label switch. Show all posts
Showing posts with label switch. Show all posts

Monday, April 16, 2012

Java Tutorial & Lesson 6 - Making decisions with Conditionals


How to use Java conditionals if and switch


Conditionals are a very important part in any program language. Very useful particularly when you have many options and have to let the computer choose one of them (making a decision) before operating. These kind of computer-decisions are called conditional expressions, and they are usually an equality or inequality that can be evaluated to either true or false.


If-else conditionals in Java


For example, an equality evaluation in Java goes like this:

if( a == b ) //This expressions evaluate if a is equals to b.
{
    System.out.println( "a and b are the same.");
}
else //If they are not equal, the message inside the "else" will be printed.
{
    System.out.println( "a and b are different.");
}

This can also be written like this:

if( a == b )
{
    System.out.println( "a and b are the same.");
}
else if( a != b ) //In Java, != is the opposite of ==
{
    System.out.println( "a and b are different.");
}

The last two expressions will show the same result. Now, an inequality evaluation in Java goes like this: