溫馨提示×

Java中switch對字符串的支持情況

小樊
81
2024-09-03 14:02:49
欄目: 編程語言

在Java 7及更早版本中,switch語句僅支持基本數(shù)據(jù)類型(如int、charbyteshort)以及枚舉類型。對于字符串,你需要使用if-else語句進行比較。

從Java 8開始,switch語句支持字符串類型。這是一個簡單的示例:

public class SwitchStringExample {
    public static void main(String[] args) {
        String input = "hello";

        switch (input) {
            case "hello":
                System.out.println("Hello!");
                break;
            case "world":
                System.out.println("World!");
                break;
            default:
                System.out.println("Unknown input.");
                break;
        }
    }
}

在這個示例中,我們使用switch語句來比較字符串input。如果input等于"hello",則輸出"Hello!“;如果等于"world”,則輸出"World!“;否則,輸出"Unknown input.”。

0