Showing posts with label conditionals. Show all posts
Showing posts with label conditionals. Show all posts

Tuesday, July 8, 2025

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java that every good programmer should be aware of: the switch statement.

switch looks like this

int day = 4;

switch (day) {

    case 1:

        System.out.println("Monday");

        break;

    case 2:

        System.out.println("Tuesday");

        break;

    case 3:

        System.out.println("Wednesday");

        break;

    case 4:

        System.out.println("Thursday");

        break;

    case 5:

        System.out.println("Friday");

        break;

    case 6:

        System.out.println("Saturday");

        break;

    case 7:

        System.out.println("Sunday");

        break;

    default:

        System.out.println("Invalid day");

}

A few things are important to notice:

  • You work on the different states of a variable (inside the switch parentheses), which must have been declared and initialized before the switch
  • You differentiate each of those states as a “case,” after which you put a colon and the behavior you want
  • You don’t use braces to enclose multiple statements, like you would in an if, else, or loop. You instead use “break” to determine when you’re done giving behavior for a specific case
  • If a “break” is ever omitted, Java will “fall through” and continue executing either until a break, return, or the end of the switch
  • For all other cases besides the ones you explicitly label in this construction, you can define a fallback behavior with the “default” part of the statement. Typically, this appears last, as above, but technically, Java's specifications allow it to be placed in any order among the different possible branches of the switch statement. 
  • Just like you can nest if-statements and loops, you can nest switch statements

You won’t see switch statements as often as you will if statements, but it’s still important to know how to build them, and that every idea expressible by one form is expressible by the other. Happy switching!

Saturday, July 5, 2025

GOTO explained

 There is a keyword in Java that can’t be used, and hasn’t been used in modern programming languages for decades, but it’s worth discussing because it brings up a point about how to write good, clean code (hint: by not ever using this keyword anywhere). This is, of course, the goto (or go-to, or GOTO, depending on the language; in Java, the reserved word is “goto” all lowercase, no hyphen) statement condemned by none other than Edgar Dijkstra himself, long before Java was invented.

GOTO was initially devised as a part of a branching or looping instruction (as in: “if this is true, GOTO this line and do xyz, else GOTO this other line and do abc” or “while this is true, do this, then GOTO this place to check the loop condition”).  But, very quickly, problems came about with GOTO as an introducer of spaghetti code.

People used to number the lines of their code, and feed those line numbers into GOTO to tell it where to jump to. Most of the time, people would write successive lines of code separated by 10; the first line was line 10, then 20, then 30, and so on. These gaps  were put in place so that, if there was ever a bug, there would be numeric space in between to, later in the file, insert a fix at an available line number, even out of counting order, and then use go-to to come in or out of the fix as needed.

But, of course, as programs get longer and more complex, mistakes become simultaneously more common and more difficult to fix, so the need for these kinds of goto statements jumping around the code increases rather rapidly, much faster than the length of the code. That is, a piece of code that has twice as many lines, probably has more than twice as many bugs (and therefore needs more than twice as many of these goto statements).


This example is in C, not in Java, but it illustrates the messiness just as well:

#include <stdio.h>

 

int main() {

    int value = 42;

 

    printf("Start of program\n");

 

    // Suppose this block is buggy

    goto skip_buggy_code;

    printf("This buggy code would crash!\n");

    value = value / 0; // Division by zero bug

 

skip_buggy_code:

    printf("Buggy code skipped. Value is %d\n", value);

 

    // Another bug

    if (value == 42) goto avoid_null_pointer;

    int *ptr = NULL;

    printf("Dereferencing null pointer: %d\n", *ptr); // Would crash

 

avoid_null_pointer:

    printf("Null pointer dereference avoided.\n");

 

    printf("End of program\n");

    return 0;

}

