Thinking in Java Notes (fifth chapter initialization and Cleanup (iii))

Source: Internet
Author: User

Fifth chapter initialization and cleanup 5.6 member initialization

Java makes every effort to ensure that all variables are properly initialized before they can be used. For local variables of a method, Java is guaranteed in the form of a compilation error. As follows:

void f() {    int i;    i++; //Error:i not initialized}

Gets an error message that indicates I may not be initialized. The compiler can assign an initial value to I, but it does not, because no initialization is the programmer's negligence, in order to ensure the stability of the program, can help the programmer to find out the shortcomings of the program.

However, if the data member of the class is the base type, each basic type member variable of the class will be guaranteed to have an initial value. As follows:

public class Test {    boolean t;    char c;    byte b;    short s;    int i;    long l;    float f;    double d;    InitialValues reference;}

The above series of values are: false, (空白), 0, 0, 0, 0, 0.0, 0.0, null . The char value is 0, so the display is blank.

5.6.1 Specifying initialization

There is a straightforward way to assign an initial value to a variable, which is assigned directly to it where the class member variable is defined, not allowed in C + +. It is also possible to initialize an object of a non-primitive type, such as an object of Class A below, so that each object of the class test has the same initial value. As follows:

class A{}public class Test {    boolean bool = true;    char ch = ‘x‘;    int i = 99;    A a = new A();}
5.7 Constructor initialization

You can also initialize with a constructor. At run time, you can invoke a method or perform certain actions to determine the initial value, which gives programming greater flexibility. Remember, however, that automatic initialization cannot be organized, that is, the compiler automatically assigns the previously mentioned work, which occurs before the constructor is called. For example:

public class Test {     int i;    Test() {i = 7;} }

The value of I is first set to 0, and then is assigned a value of 7.

5.7.1 Sequence of initialization

Within the class, the order in which the variables are defined determines the order in which they are initialized. Even if the definition of a variable is between a scatter and a method definition, they are initialized before any method (including the constructor) is called. For example:

class Window {    Window(int maker) {        System.out.println("Window(" + maker + ")");    }}class House {    Window w1 = new Window(1);    House() {        System.out.println("House");        w3 = new Window(33);    }    Window w2 = new WIndow(2);    void f() {        System.out.println("f()");    Window w3 = new Window(3);    }}public class Test {    public static void main(String[] args) {        House h = new House();        h.f();    }   }

The result is Window(1) Window(2) Window(3) House() Window(33) f() .

5.7.2 initialization of static data

Regardless of how many objects are created, static data takes up a portion of the storage area. The static keyword cannot be applied to local variables. Look at the following example:

Class Bowl {Bowl (int marker) {System.out.println ("Bowl (" + marker + ")");    } void F1 (int marker) {System.out.println ("F1 (" + marker + ")");    }}class Table {static Bowl bowl1 = new Bowl (1);        Table () {System.out.println ("table ()");    BOWL2.F1 (1);    void F2 (int marker) {System.out.println ("F2 (" + marker + ")");    } static Bowl bowl2 = new Bowl (2);    }class Cupboard {Bowl bowl3 = new Bowl (3);    static Bowl Bowl4 = new Bowl (4);        Cupboard () {System.out.println ("cupboard ()");    BOWL4.F1 (2);    } void F3 (int marker) {System.out.println ("F3 (" + Marker + ")"); } static Bowl bowl5 = new Bowl (5);}} public class Test {public static void main (string[] args) {System.out.println ("Creating New Cupboard () in main"        );        New Cupboard ();        Syste.out.println ("Creating New Cupboard () in main");        New Cupboard ();        TABLE.F2 (1);    CUPBOARD.F3 (1); } static Table table = new TaBLE (); Static cupboard cupboard = new Cupbpard ();}

The results of the output are:

Bowl(1) Bowl(2) Table() f1(1) Bowl(4)Bowl(5)Bowl(3) Cupboard()f1(2) Creating new Cupboard() in main Bowl(3)     Cupboard() f1(2) Creating new Cupboard() in main Bowl(3)Cupboard()f1(2)f2(1)f3(1)

Static initialization occurs only when necessary, and static data is initialized only when the first class object is created (or the first time a static data is accessed). After that, no matter how the object is created, it will not be initialized again.

The order of initialization is static objects (if they have not been initialized), and then "non-static objects".

Summarize the object creation process, assuming there is a class named dog:

    1. Even if the static keyword is not explicitly used, the constructor is actually a static method. Therefore, when the first creation of a type is a dog object (a constructor can be considered a static method), or when the static method of the dog class is first accessed, the Java interpreter must find the path to the class to locate Dog.class.
    2. Then loading dog.class, all actions on static initialization are performed, so static initialization occurs only once when the class object is first loaded.
    3. When you create a dog object with new, you first allocate enough storage space on the heap to the dog object.
    4. Clear 0 of the allocated storage space, which automatically sets all the basic data types in the dog object to the default values (0 for the number, similar to the Boolean and char types), and the reference is set to NULL.
    5. Performs all initialization actions that occur in the field timing.
    6. Executes the constructor method.
Static initialization for 5.7.3 display

Java allows multiple static initialization actions to be organized into a special "static clause" (sometimes called a "static Block"). Just like this:

public class Spoon {    static int i;    static {        i = 47;    }}

As with other static initialization actions, this code executes only once: when the object of the class is first generated, or when the static member data belonging to the class is first accessed. For example:

class Cup {    Cup(int marker) {        System.out.println("Cup(" + marker + ")");    }    void f(int marker) {        System.out.println("f(" + marker + ")");    }}class Cups {    static Cup cup1;    static Cup cup2;    static {        cup1 = new Cup(1);        cup2 = new Cup(2);    }    Cups() {        System.out.println("Cups()");    }}public class Test {    public static void main(String[] args) {        System.out.println("Inside main()");        Cups.cup1.f(99);  //  (1)    }    //static Cups cups1 = new Cups(); //  (2)    //static Cups cup2 = new Cups();  //  (2)}

The above results are:Inside main() Cup(1) Cup(2) f(99)

5.7.4 non-static instance initialization

Java also has a similar syntax that is initialized to an instance, which initializes the non-static variables for each object. Same as the static statement block, but with less static. If you do not create an instance of the class, the non-static statement block is not executed, only the static variable and the statement block are touched.

Here is an example to summarize the above sequence:

class Cup {{    System.out.println("Block - Cup");}static int c;static {    c = 1;    System.out.println("Static Bolck - Cup");}    Cup(int marker) {        System.out.println("Construct - Cup(" + marker + ")");    }    void f(int marker) {        System.out.println("Function - f(" + marker + ")");    }}class Cups {    static {        cup1 = new Cup(1);        cup2 = new Cup(2);    }    static Cup cup1;    static Cup cup2;    {        System.out.println("Block - Cups");    }    Cups() {        System.out.println("Construct - Cups()");    }}public class JavaTest {    public static void main(String[] args) {        System.out.println("Inside main()");        Cups.cup1.f(99);  //  (1)    }}

The result of the output is:

Inside main()Static Bolck - CupBlock - CupConstruct - Cup(1)Block - CupConstruct - Cup(2)Function - f(99)

As can be seen from the above results, non-static statement blocks, or block of statements that are included in {} , are not executed when the object of the Cups class is not created. When you first create a class object or use a static variable of a class, you load the. class file, initialize the static variable, and execute the static{} statement block.

5.8 Array Initialization

An array is just the same type of object sequence or primitive type data series that is encapsulated together with an identifier name. The vegetarian group is defined and used by the square brackets subscript operator "". Defining an array requires only the type name followed by an opposite bracket: int[] a1; . Square brackets can also be placed at the back:int a1[];

The meanings of the two formats are the same, and the latter format conforms to the habits of C and C + + programmers. The previous format can be seen more visually, indicating that the type is "an array of int".

The compiler does not allow the size of the specified array, and now has only one reference to the arrays (you have allocated enough storage space for the reference), and it does not allocate any space to the array object itself. In order to create the appropriate storage space for the array, the arrays need to be initialized. The initialization code for an array can appear anywhere in the code, but you can also use a special initialization expression that must occur where the array is created. This special initialization is enclosed by a pair of curly braces, and the allocation of storage space (equivalent to using new) will be the responsibility of the compiler. For example:

int[] a1 = {1,2,3,4,5};

So why define a reference to an array when there is no array? In Java, you can assign an array to another array, int[] a2; and in Java You can assign an array to another array, so you can: a2 = A1; directly copy a reference. The following example:

public class ArrayTest {    public static void main(String[] args) {        int[] a1 = {1,2,3,4,5};        int[] a2;        a2 = a1;        for(int i = 0;i < a2.length; i++)            a2[i] = a2[i] + 1;        for(int i = 0;i < a1.length; i++)            System.out.println("a1[" + i + "]" + a[i]);    }}

Output toa1[0]=1 a1[1]=2 a1[2]=3 a1[3]=4 a1[4]=5

All arrays (regardless of the element's origin or base type) have an intrinsic member length, which can be used to get the array lengths, but it cannot be changed directly. Like C + +, Java array counting starts with 0, arrays are out of bounds, C and C + + silently accept, but Java has a direct runtime error.

You can create elements in the array by new again when programming. Although you are creating an array of primitive types, new can still work (you cannot create a single basic type of data with new).

public class ArrayNew {    public static void main(String[] args) {        int[] a;        Random rand = new Random(47);        a = new int[rand.nextInt(20)];    }}

If you create an array of non-primitive types, it is a reference array. Take the integer wrapper class integer as an example:

public class Test {    public static void main(String[] args) {        Random rand = new Random(47);        Integer[] a = new Integer[rand.nextInt(20)];    }}

Even after the array is created with new, it is only a reference array, and the initialization is completed until the new integer object is created and the object and reference are concatenated. If you forget to create an object and link objects and references, the array is full of null references, and the runtime generates an exception.

5.8.1 Variable parameter list

The variable parameter list can be used where the number of arguments or the type is unknown. For example void f(Object[] args) , a parameter in a function. This occurs before Java SE5, however, in Java SE5, add new features, you can use the new features to define a mutable parameter list, the following example:

public class NewVarArgs {    static void printArray(Object... args) {        for(Object obj : args) {            System.out.println(obj + " ");        }    }    public static void main(String[] args) {        printArray(new Integer(47), new Float(3.14), new Double(11.11));        printArray(47, 3.14F, 11.11);        printArray("one", "two", "three");    }}

With mutable parameters, you do not have to display the syntax of the writing array, when the parameters are specified, the compiler will actually go to populate the array, and finally the resulting is still an array.

5.9 Enum Types

Java SE5 Adds a seemingly small feature, the enum keyword, that makes it easy to handle when you need a group and use an enumeration set. C and C + + and in many other languages already have enumerated types, and the enumeration type functionality in Java is more complete than C + + functionality. The following is a simple example:

public enum A {    NOT, MILD, MEDIUM, HOT, FLAMING}

This creates an enumeration type named A, which has 5 values, because instances of enumerated types are constants, so the naming conventions are usually capitalized (with multiple letters underlined).

In order to use an enum, you need to create a reference to that type and join it with an instance.

public class Test {    public static void main(String[] args) {        A a = A.MEDUIM;        System.out.println(a);    }}

When you create an enumeration type, the compiler automatically adds some attributes. For example:

    • The ToString () method is created, which makes it easy to display the name of an enum instance.
    • Creates a ordinal () method that represents the order of declarations for a particular enum constant.
    • The static values () method, which is used to produce an array of these constant values in the order in which the enum constants are declared.

Examples are as follows:

public class EnumOrder {    public static void main(String[] args){        for(A a : A.values) {            System.out.println(s + ", oridinal " + a.ordinal());        }    }}输出结果为:NOT, oridinal 0MILD, oridinal 1MEDIUM, oridinal 2HOT, oridinal 3FLAMING, oridinal 4

Another particularly useful feature of the enum is that it can be used with the switch statement. Look at the following example:

    enum Pet {    Cat,    Dog,    Bird}public class JavaTest {    Pet pet;    public JavaTest(Pet p) {        pet = p;    }    public void describe() {        switch(pet) {        case Cat :            System.out.println("The pet is Cat");            break;        case Dog :            System.out.println("The pet is Dog");            break;        case Bird :            System.out.println("The pet is Bird");            break;        }    }    public static void main(String[] args) {        Pet p1 = Pet.Bird;        JavaTest test = new JavaTest(p1);        test.describe();    }}结果为:The pet is Bird

Thinking in Java Notes (fifth chapter initialization and Cleanup (iii))

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.