What is Static Initialization Blocks? and their alternatives in Java?

Why we need Static Initialization Blocks?

The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:

public class InitializationWithConstants{

public static int staticIntField = 100;
private boolean instanceBoolField = true;

}

This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic – like initializing only selected elements of a complex array using some logic in a for loop statement.

Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.

Static Initialization Blocks – what are they and how to use them?

It’s a normal block of code enclosed in a pair of braces and preceded by a ‘static’ keyword. These blocks can be put anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code and this happens while loading of the class in the memory.

public class InitializationWithStaticInitBlock{

public static int staticIntField;
private boolean instanceBoolField = true;

static{
//compute the value of an int variable 'x'
staticIntField = x;
}
}

Since static initialization blocks are actually code-blocks so they will allow us to initialize even those static fields which require some logical processing to be done for them to get their initial values.

Alternative:

A private static method is a suitable alternative to the static initialization blocks. In fact it has some advantages over static initialization blocks as well like you can re-use a private static method to re-initialize a static field in case you need it. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a ‘public’ static method can’t do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method ‘public’.

public class InitializationWithPrivateStaticMethod{

public static int staticIntField = privStatMeth();
private boolean instanceBoolField = true;

private static int privStatMeth() {
//compute the value of an int variable 'x'
return x;
}
}

Why String Class is made Immutable or Final in Java?

string1

Performance is a reason. But the MAIN REASON is about SECURITY. Are you surprised about this?
OK I’ll let you know..

Suppose you want to open a secured file which require the user authentication. Let’s say there are two users named huynguyen1 and huynguyen2 and they have their own password files password1 and password2, respectively. Obviously huynguyen2 should not have access to password1 file.
As we know the filenames in Java are specified by using String. Even if you create a File object, passing the name of file as a String only and that String is maintained inside the File object as one of its members.


huynguyen1 could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from password1 to password2 before JVM actually places the native OS system call to open the file. This would have allowed huynguyen1 to open huynguyen2‘s password file.

Understandably, it would have resulted into a big security flaw in Java. I understand there are so many ‘could have’s here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.

With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged filename String object. The filename instance member being a final in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).

Cheers.
Huy Nguyen.

Feel free to contact me via email: contact@alway5.com

Trong Java có Destructor không, Garbage Collection (GC) là gì?

0001

– garbage collector –

 

Không có destructor.

Java có cơ chế “tự động dọn rác”. Vì là tự động nên ta không thể biết được khi nào một đối tượng “rác” sẽ bị hủy.

Có một phương thức con được gọi là finalize. Nó được gọi tự động bởi “cơ chế thu dọn” (GC), có thể xem đây tương tự như một destructor nhưng thực tế nó lại không phải. Để biết sâu hơn về thằng này thì vui lòng  xem tại đây.

Khi khởi tạo đối tượng, các đối tượng được phân bố trên vùng nhớ heap.

Ta xem ví dụ sau:
YourClass a = new YourClass();
Thì đối tượng (object) a được tạo ta và được gán tham chiếu (reference) đến biến a. Lúc khác, ta gán b = a thì khi này 2 biến a b cùng tham chiếu đến cùng một đối tượng, số lượng biến tham chiếu tăng lên 1.

Tuy nhiên, Khi ta gán a = new YourOtherClass() thì số tham chiếu giảm đi 1 (a bây giờ không còn chỉ đến đối tượng cũ nữa). GC kiểm soát việc đó một cách tự động, trong trường hợp nếu như một đối tượng không được ai tham chiếu đến thì đối tượng đó được coi là rác, sau đó sẽ tự động được giải phóng, nếu bạn nào học C/C++ có lẽ đã biết qua lệnh delete hay free rồi nhỉ? Tóm lại nó là như thế. Với một ngôn ngữ như Java, C#.. thì việc quản lí bộ nhớ đã được tự động hóa lên rồi đúng không :)

Để thảo luận thêm về vấn đề này thì các bạn vào ĐÂY nhé!

Mọi góp ý vui lòng gửi về mail n@mhuy.xyz :)