O
O
Omur T2018-09-24 19:37:00
Java
Omur T, 2018-09-24 19:37:00

If/else VS Ternary Conditional?

Hi all!
just found out that there are two types of condition statement
1 - if / else if / else .
2. "?" and " : " (Ternary Conditional) abbreviated
question: when and where is what used?
which one would you like to use?
(Thank you!)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Clark Kent, 2018-09-24
@black_niggar1998

Everything is simple! I use this rule in all languages:
? and : we use where you need to set some value and the result of the value is affected by the condition, the record should also be short, examples:

// нахождение максимального значения
max = a > b ? a : b; 

// нахождения первого валидного значения
result = x != null ? x : y != null ? y : null; 

 // возврат значения по условию
return exists ? a : b;

if / else / switch /case use in other cases, example:
// тут не разложить в тернарный оператор
if (visible) {
    a = displayObject.x; // установка переменной a
} else {
    b = displayObject.y; // установка переменой b
}

A
aol-nnov, 2018-09-24
@aol-nnov

Use common sense. Code readability is paramount.

O
Orkhan, 2018-09-24
Hasanly @azerphoenix

More readable if else... Less code ? :
I study java myself and somehow got used to using if else else if... I need to slowly start using the ternary condition...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question