A boolean expression in java is any expression that evaluates to true or false. For example, x>1 is either true or false. This is a valid boolean expression in java given that x is a declared variable. The most common boolean expressions checks for equality. For example, what if given a variable x, you want to check if that variable is a certain value? That is where the equality operators come in. The two equality operators are == (equals) and != (not equals).

boolean result = (1 == 2);
boolean result2	= (1 == 1);

In the two lines above, the expression to the right of the assignment operator ( 1 equal sign ) is a boolean expression so it will evaluate to true or false value based on the result of the equality check. Because 1 does not equal 2, the first expression evaluates to false and the second evaluates to true. When you are dealing with more intensive calculations, you will not know actual literal values contained in variables. Remember the whole point of variables is to allow the program to handle variability. Let's write a more general version of the two statements above. First, assume there is an int variable x that has been declared and assigned an initial value. You do not know the value contained in x.

boolean result = ( x == 2);
boolean result2	= ( x != 1);

We do not know what the value of x is, but we can simply check with the equality operators. You can also check to see if x is in a given range of values using relational operators less than (<), greater than (>), less-than-equal-to (<=), greater-than-equal-to (>=).

boolean result = ( x >= 0);
boolean result2	= ( x < 0 );

In the two lines above, the relational operators read as you would in your math class. It is asking the question is x greater-than-or-equal to 0? Is x less than 0? Based on the actual value of x the expressions will evaluate as true or false. That result is then assigned to be the value of the variables result and result2. Assume that x has been declared and assigned the int value of 7. Determine if each of the following boolean expressions evaluate to true or false.

x == 7
x != 1
x <=7
x >-3
x < 101
x <= 30 

Boolean expressions are a big part of if statements. An if-statement is commonly referred to as a conditional or a blocking statement. The keyword if is a reserved keyword. Much like int, double and boolean, it is part of the java language. Java keywords cannot be used as variable names. This is because Java interprets them differently and expects a particular syntax as soon as it sees them.

if Statement

if statements are often used in methods. As a matter of fact, what you run your code as we have been doing, your code was inside a method, the main method. For now, consider the following examples separate from a method. Assume you are given an int variable x. Let's write code that will print a different message on the console depending on what is stored in x.

The line of code in the body of the if statement will only run if the value of x is 18. This is often times why it is referred to as a blocking statement. The body of the if statement is blocked from executing unless the condition is met (evaluates to true). Let's do some more.

int x = 7;
if(x == 18) System.out.print ("WHAT");
if(x >= 0) System.out.print("WHAT");
if(x <= 100) System.out.print("WHAT");
if(x != 100) System.out.print("WHAT");

Given the block of code above showing the 4 if-statements, what will be printed to the console if x is 7? "WHAT" Twill be printed 3 times! This is because the if-statements are independent of one another. Even though one if-statement condition is met, the rest of the if statements also run and have their condition checked. The only if statement whose condition will not evaluate to true, given that x is equal to 7, is the first one where it is asking if x is equal to 18. Recall that double equal signs are an equality check. It is not an assignment. Since x is greater-than-or-equal-to 0 and x is-less-than-or-equal-to 100 and x is-not-equal-to 100, the other three if statements' bodies execute.

Practice

Let's practice the reading specification of a behavior and then producing the Java if-statements and expressions necessary to produce the behavior.
Specification: Given an int variable temp, which holds a number between 0 and 165 inclusive (in Fahrenheit), complete the program which will determine the state of a String variable so that its value is set to "Rare", "Medium Rare", "Medium", or "Well Done". By default, it should say "Tough Steak". The temperature required to be in each category is shown below.

String doneness = _______________; //default value
if( _______________________){
   doneness = "Rare"; //temp is within <= 120 inclusive
}
if( temp == 130){     //medium rare
   _______________________
}
else _______________________{ // medium is 140 _______________________ } else{
_______________________
}

Solution:

String doneness = "Tough Steak"; //default value
if(temp <= 120){
    doneness = "Rare"; //temp is within <= 120 inclusive } if(temp == 130){     //medium rare
    doneness = "Medium Rare"; }else if(temp == 140){ // medium is 140
    doneness = "Medium"; }else{
  doneness = "Well Done";
}

Solution

The section of code above can easily be placed in some block of code in your program. You can actually put it in a method. Why could this be a good idea? If you created a method then you would be able to check for doneness for any temperature value at any number of times. Let's see what it might look like for a void method.
//prints if steak is rare
public void isRare(int temp){
    if(temp <= 135){ System.out.println("Steak is Rare");}
}

The void method above does not return any result, but it does output to the console. Remember not to confuse print with the console for a non-void method! Take a look at the parameter of the method, temp. This means that when someone uses the method the value is passed to this method and within the method, the value is referred to as the variable temp. This is similar to the use of the Math methods. You could call upon the method by its name with a given temperature. ie isRare(30), isRare(155), isRare(165)

In the example above, the method isRare is part of the Steak class. This means that you need a Steak object in order to call upon its available public method. Previously, you were asked to invoke instance methods of objects as well as static methods like those from the Math class. instance methods require an object to exist while static methods only require you to mention the name of the class in which the method exists. In this unit, you are asked to produce code that helps define what it means to be a function based on specifications. Let's add an additional function to the Steak class. The method header is below.

The specifications are sole to print "Steak is well done" if-and-only-if the temperature (given as a parameter to the method) is >= 165. Write the required if statement(s) and java expression(s) to satisfy the specification of the method.

// prints "Steak is Well Done" if tempParameter >= 165
public void isWellDone(int tempParameter){
    //write your code 
______________________ }

