What are logical operators
-Has three main logical operators that work with boolean values
-&&, ||, !
&&
-Meaning: AND
-It connects two Boolean expressions into one. Both expressions must be true for the overall expression to be true
Example:
expression 1 true, expression 2 true expression 1 && expression 2 therefore is true
Example:
expression 1 true, expression 2 false expression 1 && expression 2 therefore is false
The || operator
-Means OR
-The logical OR (||) combines two boolean expressions and the result is true if at least one of the expressions is true
-It is false only when both expressions are false
The ! Operator
-Means: NOT
-The ! operator reverses the truth of a Boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true
What is short circuiting
-Short circuiting means java stops checking a logical condition early if it already knows the answer
-happens with && and ||
example for &&:
if (x > 0 && y > 0)
Java checks the first condition and if it is false, && anything will always be false. For &&, java stops when it sees false first
example for ||:
if (x>0 || y> 0)
Java checks the first condition and if its true || anything is always true. Java stops when it sees true first
What do you use when you are comparing string objects?
-Use (name1.equals(name2))
What is ignoring case in string comparisons
-Java gives two special methods for case insensitive comparision
-.equalsIgnoreCase() checks if two strings are the same, ignoring case
example:
“HELLO”. equalsIgnoreCase(“hello”)
-.compareToIgnoreCase() compares two strings alphabetically, ignoring case
example:
“apple”.compareTo IgnoreCase(“APPLE”)
What is the conditional operator
-Allows you to write a short version of an if else statement all in one line
-it uses three operands thats why it can also be called a ternary
can write like:
condition ? expressionIfTrue : expressionIfFalse
example:
z= (x>y) ? 10:5;
Means: if x is greater than y, set z to 10. otherwise set x to 5
What is a switch statement