π‘
Logics & Conditions π
Logical Operators π
NOT !
π
This operator negates a Boolean value, changing True to False and False to True.
boolean a = !((1 + 1) == 2);
// a will be false.
AND &&
π
T | T | |
---|---|---|
T | T | F |
T | F | F |
// Suppose a = 0, b = 5, c = 10, d = 15
boolean result = ((!(a > b)) && ((c + b + a) == 15));
// result will be false.
OR ||
π
T | F | |
---|---|---|
T | T | T |
F | T | F |
// Suppose a = 0, b = 5, c = 10, d = 15
boolean result = ((!(a > b)) && ((c + b + a) == 15)) || (d % 10 != 5);
// result will be true.
XOR ^
π
XOR ( ^
in Java Syntax) means exclusive or, it takes two boolean operands and returns true if, and only if, the operands are different.
That is, whether you're right or I am right, there's no such a place for both of us that are right.
A | B | A XOR B |
---|---|---|
T | T | F |
F | T | T |
T | F | T |
F | F | F |
// Suppose a = 0, b = 5, c = 10, d = 15
boolean result = ((!(a > b)) && ((c + b + a) == d)) || (d % c != b) ^ (c % c == a);
// result will be true. OR operator has the highest precedence.
Relational Operators π
(for integers or floating-point values, only comparing the values)
(for char, only comparing their ASCII values)
>=
, greater than or equal to<=
, less than or equal to>
, greater than<
, less than==
, equal to!=
, not equal to
String Comparison π
==
operator π
π‘ AKA reference comparison
It checks if two references point to the same memory location.
String str1 = "Late Night Snacks";
String str2 = "Late Night Snacks";
String new_str1 = new String("Late Night Snacks");
// str1 == str2 will return true
// However, st1 == new_str1 will return false, because they are not in the same String object in memory.
π‘ In general, it compares the memory addresses of the string objects rather than their actual content.
equals()
π
str1.equals(new_str1)
means that the actual contents of str1
and new_str1
are now comparing, which will return true.
compareTo()
π
Suppose we have four Strings as follows. Remember that compareTo()
is case sensitive.
String str1 = "oreo";
String str2 = "ore";
String str3 = "oreo";
String str4 = "oreooo";
System.out.println(str1.compareTo(str2)); // 1, str1 has 1 more character than str2
System.out.println(str1.compareTo(str3)); // 0
System.out.println(str1.compareTo(str4)); // -2, str1 has 2 less characters than str4
equalsIgnoreCase()
π
Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.
compareToIgnoreCase()
π
Same as compareTo()
, but it ignores case.
Short-circuit Evaluation π
π‘ Short-circuit evaluation is the process of evaluating the second argument only when needed.
Suppose we have two variables x
and y
as follows.
if (x > 0 && y > 0) {
System.out.println("Both x and y are positive");
}
- If
x > 0
is false, theny > 0
will not be evaluated, because the result offalse && y > 0
will always be false. - If
x > 0
is true, theny > 0
will be evaluated, because the result oftrue && y > 0
depends on the value ofy
.
Floating-point Numbers Comparison π
Issue with ==
operator π
It is NOT recommended to use ==
operator to compare floating-point numbers, because the result might be unexpected. Floating-point numbers should be compared for a close enough value, like Math.abs(a - b) < 1e-10
as an example. Epislon is to avoid the issue of floating-point numbers and it is expected to be a very small number. (Commonly
If you are interested discovering the actual floating numbers, you can try the following code on your own machine.
double a = 0.1;
System.out.println("The value of a is " + a);
System.out.println("The actual floating value of a is " + new.BigDecimal(a));
BigDecimal
π
BigDecimal
is a class in Java that provides operations on double numbers for arithmetic, scale handling, rounding, comparison, hashing, and format conversion. It is commonly used for financial calculations. That is, BigDecimal
is a good choice for representing monetary values in Java.
Boolean π
Return type π
π‘ The result of a relational operator is one of two special values: true
or false
, which belongs to the data type boolean
.
Initialisation π
boolean isLegit = true;
boolean result = 2 < 3; // false. You can also do this, because the result of a condition is a boolean data type.
// Multiple conditions
boolean result2 = (5 < 8 && 9 > 10 || 7 == 12); // EXAMPLE, it'll be false
if-else π
Syntax (In Good Practice) π
if (condition1) {
playMinecraft();
} else if (condition2) {
haveLNS();
} else {
goToSleep();
}
if-else
syntax in Java is pretty similar to other languages like C/C++, C# etc.
Common Logical Issue π
String food1 = "Ramen";
String food2 = "Chicken Katsu";
String food3 = "Tempura";
String food4 = "Daifuku";
String food5 = "Dorayaki";
if (food1.equals("Ramen")) {
System.out.println("Ramen for late night snack!");
} else if (food2.equals("Chicken Katsu")) {
System.out.println("Chicken Katsu for late night snack!");
} else if (food3.equals("Tempura")) {
System.out.println("Tempura for late night snack!");
} else if (food4.equals("Daifuku")) {
System.out.println("Daifuku for late night snack!");
} else if (food5.equals("Dorayaki")) {
System.out.println("Dorayaki for late night snack!");
} else {
System.out.println("Maccas for late night snack!");
}
Java is a programming language that follows a sequential execution model, which means that it executes statements in the order they appear in the code, one after the other.
Since food1.equals("Ramen")
is the first condition in if-else
statement, if the condition is true, then it will directly return Ramen for late night snack!
and ignore other conditions.
π There's a solution for the issue above:
...
boolean LNS = false;
if (!LNS) { // !false = true, which means it will be always true as long as the LNS is false as default.
if (food1.equals("Ramen")) {
System.out.println("Ramen for late night snack!");
}
if (food2.equals("Chicken Katsu")) {
System.out.println("Chicken Katsu for late night snack!");
}
if (food3.equals("Tempura")) {
System.out.println("Tempura for late night snack!");
}
if (food4.equals("Daifuku")) {
System.out.println("Daifuku for late night snack!");
}
if (food5.equals("Dorayaki")) {
System.out.println("Dorayaki for late night snack!");
}
} else {
System.out.println("Maccas for late night snack!");
}
π‘ With this solution, all conditions will be checked. You might notice the !LNS
. The if-else
parentheses inside must be a condition and the results is either false or true. LNS = false
is declared as default, by using !LNS
can satisfy the first if
and continue to do other operations.
Short Hand Form π
β Before explaning that, I personally not recommend this to programming beginners. So write if-else
in a normal form for now and if there's one day that you think you are familiar with coding it, you could start getting used to the short hand form.
π‘ Suppose we have a variable boolVal
, it could be any data types.
boolVal = (condition) ? doSomethingTrue : dosomethingFalse;
Translated in plain English, it means:
- If condition is true,
boolVal
equals todoSomethingTrue
- If condition is false,
boolVal
equals todosomethingFalse
π‘ Example
String today = "Monday";
String toListen = (today.equals("Monday")) ? "Listen to +study album" : "Listen to +sentimental.ballads album";
In normal form:
String today = "Monday";
if (today.equals("Monday")) {
String toListen = "Listen to +study album";
} else {
String toListen = "Listen to +sentimental.ballads album";
}
Switch π
- Switch statements can only test for equality
- It is possible to write nested switch statements
- The default case is optional in switch statement, in Java.
- In a switch statement, each case label must have a unique constant value.
Syntax (In Good Practice) π
switch (number) {
case 1: // number == 1 ?
word = "one";
break;
case 2: // number == 2 ?
word = "two";
break;
case 3: // number == 3 ?
word = "three";
break;
default: // else
word = "unknown";
break;
}
Similar to the form in if-else
:
if (number == 1) {
word = "one";
} else if (number == 2) {
word = "two";
} else if (number == 3) {
word = "three";
} else {
word = "unknown";
}
Multiple Conditions π
...
switch (food) {
case "dango":
case "ramen": // OR
case "Tempura": // OR
System.out.println("Jap Fav!");
break;
case "HK Style French Toast": // OR
case "Milk Tea": // OR
case "Instant Noodle": // OR
System.out.println("Canto Fav!");
break;
}
Translated to if-else
:
...
if (food.equals("dango") || food.equals("ramen") || food.equals("Tempura")) {
System.out.println("Jap Fav!");
} else if (food.equals("HK Style French Toast") || food.equals("Milk Tea) || food.equals("Instant Noodle")) {
System.out.println("Canto Fav!!");
}
Q & A π
Q1: ?
A1: !