Java Tricky Program 1 - Java Compiler Optimization

preview_player
Показать описание
A program where output seems simple but it's not because of java compiler optimization of the byte code.

From Java Specs:
If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
Рекомендации по теме
Комментарии
Автор

thanks !! indeed tricky questions set.... Please keep posting more of these.

omkarjoshi
Автор

Hi, Sir the information which is you are providing is very useful. I have tried the same program with small change like "assigned the final variable in a static block " in this scenario the static block is executing first. So can you please explain the scenario once.

satyavarapujagadeeswararao
Автор

I think this happens because there is no object instantiation with the keyword new (that is the reason static code is never called). It is very interesting to add a constructor in class T that simply prints a message and in the main program to instantiate 2 objects. The static code will be called once.

georgegeorgiadis
Автор

sir what is this static block ...is it a function, if it is why it doesnt have some name?

shubhamchaudhary
Автор

What if Class Test extends Class T? what will be the output

virendrayadav
Автор

you cannot initialize static block in inner class unless it is static inner class

tamalsaha
Автор

Hi Pankaj

Which tool you are using for this screen cast?

johnkanathon
Автор

What if x in initialised as default Int?

SandeepKumar-jqet
Автор

thank you sir for such a trick program

sandeepmaurya
Автор

This program will compile only when inner class is static.

MrRobot-oxox
Автор

This program will compile only when inner class is static. :)

debadattabiswal
Автор

class Test {
public static void main(String[] args) {
T t = new T();
System.out.println(t.x);
}
}

class T {
public final int x = 100;

static {
System.out.printf("T loaded");
}
}


in the above class x is also final but it is printed T loaded data.

lkhore