Java questions about class-loaded faces

Source: Internet
Author: User

----side questions

classSingleTon {Private StaticSingleTon SingleTon =NewSingleTon ();  Public Static intCount1;  Public Static intCount2 = 0; PrivateSingleTon () {count1++; Count2++; }     Public StaticSingleTon getinstance () {returnSingleTon; }} Public classTest { Public Static voidMain (string[] args) {SingleTon SingleTon=singleton.getinstance (); System.out.println ("Count1=" +singleton.count1); System.out.println ("Count2=" +Singleton.count2); }}

Ask to write out the printed result:

This problem involves the loading of classes, the first analysis:

1:singleton SingleTon = Singleton.getinstance (); The SingleTon of the class called the static method of the class, and the initialization of the triggering class is detailed: http://www.cnblogs.com/ zhangyu0217----/p/7625536.html
2: Class loads when the static variables of the class are allocated memory during the preparation process and initialize the default values Singleton=null count1=0,count2=0
3: class initialization, assigning values to static variables of a class and executing static code fast. SingleTon assignment to New SingleTon () calling class construction method
4: count=1;count2=1 (wrong answer) after calling the constructor method of the class
5: Continue assigning values to Count1 and Count2, at which point Count1 has no assignment, all count1 is 1, but Count2 performs assignment becomes 0

So the correct answer is;

Count1=1

Count2=0

In fact, the class starts from being loaded into the virtual machine memory until it is unloaded, and its entire lifecycle includes the 7 phases of loading, validating, preparing, parsing, initializing, using, and uninstalling .

The key to this problem is that the class is initialized by assigning values to the properties in the constructor, or when the class is initialized (the last step in the class loading process).

Java questions about class-loaded faces

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.