[Java] Initializing Varaibles

조현호_ChoHyeonHo·2025년 1월 3일
class InitTest{
	// instance variables: automatically initialized by default value(0)
	int x; 
    int y = x; // no problem. 
    
    void method1(){
    	// local variables: doesn't initialized if you don't.
    	int i; 
        int j = i; // error
    }
}

Table: Default Value for each Types

TypesDefault Value
booleanfalse
char'\u0000'
byte0
short0
int0
long0L
float0.0f
double0.0d or 0.0
reference typesnull

Three ways of initialization

1. Explicit initialization

int door = 4; : primitve type
Engine e = new Engine();: reference type

2. Initialization block: for complicated init.

클래스 초기화 블럭 - 클래스 변수의 복잡한 초기화에 사용된다.
인스턴스 초기기화 블럭 - 인스턴스 변수의 복잡한 초기화에 사용된다.

클래스 초기화 블럭은 클래스가 메모리에 처음 로딩될 때 한번만 수행되며, 인스턴스 초기화 블럭은 생성자와 같이 인스턴스를 생성할 때 마다 수행된다.

생성자보다 인스턴스 초기화 블럭이 먼저 수행된다는 사실도 기억해두자.

public class StaticBlockTest {
    static int[] arr = new int[10];
    static {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)(Math.random()*10) + 1;
        }
    }
    public static void main(String[] args) {
        for(int i = 0; i < arr.length; i++){
            System.out.printf("arr[%d] = %d%n", i, arr[i]);
        }
    }
}

Initialization order

public class InitTest {
    static int cv = 1;
    int iv = 1;

    static { cv = 2; }

    { iv = 2; }

    public InitTest() {
        iv = 3;
    }

}

Table

Code: Init Example

class Product{
    static int count = 0;
    int serialNo;

    { // runs on each Product instance init.
        ++count;
        serialNo = count;
    }

    public Product() {}
}

public class ProductTest {
    public static void main(String[] args) {
        Product p1 = new Product();
        Product p2 = new Product();
        Product p3 = new Product();
        System.out.println("p1: " + p1.serialNo);
        System.out.println("p2: " + p2.serialNo);
        System.out.println("p3: " + p3.serialNo);
        System.out.println("Product Count: " + Product.count);
    }
}

Code: Init Example2

class Document{
    static int count = 0;
    String name;

    public Document(){
        this("Unnamed" + ++count);
    }

    public Document(String name){
        this.name = name;
        System.out.printf("Document %s has been created", this.name);
        System.out.println();
    }
}

public class DocumentTest {
    public static void main(String[] args) {
        Document d1 = new Document();
        Document d2 = new Document();
        Document d3 = new Document("hoho");
        Document d4 = new Document();
    }
}
profile
Behold the rabbit hole

0개의 댓글