Home > Java > javaTutorial > Why Doesn't Java's Switch Statement Accept Seemingly Constant Variables as Case Labels?

Why Doesn't Java's Switch Statement Accept Seemingly Constant Variables as Case Labels?

Linda Hamilton
Release: 2024-12-10 15:44:10
Original
841 people have browsed it

Why Doesn't Java's Switch Statement Accept Seemingly Constant Variables as Case Labels?

Java Switch Statement Constant Expression Confusion

In Java, a switch statement requires constant expressions as case labels. However, developers often encounter errors complaining about non-constant expressions even when using seemingly constant variables.

Consider the following example:

public abstract class Foo {
    public static final int BAR;
    public static final int BAZ;
    public static final int BAM;

    public static String lookup(int constant) {
        switch (constant) {
            case Foo.BAR: return "bar";
            case Foo.BAZ: return "baz";
            case Foo.BAM: return "bam";
            default: return "unknown";
        }
    }
}
Copy after login

When compiling this code, you may encounter a "constant expression required" error on each case label.

Why aren't Foo.BAR variables constant?

While Foo.BAR variables are effectively constant from an execution perspective, they are not "compile-time constants" as required by the Java Language Specification (JLS). Section 15.28 of the JLS defines a constant expression as one that:

  • Refers to primitive types or String
  • Only uses literals, constant variables, and parentheses
  • Excludes assignment operators, , --, and instanceof
  • Does not include type casting except to primitive types or String

In the example above, Foo.BAR variables are not declared with explicit initializers, therefore they do not qualify as compile-time constants.

Solution:

To resolve the error, initialize the Foo.BAR variables with compile-time constant expressions:

public static final int BAR = 1;
public static final int BAZ = 2;
public static final int BAM = 3;
Copy after login

The above is the detailed content of Why Doesn't Java's Switch Statement Accept Seemingly Constant Variables as Case Labels?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template