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:


if( a > b )
{
    System.out.println( "a is greater than b.");
}
else if ( a <= b )
{
    System.out.println( "a is lesser or equal than b.");
}

In this example a and be can have any value, for example a could be 2 and b could be 3.5. Now we have seen the different uses of if and else in java conditionals. Don't forget to use two equal (=) symbols when writing a conditional expression, otherwise it wouldn't be a comparison but a declaration.

Also, we can create more complex statements by comparing not only one but many expressions at the same time. The way to do this is by using the symbols && and ||


  • && : Evaluates if two or more expressions are true.
  • || : Evaluates if at least one of two or many expressions is true.


For example if we want to now if a given variable x is greater than five AND lesser than 10:


if( x > 5 && x < 10 )
{
    System.out.println( "x is greater than 5 AND lesser 10.");
}
else
{
    System.out.println( "x is not greater than 5 AND lesser 10.");
}

Or for example if we want to know if a given String variable name is equals to "Tom" OR it is equals to "Fabienne"

if( name.equals("Tom") || name.equals("Fabienne") )
{
    System.out.println( "The variable name equals Tom OR equals Fabienne");
}
else
{
    System.out.println( "The variable name is neither equals Tom nor equals Fabienne");
}

Switch-Case conditionals in Java

Let's see an example of these conditionals:

int apples = 5;
switch (apples) 
{
  case 0: 
    System.out.println( "You have no apples.");
    break;
  case 1: 
    System.out.println( "You have 1 apple.");
    break;
  case 2: 
    System.out.println( "You have 2 apple.");
    break;
  default: 
    System.out.println( "You have 3 or more apples.");
}

This kind of conditional can be very useful in some cases that you want to make sure the exact value of a variable. I personally prefer to use the if-else conditional because it is easier to read and faster to write (you don't have to write all those case/break).

Now let's see some a more complex example:

Let's say we have a small business and we sell some items. There are 6 items and three different categories. These are the items:
Category: games. Items: Play Station, Xbox.
Category: computers. Items: PC, Mac.
Category: smartphones. Items: Samsung, iPhone.

First you want to know what was the best selling item, and then, you want to know if any item in the smartphones category was the best selling item.

Here is the current data of sold items:

int playStation = 6;
int xbox = 8;
int computer = 9;
int mac = 6;
int samsung = 10;
int iphone = 5;

Now let's verify what item was the best selling:

if(playStation>=xbox && playstation>=computer && playStation>=mac && playStation>=samsung && playStation>=iphone)
{
    System.out.println( "The Play Station was the best selling item.");
}
else if(xbox>=computer && xbox>=mac && xbox>=samsung && xbox>=iphone)
{
    System.out.println( "The Xbox was the best selling item.");
}
else if(computer>=mac && computer>=samsung && computer>=iphone)
{
    System.out.println( "The Computer was the best selling item.");
}
else if(mac>=samsung && mac>=iphone)
{
    System.out.println( "The Mac was the best selling item.");
}
else if(samsung>=iphone)
{
    System.out.println( "The Samsung was the best selling item.");
}
else
{
    System.out.println( "The iPhone was the best selling item.");
}

Finally, let's verify if and item in the smartphones category was the best selling item:

if( (samsung>=playStation && samsung>=xbox && samsung>=computer && samsung>=mac ) || ( iphone>=playStation && iphone>=xbox && iphone>=computer && iphone>=mac ))
{
    System.out.println( "The smartphones category was the best selling category.");
}

In short the final program would look like this:
Note: I have created two methods: one for best selling item, and another one to verify if Smartphones is the best selling category. Thus, I have put the values of each sale as attribute to be able to use them in the different methods.


private static int playStation = 6;
private static int xbox = 8;
private static int computer = 9;
private static int mac = 6;
private static int samsung = 10;
private static int iphone = 5;

static void printBestSellingItem()
{
    if(playStation>=xbox && playstation>=computer && playStation>=mac && playStation>=samsung && playStation>=iphone)
    {
        System.out.println( "The Play Station was the best selling item.");
    }
    else if(xbox>=computer && xbox>=mac && xbox>=samsung && xbox>=iphone)
    {
        System.out.println( "The Xbox was the best selling item.");
    }
    else if(computer>=mac && computer>=samsung && computer>=iphone)
    {
        System.out.println( "The Computer was the best selling item.");
    }
    else if(mac>=samsung && mac>=iphone)
    {
        System.out.println( "The Mac was the best selling item.");
    }
    else if(samsung>=iphone)
    {
        System.out.println( "The Samsung was the best selling item.");
    }
    else
    {
        System.out.println( "The iPhone was the best selling item.");
    }
}

static void isSmartPhonesBestCategory()
{
    if( (samsung>=playStation && samsung>=xbox && samsung>=computer && samsung>=mac ) || ( iphone>=playStation && iphone>=xbox && iphone>=computer && iphone>=mac ))
    {
        System.out.println( "The smartphones category was the best selling category.");
    }
}

public static void main(String[] args) 
{
    printBestSellingItem();
    isSmartPhonesBestCategory();
}


In this final example, we have included the key word void. It is actually not a data type, but it means that nothing will be returned. (In this case, we printed the message directly from the methods, so we didn't need to return anything.

Please feel free to comment and ask if you have any questions, your feedback will be greatly appreciated.

8 comments:

  1. Interesting read, I do a little c++ programming myself.

    ReplyDelete
  2. Nice guides man, keep up the good work!

    ReplyDelete
  3. Nice guides! I just started with java and these are helping out alot!

    ReplyDelete
  4. Keep up the good work. Nice tutorial, helped me a lot.

    ReplyDelete
  5. This was very helpful. Thank you.

    ReplyDelete
  6. i'm learning something like this but in C :)

    ReplyDelete