Java Lesson 4: IF-ELSE statements & Logical/Comparison Operators

Advertisements

Hello everybody,

It’s Michael, and today’s post will be on if-else statements and logical/comparison operators in Java. If-else statements allow your program to choose between two or more alternative actions.

Why are if-else statements so important? Well, with Java programs, as in everyday life, things can go several different ways. Let’s say you just took a final exam for a college class. Depending on how you did on that exam, your grade can come out one of five ways (A, B, C, D, or F). The same sort of thinking applies to programming, as there can be several different actions a program can perform depending on certain scenarios (like if an int is greater than/less than/equal to a certain amount).

Let’s demonstrate using a program example (I had to copy and paste the code since you can’t see all of it from a screenshot):

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println (“Please enter a number: “);
double temperature = sc.nextDouble ();
System.out.println (“C or F: “);
String unit = sc.next();
double temp;

if (“C”.equals(unit))
{
temp = (1.8*temperature)+32;
System.out.println (“The temperature is ” +temp+ ” degrees Farenheit”);
}

else if (“F”.equals(unit))
{
temp = (temperature-32)*0.56;
System.out.println (“The temperature is ” +temp+ ” degrees Celsius”);
}

else
System.out.println(“Not a valid answer”);
}

}

This program is a temperature unit converter; the user enters a number and a “C” or “F” (for Celsius or Fahrenheit) and, depending on what letter was entered, converts the temperature from Celsius to Fahrenheit or vice versa.

I want to clarify that there is a difference between else if and else. Else if acts as another if statement; you would use else if if your program was trying to test two or more conditions, such as whether a “C” or “F” was typed. The else statement would come at the very end of your code since that would be the statement that executes should neither of the if/else if conditions be true; the output I used for the else statement would only display if neither a “C” nor an “F” was typed.

  • Always use .equals for String variables such as these. Don’t use =.
  • You need to use brackets if you if or else if statements use more than one line of code. If you only need one line of code, you don’t need the brackets.

Let’s try inputting a number:

run:
Please enter a number:
19
C or F:
C
The temperature is 66.2 degrees Farenheit
BUILD SUCCESSFUL (total time: 17 seconds)

I entered 19 and C, meaning I wanted to find out what 19 degrees Celsius was in Fahrenheit. I got 66.2, which means that 19 degrees Celsius is equal to 66.2 degrees Fahrenheit.

Now let’s see what happens when I don’t type a “C” or an “F”:

run:
Please enter a number:
45
C or F:
W
Not a valid answer
BUILD SUCCESSFUL (total time: 8 seconds)

I typed 45 and W and as a result, “Not a valid answer” displayed (which is the output I had set to display if neither “C” nor “F” was typed).

For those who’d like a video demo of the program, here it is-Temperature converter.

Now let me introduce some new concepts that perfectly relate to if and else if statements-comparison and logical operators.

Comparison operators are pretty self-explanatory, as they are used to compare two things (usually testing a variable and a value). If you know basic algebra, you’d be familiar with most of these:

  • == is “equal to” (remember to use .equals for Strings)
  • != is “not equal to”
  • > is “greater than”
  • >= is “greater than or equal to”
  • < is “less than”
  • <= is “less than or equal to”

Logical operators are similar to comparison operators since both compare statements. However, comparison operators are only used for single boolean statements, such as (temperature > 70) while logical operators are used for groups of boolean statements, such as (temperature >= 60) && (temperature <= 80).

Here are the three main logical operators:

  • &&-AND
  • ||-OR
  • !-NOT

OK, so even though I said logical operators are used for groups of boolean statements, the NOT operator is more for single boolean statements, such as !(temperature > 70)-meaning that you’re looking for temperatures that aren’t greater than 70 degrees. You can, however, also use the NOT operator for groups of boolean statements, such as (!(temperature >= 50) && (temperature <= 0))-meaning that you’re looking for temperatures that aren’t between 0 and 50 degrees.

Here’s the one takeaway with the NOT operator-it negates boolean statements (whether an individual statement or groups of statements). In other words, it essentially contradicts whatever is in the statement(s).

Now, one more thing I want to cover regarding logical operators-the truth table. The truth table doesn’t involve any coding, rather it’s a helpful guide with regards to boolean statements in your program. The truth table compares two boolean statements, looks at the values of each statement (whether they are true or false), and based on the values of each individual statement, returns true or false for that pair of statements. Here’s the table below:

When dealing with AND, both statements in a pair have to be to true in order for the statement pair to be true. If one or both statements are false, then the statement pair returns false. With OR however, only one statement has to be true for the pair to be true, but if both statements are false, then the pair is false. And as I mentioned earlier, NOT contradicts boolean statement(s), so if you not right by a boolean statement pair that is true, then that pair is false (and vice versa).

Let’s test this logic with an example program:

27jan capture1

