Skip to content

Latest commit

Β 

History

History
386 lines (286 loc) Β· 11.7 KB

c3-note.md

File metadata and controls

386 lines (286 loc) Β· 11.7 KB

Chapter 3

🍑

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, then y > 0 will not be evaluated, because the result of false && y > 0 will always be false.
  • If x > 0 is true, then y > 0 will be evaluated, because the result of true && y > 0 depends on the value of y.

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 $0.0001$)

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 to doSomethingTrue
  • If condition is false, boolVal equals to dosomethingFalse

πŸ’‘ 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: !