Home > Java > javaTutorial > body text

Detailed explanation of java sugar-coated syntax (Syntactic Sugar)

黄舟
Release: 2017-03-01 13:19:06
Original
2441 people have browsed it


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:

  1. Generics and type erasure

  2. Automatic loading Boxing and unboxing

  3. foreach loop

  4. Variable length parameters

  5. Conditional compilation

  6. Inner classes

  7. Enumeration classes and switch

  8. Assertion statements

Let’s take a look at the functional usage of each syntax sugar and its actual principle one by one

(1) Generics and type erasure

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: http://www.php.cn/java-article-354231.html

(2) Automatic installation Boxing and unboxing

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
Copy after login

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++; //实际插入一句拆箱,再自增计算,再装箱
Copy after login

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
Copy after login

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
Copy after login

(3) foreach loop

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);}
Copy after login

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.

(4) Variable-length parameters

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");//方法中的变长参数必须位于最后一个位置
Copy after login

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.

(5) Conditional compilation

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");
Copy after login

(6) Internal classes

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: http://www.php.cn/java-article-354230.html

(7) Enumeration class Like switch

, 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
Copy after login

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);
Copy after login

与此同时,既然枚举类型是语法糖,那么也就有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中文网(www.php.cn)!


Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template