Using goto with line numbers (or in this C example—linguistically developed enough to have labels already) creates incredibly messy code that is hard to follow. Imagine trying to read an essay written by a student who writes clearly, versus reading an essay by a student who constantly circles things, crosses them out, indicates that a paragraph is in the wrong place, and so on. The first student’s work would be easier to understand than the second, even if, presentation aside, the second student did bring up some good points in the essay.

This messiness—or, rather, avoiding it—is why Java does not support GOTO behavior, and, further, prevents any use of anything even remotely similar by taking that word out of the list of possibly allowed user-defined symbols. You therefore cannot implement a method with that name, nor give the name to a variable or a class. 

Monday, June 30, 2025

Harsahad Numbers and the Ternary operator

Today’s problem has less to do with computing Harshad numbers—I was unaware of the name until I solved the problem, just a few days before this went live—and much more to do with a piece of Java syntax that tightens up conditionals. By now, you are certainly advanced enough in Java to have come across it if you’ve looked anywhere else for tutorials, so I certainly should address it here.

The problem is the following:

A number is a Harshad number if it’s divisible by the sum of its digits. Given a number, figure out if it is one of these numbers. If it is, return the sum of the digits. If it isn’t—as is convention when things fail, are not found, etc.—return -1.

Here's the logic that gets it done:

public int sumOfTheDigitsOfHarshadNumber(int x) {

          int num = x;

          int currentDigit;

          int sumOfDigits = 0;

         

          while (x > 0) {

               currentDigit = x % 10;

               x /= 10;

               sumOfDigits += currentDigit;

          }

         

          return num % sumOfDigits == 0 ? sumOfDigits : -1;

     }

I need the parameter number x to do things to it—get its digits, etc.—but I also need that value somewhere else for safekeeping. So I created another variable, num, to also store the same value.

The variable currentDigit will store, as I’m looping through, the digit I’m currently working on.

sumOfDigits is declared and initialized to 0 outside the loop, naturally, to store the sum of the digits of the number, which will determine if the number is a Harshad number or not.

Successively modding by 10 and dividing by 10 exposes and captures one digit at a time from the right, i.e., the least significant places. I’m doing addition here, so I don’t care much about the order of the numbers. This way works, and is much easier than coming from the left, so I might as well do what I know well. As I capture digits, I’m adding them to the running total of the sum of all the number’s digits.

There aren’t any leading zeroes, so while the value of x (which is initially the same as my parameter num) is bigger than zero, I can keep looping—I have to keep looping—because I still have digits to process.

Once I finish looping, I can do my Harshad calculation. This is the whole point of this article—that last line of code.

This is a ternary operator, a syntactical choice in Java and other languages that allows programmers to condense if-else logic into one line.

The ternary statement a ? b : c is exactly equivalent to the more verbose

if(a){
     b;
} else{
     c;
}

Get used to reading and writing both styles. They are interchangeable, and a good programmer knows and uses both.

Given this, that last line means the following: if num % sumOfDigits == 0  is true (that is, if num—passed in as x, but  I did all kinds of manipulation to the original x, so I made a copy for this reason—is divisible by sumOfDigits), then return sumOfDigits; if not, return -1.


 

Friday, June 13, 2025

Nulls

 Every data type has a default value. For primitives, if they’re numbers, its their form of 0. For booleans, it’s false. For the char type, it’s ASCII 0—which is not literally the character ‘0’, but a NULL value, a sort of way to say “this space contains a thing, and that thing is ‘nothing’”, as distinct from “this is an empty box.”

For objects, then, of any sort, the default value is null. “null” is reserved in Java, so just as you can’t name a variable “int” or “for” or “while,” you can’t name it “null” either.

When you create an object, before it gets a value, if you try to access it—say, to print out its contents—the value you will get on the other end will be null.

If, for example, you’re moving along a List, and you’ve reached the end of the list, then the “next” pointer won’t point to another element of the list, but will point to null, and accessing that phantom element (the one after the last one) will produce a NullPointerException.