Sometimes you may decide to write a binary decision. Based on how a boolean expression evaluates, either true or false, there is a set of code that will execute. When you add an else branch to an if statement you are guaranteeing that some block of code will execute based on the condition being true or false. Assume there is an int variable x of some unknown value. The if-else statement below can describe if the value is negative or positive.

The code above when run will always result in a printout to the console. If the boolean expression in the condition of the if statement evaluates to true then it prints "x is negative" else it prints "x is positive". This is also known as a two-way selection because of the two statements that may execute depending on the boolean expression.

The other version of the if statement you will encounter is a multi-way selection. This is because there may be multiple conditions that can be met, although still, only one branch of the entire conditional statement will run.

In the conditional tree shown above, there are four possible outputs. Only one of the print statements will run at any point. As soon as one condition is met (one boolean expression), the structure runs the body for that part of the tree then breaks out to the very end of the structure. If the value of x, is 0 then it prints D. If the value of x is 5, it prints C.

What happens if you want an if statement condition to depend on more than one condition? Or could you combine multiple conditions in an if-else-if tree if those conditions perform the same actions? Let's take a look!

Short Circuits

If you have multiple conditions that are strung together with && then you must evaluate the expression from left to right. Immediately after you find a condition that is false you should stop checking the expression. This is because given the AND boolean operator (&&) all conditions must be true. As soon as you find one that is not you know the entire thing is false. Given x = false, y = true and z = true:
x && y && z 
The expression above evaluates to false right away because x is false so the entire statement cannot be true. the AND boolean operator requires all of the operands to be true. Note that you do not need to explicitly write x == true && y== true && z == true  because of the fact that the variables are booleans. For OR (||) as soon as you find a condition that is true you can stop checking since for an OR statement only one of the statements needs to be true. 

Given x = false, y = true and z = true, what is
y || x || z
The expression above evaluates to true because the first operand is true. You only need one of the operands to be true.

The following are examples of boolean expressions and their results evaluated. Assume x = 0, y = 2 and z = true.

x == 0 || y >30;            //true
x !=0 && y !=2;             //false
z || y == 0;                //true
x == 1 || y == 3 || z;      //true

Truth Tables

Below is the truth table for the OR (||) operator. Given two boolean expressions, OR returns true if just one of the expressions is true.

ex: a || b 

a
b
a || b
false
false
false
false
true
true
true
false
true
true
true
true


Finally, you can add the not operator anytime you want the opposite of a boolean expression. Let's see how we can use it to check the content of a String variable str.

The syntax is very particular however in that every part of the compound boolean expression must be a valid boolean expression. You cannot simply write x==1, 20, || -5. Every boolean expression separated by the OR operator must be a valid java expression. Finally, commas cannot be used to separate different conditions. Commas do not tell java how to combine multiple Boolean expressions. Checking to see if the value of the variable is within a given range makes good use of the and operator. For example, what if you want to check if x is greater than 0 but less than 20?

In the conditional tree above you can see that the print to the console is the same if x is equal to 1, 20, or -5. Why not just combine these into one boolean expression? Boolean operators help with just that. The three Boolean operators you're expected to know are the AND (&&), OR (||), and NOT (!). The use of these boolean operators is similar to how you would combine two conditions in everyday life, but let's examine them further. In the tree shown above, in English you could just say if x is equal to 1, 20 OR -5 then print Hi otherwise print Goodbye. In code, this looks like the following.

It can be useful to know how to manipulate boolean expressions to find equivalent expressions. Sometimes, finding equivalent expressions will simplify the code and logic of your program. In this section, we will go over De Morgan's law as a way to find equivalent boolean expressions.

Distributing ! (NOT) operator

What is another way of writing! ( a && b ) ? Let's say we are trying to buy a new laptop. Assume that a = "expensive" and b = "slow".

!(a && b)
The statement above then says NOT ( expensive and slow).

Let's distribute the NOT operator and see what happens.

!a || !b

What happened? Why did the && (AND) change to || (OR)?

Think about it, is it still equivalent if you said not expensive and not slow? Is that the same as saying not expensive and slow?

When it is written as! (a && b), it means that the expressions are false when a and b are both true. In all other cases, it is true. This is equivalent to !a || !b. Anytime a or b is false, the statement evaluates to true. The table below shows you the result of each expression for all possible values of a and b.

a
b
!a || !b
false
false
true
false
true
true
true
false
true
true
true
false

Distributing ! operator across ||

The same logic can be applied for distributing the ! (NOT) operator across boolean expressions joined together with || (OR).
! (a || b) is equivalent to !a && !b
As a shortcut, to distribute !(NOT) across expressions, you need to change the && to || and vice versa.

Other examples of this are below for compound boolean expressions
!(a || b || c) && d => !a&&!b&&!c&&d
! ( ( a && b) || d) => !(a&&b) && !d => !a || !b && !d
! ( (a&&b) && (d || e) => !(a&&b) || !(d||e) => !a || !b || !d && !e

It is simple to compare numeral and boolean types in java using the equality operator, ==. When you're comparing objects it is not quite as simple! Consider the following block of code.
String str1 = "Hello"
String str2 = "Hello"
String str3 = "hello"
String str4 = str1; 

equals() Method

The method to compare objects is equals. The parameter would be the object you are comparing to the object from which you are calling the method. This is an instance method so you need an object to invoke it.

What would happen if we run System.out.println(str1.equals(str2)); ? The output of this is true because a String in java implements the equals method where it is true if every character is the same where capitalization matters. In this case, str1 and str2 both contain the same exact set of characters in the same order.

What would happen if we run System.out.println(str1.equals(str3));? If you guessed it would print false then you would be correct. The equals method for String objects compares each character where order and case matter (upper vs lower case).

What would happen if we run System.out.println(str1 == str2)?

Finally, what will happen if we run System.out.println(str4.equals(str3))?