Java syntax for sugar

Source: Internet
Author: User

1. Preface

This document is from the tenth chapter of "in-depth understanding Java Virtual Machine" early (compilation period) optimization of one of the sections, other content personally feel that there is no need to pay too much attention, such as grammar, lexical analysis, semantic analysis and bytecode generation process. The main concern is how some of Java's syntactic sugars are implemented.

Syntactic sugars do not provide substantial functional improvements, but they can improve efficiency, improve grammar rigor, or reduce the likelihood of coding errors. The use of a large number of grammatical sugars may be lost in the wrong, the following describes the Java syntax for the implementation of sugar.

2. Generics and type Erasure

JDK5 adds a feature that is generic. The essence is the application of a parameterized type, that is, the data type being manipulated is specified as a parameter, which can be applied to the creation of classes, interfaces, and methods.

Java does not have generics, only through object is all types of parent class and type casts two characteristics of a mate to implement type generalization, such as the HashMap get method, return is object, because everything is possible in map. However, such an operation poses some risks, and if the type of the strong turn is wrong, it throws an exception during the run and we need to identify this problem during encoding.

Java generics are pseudo-generics, not generics in the traditional sense of C #. In C #,,list<int> and list<string> are two types, but in Java it is a list. Because Java generics exist only in the code, the generics disappear after compilation, which is called the type erase, instead of inserting a strong transcoding code. After compiling a Java program containing generics, and then recompiling it back, you will find that the generics in the anti-compilation code disappear, and the new one is the strong transcoding code.

The reason why you should use type erase to implement generics is unclear, but this is really a place to spit. Some say that performance-based generics are slower than true generics because of the lack of type-based optimizations for forced-transition operations and run-time. This evaluation angle is not correct, because generics are used to improve semantic accuracy. Java generics can lead to some peculiar problems.

such as overloading: public static void Method (List<string> list) and public static void method (List<integer> list) The existence of these two methods is not compiled, because the type erasure is identical to the signature. Seemingly overloaded incorrect reason found: Overload requires method name is the same, the parameters are different, the return value can be different. Here the parameter, method name unanimously must fail. But actually not, because if you change the next return string type, one returns an integer type, according to the overloaded definition, the return value can be different, the two methods should be the same, the compilation is different, but actually can be passed. Why is that? In the Java language, method overloading is actually required for methods with different signature signatures, the same method name. A signature is a collection of field symbol references for each parameter in a method in a constant pool, and the return value is not in it, so you can understand that overloading requires the same method name and different parameters. And why did you change the return value? The reason is that this is not an overloaded category, in the class file format, as long as the descriptor is not exactly the same two methods can coexist. The descriptor of the method and the return value are related, so the descriptors of the two methods are different because of the difference in the return value, which can coexist but is not overloaded.

3. Automatic packing, unpacking and looping

Technically, these syntactic sugars are not as generic as they are in terms of implementation and thought, but this is the most used syntax sugar.

The auto-boxing operation is: integer.valueof (i), which was replaced during the compilation phase.

The automatic unpacking operation is: Integer.intvalue ()

The foreach operation of the collection is: for (its = list.iterator; Its.hasnext; ;) {Its.next}, takes the form of an iterator traversal

The foreach operation of an array is actually a stack-up operation.

These principles are simple, you can write a class after compiling, and then decompile to see the results.

Auto-Boxing Traps:

    public static void Main (string[] args) {        Integer a = 1;        Integer B = 2;        Integer C = 3;        Integer d = 3;        Integer e = 321;        Integer f = 321;        Long g = 3L;        System.out.println (c = = d);        System.out.println (E = = f);        System.out.println (c = = (a+b));        System.out.println (C.equals (a+b));        System.out.println (g = = (a+b));        System.out.println (G.equals (a+b));    }

The above code executes out 1.true 2.false 3.true 4.true 5.true 6.false.

Explain what the above means:

First, the packaging class = = comparison does not trigger the automatic unpacking, so the comparison of 1, 2 is a reference comparison. Then why is 1 true,2 false? It says that the auto-boxing is implemented by integer.valueof, the Java code is optimized for integer, the source code can see that there is a cache, an integer between -128~127, get the same integer object, 321 over this range, A different object is generated.

+ number will trigger automatic unpacking, resulting in = = is generally an int type, not an integer type, and finally trigger C's auto-unpacking, two int type comparison, the value equal is true.

4 in the + number will also trigger the automatic unpacking, into int type, but because it is the Equals method, and automatic boxing, the final criterion is the Integer.equals method, the comparison is two int type to compare, so is true

The steps for 5 and 3 are similar, but G automatically lines into a long type, and a long is compared to an int with a numeric size.

6 and 4 are similar, but eventually become long.equals (Integer), according to the Equals method of long, passed in must be a long type, so the return is false.

This example tells us that it is not possible to use automatic boxing and unpacking in the code to avoid situations that may occur unexpectedly.

4. Conditional compilation

Many languages provide a way to conditionally compile, such as C, C + + preprocessor designator #ifdef to complete conditional compilation, they are used to resolve compile-time code dependencies, but there is no preprocessor in Java, because it is not necessary, the compiler does not compile Java files, Instead, the syntax tree top-level nodes of all compilation units are entered into the pending list before being compiled.

The Java language can also implement conditional compilation by using an if statement with a constant condition, such as if (true) {} else{}, so that the contents of the Else module are omitted.

This conditional compilation can only be written in the method body, and there is no way to adjust the entire Java class structure based on conditions.

5. Other grammatical sugars

Internal classes, enumeration classes, assertion statements, switch support for enumerations and strings (JDK7), define and close resources in try, and so on. These can be self-compiled by Javac javap-verbose to view bytecode, understand its implementation principle.

Java syntax for sugar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.