-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTernaryOperator.java
More file actions
87 lines (78 loc) · 2.64 KB
/
Copy pathTernaryOperator.java
File metadata and controls
87 lines (78 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package Phase1_CoreLanguage.Operators;
/**
* Ternary (Conditional) Operator
* ------------------------------
* The only TERNARY operator in Java - takes three operands - is the conditional
* operator. It is a shorter alternative to a simple if-else when both branches
* just compute a value.
* <p>
*
* condition ? valueIfTrue : valueIfFalse
* <p>
*
* Equivalent if-else
* ------------------
* int max;
* if (a > b) max = a;
* else max = b;
* <p>
*
* // is the same as:
* int max = (a > b) ? a : b;
* <p>
*
* When To Use It
* --------------
* - Good for short, expression-style assignments.
* - Good for ternary chains that read well.
* <p>
*
* When To Avoid It
* ----------------
* - When either branch has SIDE EFFECTS - use if/else for clarity.
* - When the expression spans more than one line - readability suffers.
* - When it nests deeply - "ternary tower" is a known anti-pattern.
* <p>
*
* Type Rules
* ----------
* Both branches must produce COMPATIBLE types. The compiler computes a common
* type:
* true ? 1 : 2.0 -> double (int widened to double)
* true ? 1 : "x" -> compile error - no common type
*/
public class TernaryOperator {
public static void main(String[] args) {
// 1) Basic usage - max of two numbers
int a = 7, b = 12;
int max = (a > b) ? a : b;
System.out.println("max(" + a + ", " + b + ") = " + max);
// 2) Choose a label
int score = 75;
String grade = (score >= 60) ? "PASS" : "FAIL";
System.out.println("Score " + score + " -> " + grade);
// 3) Chained ternary (readable when the categories are mutually exclusive)
int marks = 85;
String letter = (marks >= 90) ? "A"
: (marks >= 75) ? "B"
: (marks >= 60) ? "C"
: (marks >= 40) ? "D"
: "F";
System.out.println("Marks " + marks + " -> grade " + letter);
// 4) Avoid null arguments succinctly
String input = null;
String safe = (input != null) ? input : "default";
System.out.println("safe = " + safe);
// 5) Type promotion gotcha
// Both branches must produce compatible types.
// The result of (true ? 1 : 2.0) is a double because int is widened.
Object result = (1 == 1) ? 1 : 2.0;
System.out.println("result class = " + result.getClass().getSimpleName()); // Double
// OUTPUT
// max(7, 12) = 12
// Score 75 -> PASS
// Marks 85 -> grade B
// safe = default
// result class = Double
}
}