在Switch Case Java中编译时间常量用法 [英] Compile Time Constant Usage in Switch Case Java

查看:351
本文介绍了在Switch Case Java中编译时间常量用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例的规则用法说:


  1. 案例表达式必须求值为编译时间常量

case(t)表达式的类型必须与switch(t)的那个,其中t
是类型(字符串)。

case(t) expression must have same type as that of switch(t), where t is the type (String).

如果我运行此代码:

public static void main(String[] args) {
    final String s=new String("abc");
    switch(s)
    {
       case (s):System.out.println("hi");
    }

}

它给出了编译错误: case表达式必须是常量表达式
另一方面,如果我尝试使用 final String s =abc; ,它工作正常。

It gives Compile-error as: "case expression must be a constant expression" On the other hand if i try it with final String s="abc";, it works fine.

据我所知, String s = new String(abc)是一个参考到堆上的 String 对象。而 s 本身就是一个编译时常量。

As per my knowledge,String s=new String("abc") is a reference to a String object located on heap. And s itself is a compile-time constant.

这是否意味着 final String s = new String(abc); 不是编译时间常数?

Does it mean that final String s=new String("abc");isn't compile time constant?

推荐答案

使用此,

    String s= new String("abc");
    final String lm = "abc";

    switch(s)
    {
       case lm:
           case "abc": //This is more precise as per the comments
           System.out.println("hi");
           break;
    }

根据文档


基本类型或类型String的变量,即final和使用编译时常量表达式(第15.28节)初始化的
,是
,称为常量变量

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable

问题是你的代码 final String s = new String(abc); 不初始化常量变量。

The problem is your code final String s= new String("abc"); does not initializes a constant variable.

这篇关于在Switch Case Java中编译时间常量用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