Java initialization and cleaning, java initialization cleaning

Source: Internet
Author: User

Java initialization and cleaning, java initialization cleaning

Exercise 1: Create a class that contains an uninitialized String reference. Verify that the reference is initialized to null by java.

Exercise 2: Create a class that contains a String field initialized during definition, and a String field initialized by construction. What are the differences between the two methods?

 

1 package com; 2 3 public class Practice {4 String str1; 5 String str2 = "123"; 6 String str3; 7 Practice () {8 str3 = "constrtor initialization "; 9 System. out. println (str3); 10} 11 12 public static void main (String [] args) {13 Practice p = new Practice (); 14 System. out. println ("str1:" + p. str1 + "\ nstr2:" + p. str2 + "\ nstr3:" + p. str3); 15} 16}
// Output result
Constructor Initialization
Str1: null
Str2: 123
Str3: constructor Initialization

Conclusion: when creating an object, java performs null initialization for uninitialized String references. And the constructor will execute it first.

 

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.