This behavior is a core part of how Java manages memory and object references. The use of null is both practical and intentional—it signals that a reference exists, but it doesn’t point to any actual object in memory. However, this design also introduces a common pitfall: attempting to call methods or access fields on a null reference will trigger a NullPointerException. For example, if you try to call .length() on a String variable that’s null, or .next on a null node in a linked list, Java will throw this exception to alert you that your code is trying to operate on nothingness. To avoid these errors, it’s considered best practice to perform explicit null checks before accessing object members.

Java developers often encounter null in more complex scenarios, such as when working with collections or APIs. For instance, some methods may return null to indicate the absence of a value—like when searching for a key that doesn’t exist in a Map, or when a database query finds no matching row. In these cases, it’s up to the programmer to decide how to handle null values: should they throw an exception (we’ll cover this very soon), return a default value, or perhaps propagate the null up the call stack? This decision can have significant implications for the robustness and clarity of your codebase.

Look at this example:

public class NullExample {

    public static void main(String[] args) {

        String message = null; // message is declared but not set to a real string

 

        // This would throw a NullPointerException if uncommented:

        // System.out.println("Message length: " + message.length());

 

        // Safe way: check for null before using message

        if (message != null) {

            System.out.println("Message length: " + message.length());

        } else {

            System.out.println("Message is null!");

        }

    }

}

The String message is declared null, so accessing it a few lines later (that part is commented out, so it woud not execute) would return an error that, in this case, would crash the program. That is why it’s so important to take the safe approach and check whether something is null or not, and only take action on it if we know it isn’t null, as we do at the end. 

Monday, June 9, 2025

Short-circuit evaluation of booleans

 By now, you may have noticed this already, but it’s so important that it merits an article of its own: there are some instances in which you don’t care—so you don’t even compute—what certain expressions’ values are.


Suppose you have something like:

if(isMonday  || isWednesday || isFriday){
// stuff
}

Then, knowing that || means logical-or (so this means, in English, “if today is Monday, Wednesday, or Friday…”), one might look at the truth table for OR. The truth table contains all the possible inputs and their corresponding outputs:

For “OR”, that looks like:

Var1

Var2

Result

TRUE

TRUE

TRUE

TRUE

FALSE

TRUE

FALSE

TRUE

TRUE

FALSE

FALSE

FALSE


That is, 2-way logical OR is false only if BOTH are false (3-, 4-way, etc., would only be false if ALL are false). Put another way, if ANY are true, then OR is true.

AND, likewise, has a table.

Var1

Var2

Result

TRUE

TRUE

TRUE

TRUE

FALSE

FALSE

FALSE

TRUE

FALSE

FALSE

FALSE

FALSE


For a logical AND to return true, both things being AND-ed must be true (likewise for multi-way AND, ALL must be true for it to be true; any falses cause an overall false). If BOTH are true, then AND is true; if ANY are false, then AND is false.

Back to our day-of-the-week example, once we see that any day matches with today, we don’t have to look at any of the other checks, since the expression is entirely OR-based. Just the fact that one of those is true, provided that they’re all connected by OR, is enough to make the whole expression true, and we can jump into whatever code is prescribed for that case.

Similarly, in a situation where

if(is16OrOlder && hasLicense && noRestrictions && carIsWorking){
// do stuff

}

If any of these are found to be false, we don’t need to check the others. AND works in such a way that, unless all chained ANDs are true, the whole thing is false.

This is a simple and incredibly common logical optimization in Java performed at the compiler level, known as short-circuit evaluation. If you have a sophisticated IDE, it will also probably tell you if it finds any variables that can be short-circuited. IntelliJ, at least in light mode, highlights such expressions in a sepia-like color (which it also uses for infinite loops, or loops that don’t loop).

 

Saturday, June 7, 2025

Break and Continue

 Sometimes, it might be necessary to either stop a loop prematurely—without returning from a method—or skip over an iteration of a loop.


