What is the difference between a static and a non-static initialization code block

后端 未结 8 1954
萌比男神i
萌比男神i 2020-11-21 23:32

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to

8条回答
  •  情深已故
    2020-11-22 00:16

    Uff! what is static initializer?

    The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.

    OK! Tell me more...

    • is a block of code static { ... } inside any java class. and executed by virtual machine when class is called.
    • No return statements are supported.
    • No arguments are supported.
    • No this or super are supported.

    Hmm where can I use it?

    Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.

    Don't just bark! where is example?

    package com.example.learnjava;
    
    import java.util.ArrayList;
    
    public class Fruit {
    
        static {
            System.out.println("Inside Static Initializer.");
    
            // fruits array
            ArrayList fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Orange");
            fruits.add("Pear");
    
            // print fruits
            for (String fruit : fruits) {
                System.out.println(fruit);
            }
            System.out.println("End Static Initializer.\n");
        }
    
        public static void main(String[] args) {
            System.out.println("Inside Main Method.");
        }
    }
    

    Output???

    Inside Static Initializer.

    Apple

    Orange

    Pear

    End Static Initializer.

    Inside Main Method.

    Hope this helps!

提交回复
热议问题