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.