Initialization and cleanup of Java basics

Source: Internet
Author: User
Tags naming convention

using constructors to ensure initialization
The constructor is the same as the class name; it is a special type of method because it does not return a value.
When an object is created, the object is allocated storage space and the corresponding constructor is called.
Constructors that do not contain any arguments are called default constructors
Method Overloading
Class Person {public Person    () {} Public person    (string name) {} "public person"    (string Name,int age) {}}
    • Distinguishing overloads
Each method has a unique list of parameter types
    • Method overloading
1. If the incoming data type is less than the formal parameter type declared in the method, the actual data type is promoted; char is slightly different, and if you cannot find a method that exactly accepts the char parameter, the char is promoted directly to the INT type
2. If the actual parameter passed in is greater than the formal parameter of the overloaded method declaration, a cast is required, or the compiler will error. Eg:void Test (Byte b) {}int i = 5;test (i);//compiler will error
default constructor
The default constructor is also known as the "parameterless" constructor, which is not a formal parameter.
If there are no constructors in the class, the compiler will automatically create a default constructor for you.
    • Role
Used to create a "default object"
This keyword
The This keyword can only be used inside a method, representing a reference to the "object calling the method"
If another method of the same class is called inside a method, you do not have to use this to call directly
Class Test {    private test () {} public    Test newinstance () {        return this;    }}
    • Calling the constructor in the constructor
Class Test {    String s;    Public Test () {This ("Test");}    Public Test (String s) {THIS.S = s;}}
Only one constructor can be called with this in the constructor and must be placed at the initial
Compiler prevents other methods from calling the constructor except the constructor
    • The meaning of static
The static method can be called through the class itself, or it can be invoked through an object.
The static method is the method without this
A non-static method cannot be called inside a static method, which in turn is possible.
cleanup: End processing and garbage collection
The Java garbage collector is responsible for reclaiming memory resources occupied by useless objects
The garbage collector knows only to release the memory allocated through new
    • What is the purpose of finalize ()
Once the garbage collector is ready to release the storage space occupied by the object, its finalize () is called first, and the memory consumed by the object is actually reclaimed when the next garbage collection action is sent
Neither "garbage collection" nor "termination" is guaranteed to occur. If the Java Virtual Machine (JVM) does not face memory exhaustion, it does not waste time performing garbage collection to recover memory.
System.GC () to force the finalization action
The Java Virtual Machine employs an adaptive garbage collection technology.
    • Self-adapting technology
Tag-sweep: From the stack and static storage, traverse all references to find all the surviving objects. Whenever it finds a surviving object, it sets a tag for the object, and the process does not reclaim any objects. The cleanup action will only begin when all marks are completed. During the cleanup process, objects that are not marked are freed and no copy actions occur. Stop-copy: Pauses the program's run, then copies all the surviving objects from the current heap to the other heap, all of which are garbage. Both "Mark-sweep" and "stop-copy" are performed when the program is paused. Java Virtual opportunities are monitored, and if all objects are stable and the garbage collector becomes less efficient, switch to the "mark-sweep" mode, and the Java Virtual Opportunity tracks the "mark-sweep" effect, and if there is a lot of fragmentation in the heap space, it switches back to "stop-copy" mode
    • Attention
1. Objects may not be garbage collected 2. Garbage collection is not equal to "destruction" 3. Garbage collection is only about content
member Initialization
The local variable of the method is not initialized and an error is compiled
    • Default initialization
The data member of the class is not initialized and is given the default initial value boolean:falsechar:0 (blank) byte,short,int,long:0float,double:0.0 object: null
    • Specify initialization (auto-initialize)
Assign a value to a class member variable where it is defined
Class Test {    int i = 10;//mode 1    Int j = getnum (i);//mode 2    private int getnum (int i) {        return i *;    }}
Constructor Initialization
At run time, you can invoke a method or perform certain actions to determine the initial value
Cannot prevent automatic initialization from occurring, it will occur before the constructor is called
    • Initialization of static data
The static keyword cannot be applied to local variables, no matter how many objects are created, static data only takes one copy of the storage area static initialization occurs only at the necessary time, and static initialization occurs only once when the class object is first loaded
    • The creation process of an object

Suppose there's a class for dog

1. The first time a dog object is created (or the first time the static/static domain of a dog is accessed), the compiler first finds the Dog.class file 2. Load Dog.class to perform all actions related to static initialization 3. When you create an object with new Dog (), First allocate enough storage space on the heap for the Dog object 4. This storage space is zeroed, setting all the basic type data in the dog object to the default (default initialization), and setting the reference to NULL5. Performs all initialization actions that appear with the field definition (specify initialization) 6. Execution constructor
    • Order of initialization
The order in which the variables are defined determines the order in which they are initialized, even if the variable definitions are scattered between the method definitions, and they will still be initialized before any methods (including constructors) are called.
When new Hello (), the object creation order is t1,t2,t3,t4,t5,t6//static Object-static code block initialization-Display initialization-construct code block initialization-constructor initializes class Test {public    Test (int m Arker) {        System.out.println ("Test (" + marker + ")");}    } Class Hello {    static Test T1 = new Test (1);    Test t3 = new test (3);    Test T4;    Test T5;    static {        //code block, execute only 1 times        test t2 = new Test (2);    }    {        //constructs a code block that initializes before the constructor, regardless of which constructor is called, and executes the initialization        T4 = new Test (4);    }    Public Hello () {        T5 = new Test (5);        Test T6 = new test (6);}    }
Array Initialization
    • Defining arrays
Type after adding [], such as int[] i; or int i[];
    • Array initialization
Int[] i = {1,2,3};integer[] a = new integer[]{new integer (1), 2,new Integer (3)};
Int[] J = new INT[10];
Random rand = new Random (); int[] A = new Int[rand.nextint (20)];
object[] obj = new object[]{new Integer (1), New Float (2.0), new Double (3.0)};object[] objects = new integer[]{1,2,3};
    • Variable parameter list
Class Test {public    static void Main (string[] args) {        test test = new test ();        Test.printarray (1, New String ("Hello"), New Float (2.0));        Test.printarray (2, (object[]) new string[] {"Hello", "World"});        Test.printarray (0);    }    public void PrintArray (int num, Object ... objects) {        System.out.print (num + "");        For (object object:objects) {            System.out.print (object + "");        }        System.out.println ();    }}
Enum Type
Because an instance of an enumeration type is a constant, it is represented by a naming convention in uppercase letters
Enumeration types can be used within a switch statement
Class Test {public    enum Animal {        PIG, DOG, SHEEP, DUCK, WOLF    } public    static void Main (string[] args) {
    for (Animal animal:Animal.values ()) {            System.out.println (animal.ordinal () + ":" + Animal);        }        Animal Animal = Animal.pig;        System.out.print (animal);    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Initialization and cleanup of Java basics

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.