Boolean expressions evaluate to a Boolean value (true, false
).
Comparing primitives and reference values using relational operators:
==, !=, <, >, <=, >=
Examples:
a=5;
b=3;
Boolean x=(a!=b); // x will initialize to false as 3 does not equal 5.
return password.equals("123"); //returns true if the value in the password variable equals "123".
Task: Practice writing Boolean expressions (logical tests) here and evaluating Boolean expressions here.
if (logical test)
do this stuff;
The code under "do this stuff" will only execute if the logical test evaluates to true.
Task: Practice the if statement syntax here.
if (logical test)
do command A;
else
do command B;
If the logical test evaluates to true, command A will be executed, otherwise command B will be executed. Remember to use curly brackets in case you have more than one command under the if or else branch, e.g.:
if (logical test)
{
do command A;
do command B;
}
else
{
do command C;
do command D;
}
Task: Check your understanding of if-else statements here, here, here, here, and here .
if (logical test 1)
do command A;
else if (logical test 2)
do command B;
else if (logical test 3)
do command C;
...
else
do command X;
If logical test 1 evaluates to true, then command A is executed; otherwise logical test 2 is performed - if it evaluates to true, then command B is executed, otherwise, command C is executed.
Task: Consolidate your understanding of one-way selection, two-way selection and multi-way selection by doing the following Runestone academy units: 3.2 (try the Magic 8 Ball challenge), 3.3, 3.4.
Complex conditionals are either nested if statements or using boolean operators (&&, ||, !
) in logical tests.
Nested if statement example:
if (username=="user1")
{
if (password="123")
return true;
}
else
return false;
The same program implemented using boolean operators instead of a nested if statement:
if (username=="user1" && password=="123")
return true;
else
return false;
Task: read on Compound Boolean expressions on Runestone Academy and do the tasks on the page.
false
for the whole expression to evaluate as false
. The second condition does not get evaluated.true
for the whole expression to evaluate as true
. The second condition is not evaluated.Main points:
Task: Read on DeMorgan's Laws and do the tasks on the page on Runestone Academy
==
and !=
operators.!=null
or ==null
equals()
method if the class features such method.Task: Read more on comparing String objects and do the task on the page on Runestone Academy
Task:
What will be the output of the following program snippet?
public class Main
{
public static void Main()
{
String s1 = new String("Hi There");
String s2 = new String("Hi There");
String s3 = s1;
s1="hello";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1 == s3);
System.out.println(s2.equals(s3));
}
}