The colon in Java is used in a variety of situations, including the ternary operator, switch statement labels, array declaration and initialization, variable declaration and initialization, field definitions in enumerations, and lambda expressions.
: in Java:
The colon (:) in Java is used in many situations, the main meanings are as follows :
1. The ternary operator in conditional judgment
The usage format of the ternary operator isConditional expression? Value when the condition is met: The value
when the condition is not met. It allows conditionals and assignments to be performed in a single line of code.
Example:
<code class="java">int age = 18; String result = age >= 18 ? "成年人" : "未成年人";</code>
2. Case labels in the switch statement
In the switch statement, each case label They all start with a constant or expression followed by a colon, indicating the value to be checked.
Example:
<code class="java">switch (dayOfWeek) { case 1: System.out.println("星期一"); break; case 2: System.out.println("星期二"); break; ... }</code>
3. Array declaration and initialization
When declaring an array, you can use a colon to specify the array type. Element type.
Example:
<code class="java">int[] numbers = new int[] {1, 2, 3, 4};</code>
4. Variable declaration and initialization
In Java 9 and above, you can use The colon initializes the variable when it is declared.
Example:
<code class="java">int number = 5; String name = "John";</code>
5. Field definitions in enumerations
In enumerations, each enumeration A constant is followed by a colon and its value.
Example:
<code class="java">enum Season { SPRING: "春天", SUMMER: "夏天", FALL: "秋天", WINTER: "冬天" }</code>
6. Lambda expression
In a lambda expression, the colon separates the parameter list from the lambda separated from the body of the expression.
Example:
<code class="java">Comparator<Integer> comparator = (a, b) -> a - b;</code>
The above is the detailed content of What does : in java mean?. For more information, please follow other related articles on the PHP Chinese website!