In this program I have two boolean statements (5 > 7) and (12 < 16). I then use System.out.println to test whether the statement pair greaterThan && lessThan is true or false. Since I used AND and one of the statements is false-greaterThan-both of the statements are false. Remember with AND, if one of the statements are false, then both are false.

Now let’s apply our knowledge of truth tables to more than two boolean statements:

When dealing with more than two boolean statements, logical evaluation is done from left to right. The Java compiler would first read the first pair of statements-greaterThan && lessThan-to evaluate whether that statement pair is true or false (it’s false). The compiler then takes the false result and compares it with the subtraction statement, which is true (thus statements 1-3 are collectively true). Finally, the compiler takes the collective true result from statements 1-3 and compares it with the multiplication statement, which is false. But, since OR is being used to compare the statements, you only need 1 true statement to result in true, which is the case here. After analyzing all 4 statements, the compiler states that the 4 statements together are collectively true.

Now, let’s analyze a program with several if options. In this program, you would type in a year, and the program will tell you what generation you belong to; keep in mind that the dates provided are just approximations, as different sources use different dates to mark the beginning and end of a generation. Here is the code:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println (“Enter your birth year: “);
int year = sc.nextInt();

if (year >= 1900 && year <= 1928)
{
System.out.println(“You are part of the Greatest Generation”);
}

else if (year >= 1929 && year <= 1945)
{
System.out.println(“You are part of the Silent Generation”);
}

else if (year >= 1946 && year <= 1965)
{
System.out.println(“You are a Baby Boomer”);
}

else if (year >= 1966 && year <= 1981)
{
System.out.println(“You are a Gen-Xer”);
}

else if (year >= 1982 && year <= 2000)
{
System.out.println(“You are a Millenial”);
}

else if (year >= 2001 && year <= 2019)
{
System.out.println(“You are a Gen-Zer”);
}

else
{
System.out.println(“Invalid input”);
}
}

}

Please note that you will get a certain output (i.e. “You are a Millennial”) if both conditions are true; “You are a Millennial” will only print out if the year you typed is between 1982 and 2000.

Now let’s use the year 1946 (President Trump’s birth year):

run:
Enter your birth year:
1946
You are a Baby Boomer
BUILD SUCCESSFUL (total time: 3 seconds)

As you can see, 1946 corresponds to Baby Boomer, meaning President Trump is a Baby Boomer.

Now let’s try 1996 (my birth year):

run:
Enter your birth year:
1996
You are a Millenial
BUILD SUCCESSFUL (total time: 3 seconds)

According to the program, I am a millennial.

For those who want a video demo of the program, check this out-Generation program.

Now, a concept you should know that ties in with the material in this post is precedence. Precedence is similar to order of operations in the sense that both concepts involve doing things in a certain order. However, while order of operations just deals with arithmetic and exponents, precedence deals with arithmetic, comparison, and logical operators. With precedence, there is a certain order which the compiler evaluates statements with multiple arithmetic/comparison/logical operators. Here’s a handy guide:

  • First-the operators +,-,++,–, and !
    • The ++ and — operators represent incrementing and decrementing, respectively. These operators basically increase or decrease (or increment and decrement) a number by 1; you’ll see them more when I cover loops.
  • Second-the operators *, / and %
  • Third-the operators + and –
    • The plus and minus signs that take highest precedence actually refer to positive and negative numbers, while the one that are 3rd in precedence order actually refer to addition and subtraction
  • Fourth-the operators <, >, <= and >=
  • Fifth-the operators == and !=
  • Sixth-the operator &
  • Seventh-the operator |
  • Eighth- the operator &&
  • Ninth-the operator ||
    • The difference between the single & and || and the double && and || is that the former two are known as bitwise operators, which analyze data of types int, long, short, char, and byte bit by bit.
    • Check out this forum to learn more about bitwise operators-Bitwise Operators.

Keep in mind that parentheses ALWAYS take highest precedence (yes even higher than the operators listed as highest precedence). Any statements inside the parentheses are evaluated in order of operator precedence; if you’re dealing with parentheses-within-parentheses, the expression in the innermost set of parentheses is evaluated first, after which the compiler will work its way outward.

Here’s a series of statements; can you guess the result (true or false) based on precedence:

temperature = 44;

temperature – 2 < 32 || (temperature + 5 != 55) && temperature / 2 < 30

If you said true, you are right. Let me break it down:

  • The statement temperature + 5 != 55 is evaluated first, as it is in parentheses. It is true.
  • The next statement to be evaluated is temperature / 2 < 30, as it right by the && sign, which takes higher precedence than ||. That statement is also true, so that results, along with the true statement in parentheses, makes for a true statement pair.
  • The last statement to be evaluated is temperature - 2 < 32, since it’s right by the || sign. Even though this statement is false, the true statement pair to its right makes the whole group of statements collectively true (remember with OR, only one true makes for a collective true).

Thanks for reading,

Michael

Leave a ReplyCancel reply