It is for this reason that Java has two special keywords: break (for the former case), and continue (for the latter).

Suppose we want to exit a loop early. The break keyword would be used to do that, like so:

public class BreakExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {

            if (i == 5) {

                break; // Exit the loop when i is 5

            }

            System.out.println("i = " + i);

        }

        System.out.println("Loop ended.");

    }

}

(Never mind that, in this instance, the loop was written very badly—why loop from 1 to 10, if you’re going to break out of the loop and stop it completely, at 5? Poor design as this may be, it serves our purpose of illustrating how break is used.)

This works for any loop—even those for which the index is not exposed (the for-each/enhanced-for loop):

public class BreakForEachExample {

    public static void main(String[] args) {

        String[] laptops = {"Windows", "Samsung", "Apple", "Dell", "Asus"};

 

        for (String laptop : laptops) {

            if (laptop.equals("Apple")) {

                System.out.println("Yes, we want an Apple company laptop");

                break; // Exit the loop when "Apple" is found

            }

        }

    }

}

The “continue” keyword, meanwhile, keeps the loop running, but skips over one particular iteration.

Here, we see continue used in a while loop—just to drive home the point that both these keywords can be used (meaning the same thing), regardless of what particular loop they’re in: continue skips one, break comes out.

public class ContinueWhileExample {

    public static void main(String[] args) {

        int i = 0;

        while (i < 5) {

            i++;

            if (i == 3) {

                continue; // Skip the rest of the loop when i is 3

            }

            System.out.println("i = " + i);

        }

    }

}

Now, that’s all well and good if all we have is one loop to deal with—if that’s true, then the behavior of these breakpoints is straightforward—but what happens if we have nested loops, that is, loops inside loops, inside loops, inside loops…?

This, for example, is a nested loop:

public class NestedLoopExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 3; i++) { // Outer loop for rows

            for (int j = 1; j <= 5; j++) { // Inner loop for columns

                System.out.print("* ");

            }

            System.out.println(); // Move to the next line after each row

        }

    }

}

For each of the 3 rows, the program prints 5 * characters—producing something like

*****
*****
*****

If someone were to break or continue in a situation like this, where there are nested loops—which can be of mixed types (for inside while, while inside do-while, indexed-for inside for-each, while inside for-each, etc.)—break and continue only apply to the innermost loop in which they could:

For example, the following code:

public class NestedLoopBreakExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 3; i++) { // Outer loop

            for (int j = 1; j <= 5; j++) { // Inner loop

                if (j == 3) {

                    break; // Exit the inner loop when j is 3

                }

                System.out.println("i = " + i + ", j = " + j);

            }

        }

    }

}

has this output:

i = 1, j = 1

i = 1, j = 2

i = 2, j = 1

i = 2, j = 2

i = 3, j = 1

i = 3, j = 2

But if we use “continue” in the outer loop, then something like this might happen:

public class OuterContinueExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 3; i++) { // Outer loop

            if (i == 2) {

                continue; // Skip the rest of this outer loop iteration when i is 2

            }

            for (int j = 1; j <= 3; j++) { // Inner loop

                System.out.println("i = " + i + ", j = " + j);

            }

        }

    }

}

i = 1, j = 1

i = 1, j = 2

i = 1, j = 3

i = 3, j = 1

i = 3, j = 2

i = 3, j = 3

Both break and continue are vitally important logical flow controllers—so be sure you understand how each works (and is different from the other!). Don’t just stick to these code examples; write your own, or modify these, and see how the behavior changes as you make changes to your code.

Sunday, May 25, 2025

Indexed-for loops

In this article, we’ll cover the indexed-for loop. Its syntax may seem a little more daunting than the do-while or while loops, but it’s always possible to convert a while to a for or vice versa.

For-loops look like this:

for(start state; end condition; variable change rule){
       do this stuff in here;
}

