JavaRush/Java Blog/Random EN/Ternary operator in five seconds.
Sasha
Level 11

Ternary operator in five seconds.

Published in the Random EN group
members
I’m not a copywriter, don’t throw slippers.🤗 Let’s get down to business right away. Ternary operator in five seconds.  - 1The ternary operator performs a comparison operation between two objects: it works almost the same as if-else, it’s just written more compactly. It consists of a condition, Block number one and Block number two, and looks like this: (Value one (operation) value two, followed by a question mark (? ) , after which Block1 : Block2 . What does this mean? If in the condition we have If it turns out True, we execute the first block, if False, we execute the second block. Ternary operator in five seconds.  - 1Let's say we need to calculate the minimum of two numbers. Here is the most obvious example:
int y = 5;
int x = 10;

int min = y < x ? y : x; // Условие | Блок1 | Блок2
System.out.println(min) // min == 5
? - this is a transition to blocks. If the left comparison evaluates to TRUE, block ONE is executed. In this case, Block1 will be executed, since Y is less than X. But what if we need to find out the minimum of, say, FIVE numbers? Another clear example:
public static int min(int a, int b, int c, int d, int e) {
        int min = a < b ? a : b; // А меньше Б? Если да, минимальное число равно A. Иначе min = b;
        min = c < min ? c : min; // C меньше МИНИМАЛЬНО ЧИСЛА? Если да min = c. Иначе min = min
        min = d < min ? d : min; // D меньше МИНИМАЛЬНО ЧИСЛА? Если да min = d. Иначе min = min
        min = e < min ? e : min; //  E меньше МИНИМАЛЬНО ЧИСЛА? Если да min = e. Иначе min = min
        return min; // Возвращаем полученное минимальное число.
}
In this beautiful way we get the minimum number of five. I hope you understand everything)) And if you don’t understand, don’t be upset: here’s an explanation in the video . Be sure to watch it! https://www.youtube.com/watch?v=fHCNlQY-ssI Leave your questions and corrections in the comments.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet