Please give me some examples of ternary operators | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 4

Please give me some examples of ternary operators

21st Jun 2018, 7:01 PM
Nitin Janyani
Nitin Janyani - avatar
5 Respostas
+ 7
In Python it would be (code) If (Condition) else (code)
22nd Jun 2018, 12:30 PM
Muhammad Hasan
Muhammad Hasan - avatar
+ 2
Different languages use it in different ways, the ones I do know are python and java. In java it is useful for return statements especially. Lets say you had a variable ā€œisDayā€ and you wanted to return a sun if it was day and a moon if it was night. To write this you would do return isDay ? sun : night if true, do the first option, otherwise the second option. Itā€™s called ternary(3) because theres three parts. In python its also useful for assigning variables. Using the same scenario as before, you could do something like sky = sun if isDay else moon This can also be used for return statments.
21st Jun 2018, 7:08 PM
Bryce Parkman
Bryce Parkman - avatar
+ 2
int age = 26; String type = age < 18 ? "child":age < 45? "adult" : "old"; java
22nd Jun 2018, 12:48 PM
Sharofiddin
Sharofiddin - avatar
+ 1
Example: String result = condition ? "condition is true" : "condition is false" is equivalent to: String result; if (condition == true){ result = "condition is true" } else { Result = "Condon is false" }
21st Jun 2018, 7:40 PM
ifl
ifl - avatar
0
ternary operator is like if - else for example: (1<2)?2:1 this means: if 1 lesser than 2 return 2 else return 1 and its equivalent to: if (1 < 2) { return 2; } else { return 1; }
22nd Jun 2018, 4:39 PM
No Timrā€Ž