转载自https://github.com/Snailclimb/JavaGuide (添加小部分笔记)感谢作者!
简介#
语法糖(Syntactic Sugar)也称糖衣语法,指的是在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用,简而言之,让程序更加简洁,有更高的可读性
Java中有哪些语法糖#
Java虚拟机并不支持这些语法糖,这些语法糖在编译阶段就会被还原成简单的基础语法结构,这个过程就是解语法糖
javac命令可以将后缀为.java的源文件编译为后缀名为.class的可以运行于Java虚拟机的字节码。其中,com.sun.tools.javac.main.JavaCompiler的源码中,compile()中有一个步骤就是调用desugar(),这个方法就是负责解语法糖的实现的- Java中的语法糖,包括 泛型、变长参数、条件编译、自动拆装箱、内部类等
switch支持String与枚举#
switch本身原本只支持基本类型,如int、char
int是比较数值,而char则是比较其ascii码,所以其实对于编译器来说,都是int类型(整型),比如byte。short,char(ackii 码是整型)以及int。

而对于enum类型,
对于switch中使用String,则:
public class switchDemoString {
public static void main(String[] args) {
String str = "world";
switch (str) {
case "hello":
System.out.println("hello");
break;
case "world":
System.out.println("world");
break;
default:
break;
}
}
}
//反编译之后
public class switchDemoString
{
public switchDemoString()
{
}
public static void main(String args[])
{
String str = "world";
String s;
switch((s = str).hashCode())
{
default:
break;
case 99162322:
if(s.equals("hello"))
System.out.println("hello");
break;
case 113318802:
if(s.equals("world"))
System.out.println("world");
break;
}
}
}即switch判断是通过**equals()和hashCode()**方法来实现的






