How switch cases are executed for strings?

徘徊边缘 提交于 2019-12-22 01:21:06

问题


I have a doubt in switch-case statement. Here is my code :

String month = "April";
switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;

and so on..

I have 3 questions in this context:

1) While comparing month with the case values i.e case "January", case "February" .. What is exactly used from the following by compiler ?? - month.equals("case-value") ? - month == case-value ?

2) And are case-values internally converted to StringBuilder/StringStringBuffer or simply they remain String object ??

3) How I can I know this from byte code i.e is there any tool available using which I can view directly the compiler generated code just to find out how the things behave internally?


回答1:


3) I believe JDeveloper has bytecode debugger feature. If JDeveloper is not and option, check out these tools I found:

http://sourceforge.net/projects/jbcd/

http://andrei.gmxhome.de/bytecode/index.html

http://www.drgarbage.com/how-to-debug-bytecode-with-bytecode-visualizer.html




回答2:


Not sure about number 3 but looking at the byte code is probably too low level to easily see what methods are being used.

1) the strings are compared using .equals().

2) the strings remain as String objects

See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html




回答3:


1 - The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used.

2 - Normal String object is used for this switch case statement

http://blogs.oracle.com/darcy/entry/project_coin_string_switch_anatomy



来源:https://stackoverflow.com/questions/9124658/how-switch-cases-are-executed-for-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!