In real Java, you might see something like:

int res = 0;
for(int i = 0; i <= 10; i++){
       res+=i;
}
System.out.println(res);

How does this loop flow?
  • Before we enter the loop, we create res and give it the value 0
  • Now we are concerned about the loop. Inside it, there’s a counter called i, which is initially 0.
  • We’ll check against the condition i<=10
  • If that check succeeds, we’ll do whatever is in the braces
  • Then we’ll change i according to i++
  • Then we’ll see if we should keep going according to i<=10
  • Then if we should, we’ll do whatever is in the braces, and so on, and if not we exit
  • Once we exit the loop, we print res

Take a second to go back to the while-loop article and compare the while-loop implementation of the sum of the first 10 numbers to the for-loop implementation. Notice anything similar? Different?

The Do-while loop

 Next on our list of loops is the do-while loop.

The do-while loop is very similar to the while-loop, with one key difference.

The regular while-loop looks like:

while(something is true){
do this;
}

but the do-while loop looks like:

do {
this;
} while (something is true);

There is a key difference here. The while loop we saw is never guaranteed to execute. The while-loop checks the condition, and if it’s false from the get-go, nothing happens, and we just move on. But the do-while loop, on the other hand, encounters the “do this thing” part of its instructions before it encounters the condition to check. Do-while loops are therefore guaranteed to execute at least once, since they execute, then check, then execute, then check… and so on. Take a moment to realize that {execute, check, execute, check…} could produce different results than {check, execute, check, execute…}

The While-Loop

It’s very natural in computer science to want to do something over and over again. It’s for this reason that loops exist. Java has 4 loops, and we’ll cover one each in the next 4 articles: the while, the do-while, the indexed-for, and the for-each.


Syntactically, the while is the simplest. Logically, it’s the easiest to understand. We’ll start with it.

In plain English, “check if something is true, then do X; check if something is true, then do X; check if something is true, then do X.”

While loops look like this:

while(condition){
statements;
}

This should look very familiar, since if-statements are nearly identical. In fact, one of the ways you might hear about a while loop in a formal computer science course  is as  a repeated if-statement. You check the condition, then you do the thing, then you check the condition again, and you do the thing…

The same rules about braces apply to while loops. But, again, my recommendation is to always use them.

Imagine we want to sum all the numbers from 0 to (and including) 10.

We could set up a WhileLoopPractice class, and inside main say something like

int res = 0;
res+=1;
res+=2;
res+=3;

And so on…
and eventually come up with the (correct) answer 55.

But one of the benefits of a while loop is that we don’t need to be that verbose.

in that example, we could say:

int i = 0;
int res = 0;
while (i <= 10){
     res+=i;
}

If we then print out res after the loop finishes, it will have the right result.

Let’s look more closely at the bare-bones structure of a while-loop.

There is an iterator, a counter of some sort—in the sum example, we called it i. There is a condition being checked—in this case, whether i is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, or 10. And there is at least one statement to be executed as long as the condition evaluates to true. Any valid Boolean expression can be that condition, just as was the case for if-statements.

Right out of the gate, there are two common bugs you might face:

  • What if a loop you intended to run never executes?
  • What if a loop you intended to run for a while and then have stop never stops?

It is easy to produce examples of both.

Scenario 1 looks like this:

int i = 0;

while(i < 0 && i > -10){
      System.out.println(“I’m negative!”);
     i--;
}

Notice here that i is set to 0. The condition specifies that i must be strictly less than 0, and strictly greater than -10.

But i is 0, which is not strictly less than 0. And given how we know AND works—both things fed to && must be true for && to return true—the very first check will fail and we’ll just skip over the loop. That loop, which we intended to print “I’m negative!” 10 times never actually executes.

Scenario 2 looks like this:

int i = 0;

while(i < 100){
     System.out.println(“I’m happy!”);
}

