How To Test Multiple Variables For Equality Against A Single Value?

Here we will learn how To Test Multiple Variables For Equality Against A Single Value. as we can follow multiple ways to do so like conditional operators like if- else or switch case can be used for the same if the thing is to simply check for equality.

Variable

Checking Of Multiple Variables With A Variable

Checking Of Multiple Variables With A Variable means we keep a variable constant and keep on comparing that variable with a number of variables or there are multiple options among them the variable might be matching.

As it could be done in different ways let’s see some examples of ways of doing so.

Using Switch Case

Switch case is a conditional operator where we compare a single variable with a number of different variables and when it matches it printed the set of code which need to be executed. So let’s take an example and understand how exactly it works.

class Main {
  public static void main(String[] args) {

    int number = 44;
    String size;

    // switch statement to check size
    switch (number) {

      case 29:
        size = "Small";
        break;

      case 42:
        size = "Medium";
        break;

      // match the value of week
      case 44:
        size = "Large";
        break;

      case 48:
        size = "Extra Large";
        break;
      
      default:
        size = "Unknown";
        break;

    }
    System.out.println("Size: " + size);
  }
}

Here we use the variable number is being compared with multiple options and when it matches any of the given cases it starts printing that set of code for it is designed.

If- Else

Here we compare a single variable with different variables which we need to compare where the given variables need present to compare as we compare with the help of our operator and in such a way we can compare as many variables as we want.

spam = 42
if spam == 3.1415 or spam == 'hello' or spam == 42 or spam == False:
 print("spam is either 3.1415, 'hello', 42, or False")

spam is either 3.1415, 'hello', 42, or False

Here we compare spam variables with a number of variables or values and if any of the given variables match spam it will print the output of our choice which is what we call comparing multiple values with a single variable or value.

To learn more about comparing multiple values with a single variable follow Learn to compare the variables.

And also visit Java Tutorials to learn more about java and to learn more about python go with How To Reverse A String In Python? and explore more programing laguages.

Leave a Comment

%d bloggers like this: