Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Question about Static [closed]

Tags:

java

static

I came across this bug in our code today and it took a while to figure. I found it interesting so I decided to share it. Here is a simplified version of the problem:

public class Test {

    static
    {
      text = "Hello";
    }

    public static String getTest() {
      return text + " World";
    }

    private static String text = null;
}

Guess what Test.getTest(); returns & why?

like image 984
Caner Avatar asked Jul 05 '11 13:07

Caner


People also ask

How many times static block is executed in Java?

2. Static Block. Static initializer block or static initialization block, or static clause are some other names for the static block. Static block code executes only once during the class loading.

Do you know static block in Java when is it getting executed?

Static blocks in Java are executed automatically when the class is loaded in memory. Static blocks are executed before the main() method. Static blocks are executed only once as the class file is loaded to memory. A class can have any number of static initialization blocks.

Why should we avoid using static for everything?

Code that relies on static objects can't be easily unit tested, and statics can't be easily mocked (usually). If you use statics, it is not possible to swap the implementation of the class out in order to test higher level components.

What are the restrictions when a method is declared static?

Static methods Methods declared as static have several restrictions: They can only directly call other static methods. They can only directly access static data. They cannot refer to this or super in any way.


2 Answers

It should print "null world". Static initializations are done in the order listed. If you move the declaration higher than the static block you should get "Hello World".

like image 178
sshannin Avatar answered Sep 21 '22 15:09

sshannin


It returns "null World" The documentation states that static initialization happens in the order it appears in the source code, so if you move your static block down to the bottom, it will return "Hello World"

like image 25
Loduwijk Avatar answered Sep 21 '22 15:09

Loduwijk