简体   繁体   中英

How does switch statements work in java 1.5 with string arguments?

Can i implement switch statements(by passing string arguments) in java 5 without making use of enums?I tried doing it using hashcode but i got an error

package com.list;

import java.util.Scanner;

public class SwitchDays implements Days {

    static final int str = "sunday".hashCode();




    public static void main(String[] args) {


          Scanner in=new Scanner(System.in);    
            String day= in.nextLine();

        switch (day.hashCode()) {

        case str:
            System.out.println(day);

            break;

        default:
            break;
        }
            }


}

str in case str given an error:

case expressions must be constant expressions

Please guide.

The problem is that str is referring to the expression "sunday".hashCode() , which is not a compile time constant expression as described by the JLS:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following: ... Qualified names (§6.5.6.2) of the form TypeName . Identifier that refer to constant variables (§4.12.4).

When you check the definition of constant variables:

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28). Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9), and definite assignment (§16 (Definite Assignment)).

Since "sunday".hashCode() does not meet this requirements, you get the error.

If you would change "sunday".hashCode() to a real compile time constant like 3 it would compile.

The most straight forward solution is to make an enum, ie.

enum Days{
    sunday, monday;
}

Then it could be used as:

Day d = Day.valueOf("sunday");
switch(d){
    case sunday:
        System.out.println("ONE");
        break;
    case monday:
        System.out.println("TWO");
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM