Initialization and cleanup of JAVA Basics __java

Source: Internet
Author: User
using constructors to ensure initialization
The constructor is the same as the class name; is a special type of method because it has no return value.
When an object is created, the object is allocated storage space and the corresponding constructor is invoked.
Constructors that do not contain any parameters are called default constructors
method overload
Class Person {public Person
    () {} ' public person (
    string name) {} ' Public person
    (String Name,int age) {}
}
distinguishing between Overloads
Each method has a unique list of parameter types
method overload
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 a method that just accepts the char parameter cannot be found, the char is raised directly to the int type
2. If the actual parameter passed in is greater than the formal argument of the overloaded method declaration, a cast is required, otherwise the compiler will complain.
eg:
void Test (Byte b) {}

int i = 5;
Test (i);//compiler will complain
default Builder
The default constructor, also known as the "parameterless" constructor, is without formal arguments.
If there is no constructor in the class, the compiler will automatically create a default constructor for you.
function
Used to create a "default object"
This keyword
The This keyword can only be used within a method, representing a reference to the object that invokes the method
If you call another method of the same class inside a method, you do not have to use this, you can call it directly
Class Test {
    private test () {} public
    Test newinstance () {return this
        ;
    }
}
to invoke 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
In addition to constructors, the compiler prevents other methods from calling the constructor
the meaning of static
The static method can be invoked through the class itself, or it can be invoked by an object.
The static method is a method without this
Non-static methods cannot be invoked inside the 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 unwanted objects
The garbage collector only knows to release the memory allocated via 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 occupied by the object is actually reclaimed when the next garbage collection action is sent.
Whether it's "garbage collection" or "end", there is no guarantee that it will happen.
If the Java Virtual Machine (JVM) is not running out of memory, it does not waste time doing garbage collection to recover memory.
System.GC () is used to force an end action
Java Virtual machines Adopt an adaptive garbage collection technology.
self-adapting technology
Tag-sweep:
start from the stack and static storage, iterate through all the references, and find all the surviving objects.
whenever it finds a surviving object, it sets a tag on the object, and no objects are reclaimed in the process. The
cleanup action begins only when all the tags are complete. During the
cleanup process, objects that are not marked are freed and no replication action occurs.

stop-copy:
suspends the operation of the program, and then copies all the surviving objects from the current heap to another heap, and all that is not replicated is garbage.

"Mark-sweep" and "stop-copy" are not performed until the program is paused.

Java Virtual opportunities for monitoring, if all objects are stable, the garbage collector is inefficient, switch to the "tag-sweep" way;
Similarly, Java Virtual opportunity to track the "tag-sweep" effect, if heap space appears many fragments, will switch back to stop-copy Way
Attention
1. Objects may not be garbage collected
2. Garbage collection is not equal to "destructor"
3. Garbage collection is about content only
member Initialization
The local variable of the method is not initialized and an error is compiled
Default Initialization
The data members of the class are not initialized and are given the default initial value

boolean:false
char:0 (blank)
byte,short,int,long:0
float,double:0.0
Objects: null
Specify initialization (automatic initialization)
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 call a method or perform certain actions to determine the initial value
Cannot prevent automatic initialization, which occurs before the constructor is invoked
initialization of static data
The static keyword cannot be applied to a local variable, and no matter how many objects are created, it takes up only 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
Object creation Process

Suppose there is a class of dog

1. When the first time a Dog object is created (or a Dog static method/static domain is first accessed), the compiler first finds Dog.class file
2. Load Dog.class, perform all actions on static initialization
3. When you create an object using the new Dog (), First, allocate enough storage space for the dog object on the heap
4. This storage space is zeroed, setting all the base type data in the dog object to the default (default initialization), and setting the reference to null
5. Performs all the initialization actions that appear with the field definition (specify initialization)
6. Execution Builder
Order of initialization
The order in which the variables are defined determines the order in which they are initialized, even if they are spread between the definition of the method, and they are still initialized before any method, including the constructor, is invoked.
When new Hello (), object creation Order is T1,T2,T3,T4,T5,T6
//Static Object-static code block initialization-show initialization-construct code block initialization-constructor initialization
class Test {public
    Test (int marker) {
        System.out.println ("Test (+ marker +)");
    }

Class Hello {
    static Test T1 = new Test (1);
    Test t3 = new test (3);
    Test T4;
    Test T5;

    static {
        //static code block, only 1 times
        test t2 = new Test (2);

    {
        ///construct a code block that is initialized before the constructor, which executes the initialization
        T4 = new Test (4), regardless of which constructor is invoked
    ;

    Public Hello () {
        T5 = new Test (5);
        Test T6 = new test (6);
    }
}
Array Initialization Defining Arrays
Type is added [], 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 M  Ain (string[] args) {for (Animal animal:Animal.values ()) {System.out.println (animal.ordinal () + ":
        "+ animal);
        } Animal Animal = Animal.pig;
    System.out.print (animal); }
}

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.