condition ? trueStatement : falseStatement基本上有3个部分的声明分离了?和:符号。
- 条件:第一部分是条件部分。
- trueStatement:第二个是在第一个部分条件成立的情况下执行的代码块。
- falseStatement :如果条件结果为false,则执行第三部分代码块。
ifAccountExists() ? signIn() : signUp();
#1。三进制运算符与If-Else
例如,如果必须比较两个变量并根据结果提供输出。使用If-Else,您需要编写如下代码:if( a > b ) { return "a is greater"; } else{ return "b is greater"; }使用三元运算符可以在单行中写入相同的代码。
a > b ? "a is greater" : "b is greater";
#2。 Java中的三元运算符示例
例如,下面的示例代码会将结果返回为“b更大”,因为b的值为20,该值大于a的值。
<br /> public class TernaryOperator {</p> <p> public static void main(String[] args) {<br /> int a = 10;<br /> int b = 20;</p> <p> String result = a > b ? "a is greater" : "b is greater";</p> <p> System.out.println(result);<br /> }<br /> }
1
2
3
4
5
6
7
8
9
10
11
|
public
class
TernaryOperator
{
public
static
void
main
(
String
[
]
args
)
{
int
a
=
10
;
int
b
=
20
;
String
result
=
a
>
b
?
"a is greater"
:
"b is greater"
;
System
.
out
.
println
(
result
)
;
}
}
|
#3. Nested Ternary Operator Example
You can also use Ternary operated as nested conditions. For the example, if we compare for greatest value among three integer variables. Then if-else statement will be something like below.
<br /> if( a > b ) {<br /> if ( a > c ){<br /> return "a is greatest";<br /> }<br /> else{<br /> return "c is greatest";<br /> }<br /> else{<br /> if ( b > c ){<br /> return "b is greatest";<br /> }<br /> else{<br /> return "c is greatest";<br /> }<br /> }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
if
(
a
>
b
)
{
if
(
a
>
c
)
{
return
"a is greatest"
;
}
else
{
return
"c is greatest"
;
}
else
{
if
(
b
>
c
)
{
return
"b is greatest"
;
}
else
{
return
"c is greatest"
;
}
}
|
<br /> /* TernaryOperator.java */</p> <p>public class TernaryOperator {</p> <p> public static void main(String[] args) {<br /> int a = 10;<br /> int b = 20;<br /> int c = 30;</p> <p> String result = a > b ? a > c ? "a is greatest" : "c is greatest" : b > c ? "b is greatest" : "c is greatest";<br /> System.out.println(result);<br /> }</p> <p>}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/* TernaryOperator.java */
public
class
TernaryOperator
{
public
static
void
main
(
String
[
]
args
)
{
int
a
=
10
;
int
b
=
20
;
int
c
=
30
;
String
result
=
a
>
b
?
a
>
c
?
"a is greatest"
:
"c is greatest"
:
b
>
c
?
"b is greatest"
:
"c is greatest"
;
System
.
out
.
println
(
result
)
;
}
}
|