Intern
What are unary, binary, and ternary operators?
sobes.tech AI
Answer from AI
Unary operators work with one operand, binary with two, and ternary with three. For example:
-
Unary:
- Unary minus (
-) to change the sign of a number:// Example of unary operator val x = 5 val y = -x // y will be -5 - Postfix and prefix increment (
++) and decrement (--):// Example of unary operator var count = 10 count++ // count is now 11 ++count // count is now 12 - Logical negation (
!) to invert a boolean value:// Example of unary operator val isActive = true val isInactive = !isActive // isInactive is now false
- Unary minus (
-
Binary:
- Arithmetic operators (
+,-,*,/,%):// Example of binary operator val a = 10 val b = 5 val sum = a + b // sum will be 15 - Comparison operators (
==,!=,<,>,<=,>=):// Example of binary operator val p = 7 val q = 7 val isEqual = (p == q) // isEqual is true - Logical operators (
&&,||):// Example of binary operator val condition1 = true val condition2 = false val result = condition1 && condition2 // result is false
- Arithmetic operators (
-
Ternary:
- Kotlin does not have a direct ternary operator
?:like Java. Instead, it usesif/elseexpressions. This is essentially equivalent to the ternary operator:// Example of a ternary operator equivalent in Kotlin val age = 20 val status = if (age >= 18) "Adult" else "Minor"
- Kotlin does not have a direct ternary operator