Look at what’s happening here: i is set to 0.
Is i’s value less than 100? “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”
Is i’s value less than 100? Yes “I’m happy!”

on and on forever

We’re never actually changing the value of i, so since it was initially less than 100, it will always be less than 100. This loop, in contrast to the other one we just saw that never started, never ends.

Writing this kind of loop by mistake is totally normal—and, for every programmer, doing this for the first time is a rite of passage. Thankfully, it’s a really easy mistake to fix; don’t sweat it!

All that needs to be done is, inside the loop, update i’s value.

Now, the fixed loop looks like:

int i = 0;

while(i < 100){
     System.out.println(“I’m happy!”);
     i++;
}

now, there’ll be an iteration where we print “I’m happy!” when i is 0, 1, 2, 3, 4, 5, …, 97, 98, and 99, and then, crucially, when I gets incremented to 100, it will no longer be true that 100 < 100, so the loop will stop. We’ll print “I’m happy!” exactly 100 times and then stop.


Conditionals

 Having learned the logical AND, OR, and NOT in a previous article, let’s move on to something only slightly more complex:

Set up a class (and your main method) called ConditionalPractice.

In the main method, declare a Boolean called isMonday. Set it to true, like this:

boolean isMonday = true;

In plain English, what we want to do is System.out.println() something if today is Monday.

What you’re about to see is something called pseudocode for the first time; it isn’t Java, so it won’t run if you try to run it in a class, but it gives a high-level, close-to-plain-English view of what code does in a way that what language choose to write in doesn’t matter. As we get more advanced, you’ll start seeing pseudocode in these articles a lot more frequently.

If today is Monday
               Print “Today is Monday”

In Java, we have if-statements.

Their syntax is the following

if(a condition){
     what to do if that condition is true;
}

That condition must always be evaluable to a boolean. Refer back to our Math lessons—“is 50 % 2 equal to 0?” (written as 50 % 2 == 0) is an example of such an expression that isn’t immediately a boolean like isMonday, but can become one. Both true-false questions and immediate booleans can go in the condition spot in the if.

You are not always obligated to have curly braces around ifs, but I always use them as a matter of personal preference. If your list of things to do inside a block only contains one thing, you can omit the braces. But if your list of thgs to do includes more than one statement, you must have them.

if(todayIsMonday)
     System.out.println(“Oh no!”);

works just as well (even though I don’t like it as much) as

if(todayIsMonday){
     System.out.println(“Oh no!”);
}

BUT:

(A)

if(todayIsMonday)
     System.out.println(“Oh no!”);
     System.out.println(“I don’t like Mondays”);

will produce a different—perhaps unintended result than

(B)

if(todayIsMonday){
     System.out.println(“Oh no!”);
     System.out.println(“I don’t like Mondays”);
}

In Java, if you omit braces from if-statements, Java assumes you only want the first statement inside the if bound by its condition.

So A and B are different. Can you figure out why? Pause for a second to think, and then keep reading.

A prints “Oh no!” only if today is in fact Monday, but prints “I don’t like Mondays” regardless.

B prints BOTH “Oh no!” and “I don’t like Mondays” only if today is in fact Monday, and nothing if it isn’t.

It's perfectly natural to want to do one of two other things:

·       If today is any other day of the week but Monday, print something else

·       If today is Tuesday, print X; if today is Wednesday, print Y; if today is Thursday, print Z; and so on

For this, we need an extra bit of syntax: the else clause.

Else clauses are always paired with if-statements, and always come after them. Else clauses have the same brace rules as if-statements, but, again, I like to always use them even when not technically required by the compiler.

To write the first bullet point, we need a straight-up else statement without any frills.

in pseudocode, it looks like:

If a number is even:
     Print “YAY!”
Else
     Print “BOO!”

In Java, that would look like


if(){
} else{
}

and the code to be executed in each situation would go inside the relevant curly braces.

So back to our other-days example.

