Home > Java > javaTutorial > body text

What does : in java mean?

下次还敢
Release: 2024-04-27 00:51:17
Original
1201 people have browsed it

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.

What does : in java mean?

: 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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!