All the programmers in the world are going to make mistakes.

Source: Internet
Author: User
Tags constructor execution
Program | programmer | Wrong year, international superstar Jackie Chan's "Dragon species" exposure, all accused him of sorry wife Linfengjiao, forced him to hold a note
Will, confessions to the world that he has committed "all men in the world will make mistakes." I've never made such a mistake before,
So I often think that I am not a man.

I've never committed a "mistake made by all men in the world," but I did. "All programmers around the world
Will make a mistake. " No matter what language you use, all programmers around the world must have made this mistake:
Rely too much on the compiler, but don't know what the compiler is doing.

Generally speaking, the more advanced the program language, will provide more grammatical convenience to facilitate the program writing, which is called
Syntactic sugar, I call it the "grammatical sweetness." It's a sweetness, but if you don't understand the syntax
The essence of the substance, it is likely to have no sweetness, but suffered.

Not long ago, I received an email from readers who listed the following Java program and asked me for help. After seeing this program,
, I'm sure it's another "mistake that all programmers around the world make."

Program 1

Class Singleton {private static Singleton obj = new Singleton (); public static int counter1; public static int counter2 = 0; Private Singleton () {counter1++; counter2++} public static Singleton getinstance () {return obj;}} Program 2 public class Mymain {public static void main (string[] args) {Singleton obj = singleton.getinstance (); System.out.println ("obj.counter1==" +obj.counter1); System.out.println ("obj.counter2==" +obj.counter2); } }

The results of the execution are:
Obj.counter1==1
Obj.counter2==0

Have you ever been surprised by this result? At first glance the code, you might well think that the value of Counter1 and Counter2 must be
will be equal, but the result is obviously not the case. In fact, the program 1 compiled program should be equivalent to the following program 3


Program 3 class Singleton {private static Singleton obj; public static int counter1; public static int counter2; static {// This is class constructor//before entering this class constructor, class has been JVM//config memory, and all static field will be set to 0 first. So at this point Counter1 and Counter2 are already 0, and Singleton is null obj = new Singleton (); The problem is generated by this program//Counter1 will not be set to 0 counter2 = 0; Counter2 is again set to 0 (actually superfluous)} private Singleton () {//This is instance constructor counter1++; counter2++;} public static Sing Leton getinstance () {return obj;}}

This is because when class has a static field, and the value is set directly at the declaration by "=...",
The compiler will automatically move these narratives into class constructor. Similarly, when class has instance
field and set its value directly at the declaration by "=...", the compiler automatically follows these statements
Move to instance constructor.

When this program is in class constructor and the static field is not initialized (this time, Counter1 and Cou
Nter2 are 0), call instance constructor, and instance constructor will change
The value of the static field makes both Counter1 and Counter2 1. And then instance constructor execution.
, go back to class constructor, and set the Counter2 value to 0 (but
Counter1 remain unchanged). The final result: Counter1 equals 1,counter2 equals 0.

To correct the procedure 1, there are three ways:

-Method One: The Singleton field is transferred to the Counter1 and Counter2 field after the announcement.
This is the best approach.
-Method Two: The counter2=0 of the Declaration, the "=0" part of the deletion. This approach is only in the hope
-Method Three: Move the initialization action to the class constructors, write it yourself, without relying on
Compiler generated. This is the safest approach.

How to avoid committing "mistakes made by all programmers all over the world", I give you Java programmers
's recommendations are:
-Familiar Java Language specification
-In case of doubt, use the JAVAP provided by J2SDK to deserialize the Java bytecode and directly observe
The result of the compilation.

Here are the examples I used to JAVAP 1 of the translation program:

C:\>javap-c-classpath. Singleton Compiled from Mymain.java class Singleton extends Java.lang.Object {public static int counter1; NT Counter2; public static Singleton getinstance (); static {}; Method Singleton () 0 aload_0 1 invokespecial #1 <method java.lang.Object () > 4 getstatic #2 <field int counter1& Gt 7 Iconst_1 8 Iadd 9 putstatic #2 <field int counter1> getstatic #3 <field int counter2> iconst_1 putstatic #3 <field int counter2> return method Singleton getinstance () 0 getstatic #4 <field Singleton ob J> 3 Areturn method static {} 0 new #5 <class singleton> 3 dup 4 invokespecial #6 <method Singleton () > 7 pu Tstatic #4 <field Singleton obj> iconst_0-putstatic #3 <field int counter2>

In fact, the Java syntactic sugar is not much, C # syntactic sugar is really ubiquitous,
So C # Beginners are more likely to make "mistakes that all programmers in the world make." Many C # books will be on one side
Introduces C # syntax, which describes the results of MSIL (. NET intermediate language, Java-like bytecode) after compilation.
However, Java books rarely do so.

Although "all programmers in the world will make mistakes," but this does not mean that you have made this mistake, you can still
Cao Qitai, who loves to borrow money, generally "head up and be righteous". As long as the heart, in fact, this kind of mistake can still
avoided.




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.