Tertiary Expressions in Java

The foundation of any programming language, Java included, is the presence of syntax that allows the program to make decisions and execute based on the conditions of the program. In Java, this is done through "if-else" statements. The ternary operator functions as shorthand version of the if-else statement. This allows programmers to express simple comparisons in single-line statements for easier readability and coding simplicity.

  1. Java Conditionals

    • Basic Java syntax resembles many other programming languages. One of these resemblances comes in the form of conditional operators. Conditional operators make comparisons between two terms which represent either values or other conditional terms. Conditionals evaluate the terms, and return True or False value based on that evaluation. For example, the greater than operator (">") checks two values. If the first value is greater than the second, it returns true. So the conditional statement "5 > 4" would return true, while the statement "5 > 10" would return false.

    If-else Statements

    • Conditionals are fundamental to most programs, because they allow the program to evaluate the state of the program and make decisions based on those evaluations. One of the Java constructs that use conditionals to make decisions is the "if-else" statement. This statement is actually pretty self-explanatory: "if" a statement is true, the program will execute some code. "Else," the program executes some different code. For example, in the following code, if variable "x" is greater that "y," then something happens. If not, something else happens:

      if(x > y){
      return x;
      }

      else{
      return y;
      }

    Ternary Statements

    • The if-else statement occurs so frequently in programming, that most languages have implemented some form of the ternary operator. The ternary operator, represented in Java as a "?" symbol, performs the same function as the if-else statement. The following ternary expression can be read as "if (condition) is true, then perform statement 1. Else, perform statement two":

      condition ? statement 1 : statement 2;

    Complex Ternary Expressions

    • Using conditionals along with joining logical statements such as "and" or "or," the programmer can create complex logical comparison statements inside ternary expressions. For example, the following ternary expression checks if both "x < y" and "y < z." If both statements are true, then variable "q" will equal x. Else, it will equal y:

      int x = 3;
      int y = 4;
      int z = 5;
      int q = 0;

      q = (x < y && y < z) ? x : y;
      System.out.println(q); // prints 3

Related Searches:

References

Comments

Related Ads

Featured