Java 中的问号和冒号
本文介绍了如何在 Java 中使用问号和冒号运算符,并列出了一些示例代码来理解该主题。
问号和冒号运算符在 Java 中统称为三元运算符,因为它们在三个操作数上起作用。
它是 Java 中 if ... else
语句的简捷解决方案,可以用作决策的单行语句。让我们看一些例子。
在 Java 中使用问号和冒号运算符
三元运算符包括三个部分。第一个是返回布尔值的条件表达式。第二和第三个是冒号之前和之后的值。如果条件表达式的计算结果为 true
,则返回冒号之前的值;否则,它返回冒号之后的值。其语法如下。
condition ? value1 : value2;
请参见下面的示例。
public class SimpleTesting {
public static void main(String[] args) {
int a = 10;
int b = 20;
boolean result = a > b ? true : false;
System.out.println(result);
}
}
输出:
false
我们可以从三元运算符获取任何类型的返回值。在下面的示例中,我们传递字符串值,并根据条件获取返回的字符串值。
public class SimpleTesting {
public static void main(String[] args) {
int a = 10;
int b = 20;
String result = a > b ? "True" : "False";
System.out.println(result);
}
}
输出:
False
下面的示例是 Java 中三元运算符的用例。我们使用此单行条件语句来检查给定的字符串是否为小写,如果字符串为小写,则将其转换为大写。否则,它返回原始字符串。
public class SimpleTesting {
public static void main(String[] args) {
String str = "mango";
String result = str.equals(str.toLowerCase()) == true ? str.toUpperCase() : str;
System.out.println(result);
}
}
输出:
MANGO
这是三元运算符的另一个用法,其中我们检查给定的整数是否为正整数,并返回字符串值。请参见以下示例。
public class SimpleTesting {
public static void main(String[] args) {
int val = 10;
String result = val > 0 ? "Positive Integer" : "Negative Integer";
System.out.println(result);
}
}
输出:
Positive Integer
在 Java 中使用嵌套问号和冒号运算符
在此示例中,我们使用嵌套的三元运算符检查是否可以像使用 if ... else
语句那样执行此操作。在这里,我们首先检查给定的整数是否为正整数,然后检查它是否位于指定范围之间并返回字符串值。请参见以下示例。
public class SimpleTesting {
public static void main(String[] args) {
int val = 10;
String result = val > 0 ? (val > 5) ? "Greater Than 5" : "Less Than 5" : "Negative Integer";
System.out.println(result);
}
}
输出:
Greater Than 5
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
在 Pandas 的列中展平层次索引
发布时间:2024/04/24 浏览次数:1782 分类:Python
-
在这篇文章中,我们将使用不同的函数来使用 Pandas DataFrame 列来展平层次索引。我们将使用的方法是重置索引和 as_index() 函数。
计算 Pandas DataFrame 中的方差
发布时间:2024/04/23 浏览次数:212 分类:Python
-
本教程演示了如何计算 Python Pandas DataFrame 中的方差。
Pandas 中的 Groupby 索引列
发布时间:2024/04/23 浏览次数:89 分类:Python
-
本教程将介绍如何使用 Python Pandas Groupby 对数据进行分类,然后将函数应用于类别。通过示例使用 groupby() 函数按 Pandas 中的多个索引列进行分组。