Sugar-coated syntax, also called syntactic sugar. It was originally a term invented by British computer scientist Peter J. Landin. Syntactic sugar refers to a certain type of syntax. This type of syntax makes the code concise and readable through some simple packaging. It can be used when compiling by "unpacking the syntactic sugar" while maintaining the same function. Simple syntax to compile.
As the name suggests, syntactic sugar is like a layer of sugar coating, which makes the code concise. The virtual machine does not support this type of syntax. Before the virtual machine is run, this type of syntax will be compiled into a more popular and simple syntax, but the function remains unchanged.
In java, the commonly used syntactic sugars are the following:
Generics and type erasure
Automatic loading Boxing and unboxing
foreach loop
Variable length parameters
Conditional compilation
Inner classes
Enumeration classes and switch
Assertion statements
Let’s take a look at the functional usage of each syntax sugar and its actual principle one by one
There are no generic classes in the Java virtual machine. Each type has a corresponding basic type in the Java virtual machine. The following is an analysis of generics and principles.
Detailed explanation portal of generic classes: //m.sbmmt.com/java-article-354231.html
In java code, many times we cannot use the eight basic types directly, but must use their corresponding packaging classes (also called wrappers). These objects wrap classes The names are also easy to remember: Integer, Long, Byte, Double, Float, Character, Boolean, Short. The simplest example is in generics. Because basic types cannot be stored in Object after erasure, wrapper classes must be used as type parameters:
List<int> list = new ArrayList<>();//errorList<Integer> list = new ArrayList<>();//ok
Auto-boxing process: use their corresponding basic types A wrapper type wraps a basic type so that it has object characteristics.
Automatic unboxing process: Contrary to the boxing process, the packaging type is converted into a basic type.
In layman's terms, boxing and unboxing make it easier for programmers to convert between packaged classes and basic classes. They save a few sentences and simplify the code. Sometimes there is an extra sentence in the code. This type of conversion is really annoying, and the advantages of automatic boxing and unboxing are obvious.
List<Integer> list = new ArrayList<>();list.add(1);list.add(Integer.valueOf(1));//实际操作 自动装箱int n = list.get(0); int m = list.get(0).intValue();//实际操作 自动拆箱Integer p = 1; p++; //实际插入一句拆箱,再自增计算,再装箱
In packaging classes such as Integer, the equals method needs to be used to compare values. Otherwise, the comparison is whether the addresses of the two objects are stored in the same area. Use == to compare. Depending on the object being packaged, the result is either true or false.
Integer a = 1000;Integer b = 1000;System.out.println(a==b); // 输出:falseSystem.out.println(a.equals(b)); //输出:true
It is worth mentioning that wrapper classes are also a good place to place static methods such as type conversion:
int x =Integer.parseInt("111"); // x=111
java provides a super simple loop method, the foreach loop. As a loop method without an index, the foreach loop can only traverse all elements without being selective, but the simple writing method is still much more convenient. In a data structure without an index such as HashMap, the foreach loop is better than the for loop. Much better than while loop. So, what is the foreach loop used to implement? The answer is Iterator.
for(int i : list){ System.out.println(i); } //实际迭代器实现for (Iterator localIterator = list.iterator(); localIterator.hasNext(); ) { int sub = ((Integer)localIterator.next()).intValue(); System.out.println(sub);}
It is easy to figure out that traversing all the elements is achieved by using Iterator, but the actual code amount does increase a lot compared to the foreach loop. The syntax sugar plays a role in making the code convenient. It’s a must.
After java1.5, a method call with variable parameters is provided, breaking the fact that the parameters can only be a fixed number. Awkward situation. It sounds mysterious, but we use the variable-length parameter method almost every day in our daily life, such as string formatting:
public void foo(String str,Object...args){...}//方法原型 System.out.printf("%d",1); System.out.printf("%d,%s", 12,"a");//方法中的变长参数必须位于最后一个位置
The essence of the variable-length parameter is to replace the last variable-length parameter with Object [], the content is the same over and over again.
Conditional compilation is a Java virtual machine that simplifies the code. It removes the code with incorrect branches based on the true or false of the Boolean constant. piece. This effect can only be achieved by using an If statement with a constant condition. This one is also easy to understand.
if(true) { System.out.println("true"); } else { System.out.println("false"); } //实际条件编译System.out.println("true");
There are no internal classes in the virtual machine. All internal classes have become ordinary classes through certain methods.
Detailed explanation portal of internal classes: //m.sbmmt.com/java-article-354230.html
, there are also enumeration types similar to C++ in Java, but objectively they are not as easy to use as in C++. Enumeration types can include a limited number of named values, and variables of this type can be declared:
package Syntactic;public enum Size { S,M,L,XL } Size s = Size.S; //声明一个s,值为枚举类型中的S
The enumeration class is also a kind of syntactic sugar. There is no enumeration class in the virtual machine, and neither does the JVM. recognize it. First of all, all enumeration classes inherit from the java.lang.Enum class. At compile time, the compiler will directly convert the enumeration class into a real subclass of Enum. Each value in the enumeration class is turned into an instance through the constructor.
//构造器protected Enum(String name, int ordinal) {...} //第一个参数为枚举值,第二个参数为这个枚举值默认的顺序 //下面是在编译时,实际操作的将枚举值实例化的过程 new Enum<Size>("S",0);new Enum<Size>("M",1); new Enum<Size>("L",2);new Enum<Size>("XL",3);
与此同时,既然枚举类型是语法糖,那么也就有switch用枚举值作为判断,也是一种语法糖。既然枚举类型是语法糖,在虚拟机中并不存在这种语法,switch中的枚举自然也是语法糖,那么它的原理是什么呢?
首先我们要分析一下switch能够用什么来判断。1.char、byte、int、short类型,2.枚举类型,3.字符串字面量。在这些之中一定有一种类型是枚举类型实际采用的判断方式。实际上,枚举类型采用的判断方式是int(short)类型。我们刚才说过,在每个枚举类型实例化的过程中都会贴上一个顺序的序号的“标签”。new Enum<Size>("S",0)
在编译的过程中,编译器把这个序号作为他们的标记来替换switch中的枚举类型。
断言语句是在java的测试阶段普遍使用的一种语句,在1.4版本发布,而其本身也是一种语法糖。
在java中有很多糖衣语法,这些语法在不改变功能的情况下方便了我们的工作,提高了我们的效率。对于这些语法的内部实际处理虽然不一定用得到,但是有些了解还是很好的。语法糖是指那种在虚拟机中不存在但是我们可以这样编写代码的语法,并不一定只有上述的几种,但是上述是其中较为常用的。
以上就是java糖衣语法(Syntactic Sugar)详解的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!