·       If today is Monday, print “I don’t like Mondays!”

·       Otherwise, for any other day of the week, print “Today is OK, I guess”

if(todayIsMonday){
      System.out.println(“I don’t like Mondays!”);
} else{
     System.out.println(“Today is OK, I guess”);

Now, what if you wanted to get a little more specific with how you handled branching, and have a few more cases? Perhaps “I really enjoy the weekend!!” gets printed if today is Saturday or Sunday?

in that case, let’s assume that all these variables are properly created and initialized (I won’t show that here, but you’ll need to make sure that’s true if you’re following along in your IDE window):

First, in pseudocode:

If today is Monday
               Print “I don’t like Mondays!”
If we know today isn’t Monday, but we still check if today is the weekend and find out it is
               Print “I really enjoy the weekend!!”
In every other situation, when today isn’t Monday or the weekend
               Print “Today is OK, I guess”

now in Java (remember to declare and initialize everything properly or you’ll get an error!)

if(todayIsMonday){
      System.out.println(“I don’t like Mondays!”);
}else if (todayIsWeekend){
     System.out.println(“I really enjoy the weekend!!”);
}else{
      System.out.println(“Today is OK, I guess”);
}

You could, in theory, have as many different else-if cases in between as you wanted. Make that an exercise. Go through and set one day a week to be true at a time, and run the code many times, setting a different message to be true for each day of the week

Remember, it would look something like:

if(todayIsMonday){
      System.out.println(“I don’t like Mondays!”);
} else if (todayIsTuesday){
     System.out.println(“I go to the store on Tuesdays”);
} else if (todayIsWednesday){
     System.out.println(“I go to the park on Wednesdays”);
}  else if (todayIsWeekend){
     System.out.println(“I really enjoy the weekend!!”);
}else{
      System.out.println(“Today is OK, I guess”);
}

of course, you could do something purely mathematical—

Like:

·       Start with 5040

  • Using % to check, if x (5040) is a multiple of 2, print “2!!”
  •  Else if x is a multiple of 3, print “3!!”
  • Else if x is a multiple of 4, print “4!!”
  • Else if x is a multiple of 5, print “5!!”
  • Else if x is a multiple of 6, print “6!!”
  • Else if x is a multiple of 7, print “7!!”
  • Else if x is a multiple of 8, print “8!!”
  • Else if x is a multiple of 9, print “9!!”
  • Else if x is a multiple of 10, print “10!!”
  • Else—that is, only as a last resort, if nothing else triggers—print “prime??”

Be careful—I’ve set a trap here! This is like the days of the week example—so only the first true thing triggers (or the else), not everything that is true!

To make everything that is true trigger, turn all else-ifs into regular ifs. (Ifs can stand alone without an else, but the reverse is not true.) 

Logical Operations

 In computer science, it’s very important when writing code to be able to express a few key ideas. In Java, :

  • A AND B (only true if both are true) is &&
  • A OR B (only false if both are false) is ||
  • NOT A (the opposite; true becomes false, false becomes true) is !

 

They all look reasonably similar to what you’d expect, but just like = is not to check for equality (that’s ==, since = is for assigning, and the single = can’t mean both), they are slightly different from what you might have first thought, for a very similar reason. (We’ll cover what single-& and single | mean in Java much later.)

In Java, you can AND booleans or Boolean expressions with &&, as in A && B; you can OR them with ||, as in X || Y; and you can NOT them by !, as in !isEmpty().

You can, of course, connect them into much longer chains: A AND (B OR C) AND NOT D OR (E AND F) would look like

A && (B || C) && !D || (E && F), and so on. Depending on the values of A..F, this will change the value of the whole expression.

Notice in this example the use of parentheses to force ordering, just as in math.

In exactly the same sense as we have PEMDAS/BODMAS in math, logical operations also have an order of precedence: parentheses go first, then ==, then ! (NOT), then && (AND), then || (OR).  

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...