java anonymous statement or what it is called? - java

I would like to understand what is this called. I saw this program in oracle website. I have kept breakpoint and saw this statment is called after static block and before constructor is called.
What is signifiance of this statement ?
{
System.out.print("y ");
}
In this code :
public class Sequence {
Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}

static {
System.out.print("x ");
}
Its the static block and its called whenever class is loaded. In general anonymous means which does not have any name like anonymous class are clases which does not have any name and their implementation is provided right at the place where it is required and can't be reused
{
System.out.print("y ");
}
As Eran commented out ,It's an instance initialization block, and it's executed whenever an instance is created and is called even before constructor.

It is an initializer block. It is executed whenever a new instance of a class is created. Most of the time you don't really need it, because instance initialization can also be put in the constructor. The initializer block is mainly there to initialize anonymous inner classes, for which you cannot define your own constructors (because to define a constructor you need the name of the class).

This is known as a static initialization block, or static initializer.
See: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Personally, I prefer not to use them exactly for the reason stated in the documentation I sited.
There is an alternative to static blocks — you can write a private
static method: The advantage of private static methods is that they
can be reused later if you need to reinitialize the class variable.

Related

why does this weird java code of only static blocks compile? [duplicate]

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 any function. For example following code compiles:
public class Test {
private static final int a;
static {
a = 5;
doSomething(a);
}
private static int doSomething(int x) {
return (x+5);
}
}
If you remove the static keyword it complains because the variable a is final. However it is possible to remove both final and static keywords and make it compile.
It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".
If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.
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<String> 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.
The static block is a "static initializer".
It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).
I've personally only ever used it when writing JNI code:
class JNIGlue {
static {
System.loadLibrary("foo");
}
}
This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/
1. Execution Order
Look at the following class, do you know which one gets executed first?
public class Foo {
//instance variable initializer
String s = "abc";
//constructor
public Foo() {
System.out.println("constructor called");
}
//static initializer
static {
System.out.println("static initializer called");
}
//instance initializer
{
System.out.println("instance initializer called");
}
public static void main(String[] args) {
new Foo();
new Foo();
}
}
Output:
static initializer called
instance initializer called
constructor called
instance initializer called
constructor called
2. How do Java instance initializer work?
The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.
Instead of
int b = 0, you could write
int b;
b = 0;
Therefore, instance initializers and instance variable initializers are pretty much the same.
3. When are instance initializers useful?
The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:
Initializer code must handle exceptions
Perform calculations that can’t be expressed with an instance variable initializer.
Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.
With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)
Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)
Thanks to Derhein.
Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.
"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.
You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.
You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..
A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
class MyClass {
private int myField = 3;
{
myField = myField + 2;
//myField is worth 5 for all instance
}
public MyClass() {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
is equivalent to:
class MyClass {
private int myField = 3;
public MyClass() {
myField = myField + 2;
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
myField = myField + 2;
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
I hope my example is understood by developers.
The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.
The static initializer blocks are invoked (in the order they were defined in) when the JVM loads the class into memory, and before the main method. It's used to conditionally initialize static variables.
Similarly we have the instance initializer blocks (aka IIBs) which are invoked upon object instantiation, and they're generally used to de-duplicate constructor logic.
The order in which initializers and constructors are executed is:
Static initializer blocks;
Object initializer blocks;
Constructors;

If a class contain an anonymous block having system.out.println(); [duplicate]

I have two classes Parent and Child
public class Parent {
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}
public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}
public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}
The output of the above code will be
Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor
Why does Java execute the code in that order? What are the rules that determine the execution order?
I learn visually, so here's a visual representation of order, as a SSCCE:
public class Example {
static {
step(1);
}
public static int step_2 = step(2);
public int step_8 = step(8);
public Example(int unused) {
super();
step(10);
}
{
step(9);
}
// Just for demonstration purposes:
public static int step(int step) {
System.out.println("Step " + step);
return step;
}
}
public class ExampleSubclass extends Example {
{
step(11);
}
public static int step_3 = step(3);
public int step_12 = step(12);
static {
step(4);
}
public ExampleSubclass(int unused) {
super(step(7));
step(13);
}
public static void main(String[] args) {
step(5);
new ExampleSubclass(step(6));
step(14);
}
}
This prints:
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12
Step 13
Step 14
Keep in mind that the order of the static parts matters; look back at the difference between the order of Example's static stuff and ExampleSubclass's.
Also note that the instance initialization block is always executed immediately after the super() call in the constructor (even if that call is implied/omitted), no matter the order. However, order does matter between an initialization block and a field initializer.
There are several rules in play
static blocks are always run before the object is created, so that's why you see print messages from both parents and child static blocks
now, when you are calling constructor of the subclass (child), then this constructor implicitly calls super(); before executing it's own constructor. Initialization block comes into play even before the constructor call, so that's why it is called first. So now your parent is created and the program can continue creating child class which will undergo the same process.
Explanations:
Static block of parent is executed first because it is loaded first and static blocks are called when the class is loaded.
First - run child class only (comment the extend clause) to see the simple flow.
second - go to Static block vs. initializer block in Java? & read the accepted answer over there.
Edit:
Execution happens in SIC way - Static, (non static) Initializer & Constructor.
(Non static) Initializer are copied into every constructor - At the TOP! (hence lines 3/4/5/6)
Before a class is initialized, its direct superclass must be initialized - http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4 (hence parent static block appears first).
Static init blocks are executed at the time of class loading.
In the class hierarchy the order for execution of static init blocks will start from top level class.
In a class the order for the execution of static block is from top to bottom.
Above rule apply regardless of where the static block is present within the class.
(In your code the parent static blocks will be executed first and then the child class static blocks.)
Instance init blocks will be executed after the call to the super(); in the constructor.
Always super(); is the very first statement in a default constructor.
In your code when you create a Child object:
The default constructor of the Child class get executed.
It will call to the super(); constructor.
Then the super class constructor is executed.
The Parent class will execute its super(); call.
After that the instance init blocks in the Parent class are executed.(From top to bottom).
Then the code within the constructor is executed (if any).
Then it will return to the Child class and execute the Child class instance init blocks.
Finally the code in the child constructor get executed (If exists).
Static block in java is executed before main method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static variables. It is mostly used in JDBC. Static block in java is executed every time when a class loads. This is also known as Static initialization block. Static block in java initializes when class load into memory , it means when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is preceded by static keyword.
so static block executed first.
Instance Initialization Blocks: Runs every time when the instance of the class is created.
so next Initialization block executed when instance of the class is created.
then Constructor executed
Just wanted to share my findings.
I read in one of the answers on another thread that static blocks are executed first before static fields which is not correct. It depends on which comes first, static field or static block. Have a look at below code. It will try to put things in perspective.
JVM looks for a class which has public static void main(String args[]) so that it can load that class.
It then initialises static fields of this class(if they come before static blocks). These fields can call static methods of this class or another. If they call static method of this class then that method gets served. If they call static method of another class, then static fields or blocks of that class(depending on which comes first) gets initialised first, then this method call is served.
Then, it moves to static blocks.
It comes back to main method.
class TestLab {
static int method(String a) {
System.out.println("in static method of TestLab" + " Coming from " + a);
System.out.println("b is " + b);
return 6;
}
static int a = method("Line 11");
static int b = 7;
TestLab() {
System.out.println("Inside test lab constructor");
}
static {
System.out.println("In static block of TestLab");
}
}
public class Test1 {
public static void main(String[] args) {
System.out.println("inside main method of Test 1");
int a = TestLab.method("Line 26");
}
// static Test ref=new Test();
Test1() {
System.out.println("Default Constructor of Test1");
}
{
System.out.println("In instance block of Test1");
}
static int d = TestLab.method("Line 37");
static int e = methodOfTest1();
static {
System.out.println("In Static Block of Test1");
}
static int methodOfTest1() {
System.out.println("inside static method:mehtodOfTest1()");
return 3;
}
}
Here is the output:
in static method of TestLab Coming from Line 11
b is 0
In static block of TestLab
in static method of TestLab Coming from Line 37
b is 7
inside static method:mehtodOfTest1()
In Static Block of Test1
inside main method of Test 1
in static method of TestLab Coming from Line 26
b is 7
It would be very helpful to ckeck out the object construction process with a step by step debuger, having a view in which you can see how your object is goning through the phases. I found this very useful for clearing the perspective from a higher point of view. Eclipse can help you with this with it's debugger step into function.
Here is what I found while preparing for a certification.
While we run a class, first static blocks/ static variable initialisation happens. If multiple static blocks are there, it will execute it in the order in which it appears,
Then it will execute init blocks/ instance variable initialisation.If multiple init blocks/ variable initialisation are there, it will execute it in the order in which it appears,
Afterwards it will look into the constructor.
Static block gets executed when a class is loaded into JVM. While init block gets copied into the Constructor whose object will be created and runs before creation of object.
control flow is-
static block -> Initialization block -> and finally Constructor.
static block -> This static block will be get executed only once when the control come to the class.(JVM Load this class)
Initialization block -> This Initialization block will be get executed whenever a new object Created for the Class (It will be executed from second statement of the Constructor then following constructor statements- remember First statement of the Constructor will be Super()/this())
Constructor -> This will be get whenever a new object is created.
Static init block executes at the time of class loading only ones.
Init block executes every time before creating object of the class.
Learn more with this video: Java Tutorial by Rajan Jain : Static Init Block and Init Block in java Video14 - YouTube

Java default constructor without initialization

I have a class similar to the below one with all static methods. Hence the class was not initialized while used in other classes. I have to check a condition before invoking any static methods from this class. Even if i add a default constructor it will not get called. Could someone suggest ideas to have solution without instantiating this class in all of its usages? It need be a default constructor could be a simple other solution.
I need to check everytime the network connectivity before making the call. Static Initializer gets called only first time on load.
public class ABCServerUtil {
public static boolean checkServer() {...bla...bla...}
}
I need some thing like below piece of code to be called and to be exit.
public ABCServerUtil(){
if(!isNetworkOnline())
return;
}
If you need to check the condition every time one of the static methods is called, you don't have much choice but to do what you're doing: Call a method to do the check at the beginning of each of those methods.
If you only need to check the condition once when the class is initially loaded/initialized, you can use a static initializer:
public class ABCServerUtil {
static {
// Code here runs when the class is loaded
}
// ...
}
Use a static Initialization block
static {
//whatever code for initialization
}
A class can have any number of static initialization blocks
they can appear anywhere in the class body
static initialization blocks are called in the order that they appear in the source code.
You should be called every time when method called
public class Test {
public static void checkServer() {
if (!checkNetwork()) {
return;
}
}
public static void checkClient() {
if (!checkNetwork()) {
return;
}
}
private static boolean checkNetwork() {
return true; // or false depending on network condition
}
}
You can use a static initialiser.
static {
// code here
}
It will be run before any method of property (static or otherwise) of the class is first accessed.
you can directly call a static method with the class name like this,
boolean val=ABCServerUtil.checkServer();
some tutorial is given here
Since there's already 5 answers saying the same thing and none of them seem to be what you're after:
A tool like Byte Buddy sounds like what you need.
I think that this is your solution: Static initializer in Java
In practice you need a block of code executed the first time that your class is loaded.

How is the Static method(main) able to grab hold of non static method(constructor) and execute it?

Seems like a very basic query but I was pondering how the static method main() below is able to execute a non static method(the constructor obviously) from it using the new keyword. Though I understand that new brings onto the table a few other things as well but how should I convince myself that this isn't an exception to the rule that static and non static methods can't using non static and static context respectively?
Below is the sample code:
public class ConstructorTest {
ConstructorTest(String str)
{
System.out.println("Constructor Printing "+str);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorTest cnst=new ConstructorTest("here");
}
}
The above code actually prints --> Constructor Printing here
or in other words executing the body of a Non static method from a Static method?
Any plausible explanations are welcome.
The Java Tutorial states that
[...] Constructors are not members.
Therefore, there is no problem in calling them, since they are not bound to instances of your class. This would not make sense - hence, you cannot do the following:
Thing thing = new Thing();
Thing anotherThing = thing.Thing();
A constructor is not a method, so you cannot apply "method logic" to them.
In case you want to know more, the whole instantiation process is very well documented in the JLS. See 12.5. Creation of New Class Instances.
Actually constructor is compiled into the static method, this is how JVM internally creates instances of classes.
You are executing non-static code, but you are not doing it in a static context.
for instance:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
do();
}
}
This can not work, since do is an instance method, which might run code that is specific to the instance. So, how would the VM know which instance to use, or what value x should have?
Now, to first use a constructor, which is possible from any context:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
C1 t = new C1();
t.do();
}
}
Here, even though you are calling the method from within a static method, you are using it through an instance, so not in a static context.
ConstructorTest is not a method.
its an constructor,and you can use the constructor for initialize class property.
you can also initialize the static variable from the constructor like that :-
public class XYZ
{
static int i=0;
public XYZ() {
i=1;//not an compile time error
}
public static void doSome(){}
public static void main(String[] args) {
}
}
On a formal language level you should read the line
ConstructorTest cnst = new ConstructorTest("here")
as a class instance creation expression. As a matter of fact, this is not a call to a constructor or any other method.
The instance creation does many steps, like allocating memory for the new object, initializing the fields, calling constructors and initializer blocks. See JLS §12.5 for a detailed step-by-step description. Thus being said, the constructor invocation is only a part of the instance creation.
Additionally, you might see constructors as being static parts of the class. In fact, constructor declaration are not members (see JLS §8.8) and thus they are not overridable (as static methods also). Beware: This is only half true. When being inside the constructor you already have the instance created, and you are able to call other instance methods and/or access instance fields.

What does the {{ syntax on ArrayList initializer really do

I have recently found what appears to me to be a new syntax for statically initializing an ArrayList:
new ArrayList() {{
add("first");
add("second");
}};
My question is, what is really happening there? Is that a shortcut for defining a static block (I thought it would need the static keyword)? Or just a way to define a default constructor? Something else? What version of Java did this become valid?
An explanation plus a link to further reading would be greatly appreciated.
edit:
My test class for showing whether initializer block executes before or after the constructor is below. Results show that initializer blocks execute before the other constructor code:
import org.junit.Test;
public class InitializerBlockTest {
class InitializerTest {
{
System.out.println("Running initalizer block");
}
public InitializerTest() {
System.out.println("Running default constructor");
}
}
class SubClass extends InitializerTest {
{
System.out.println("Running subclass Initializer block");
}
public SubClass() {
System.out.println("Running subclass constructor");
}
}
#Test
public void testIt() {
new SubClass();
}
}
Output:
Running initalizer block
Running default constructor
Running subclass Initializer block
Running subclass constructor
You are creating a new anonymous subclass of ArrayList, with an instance initializer which calls add() twice.
It's the same as:
class MyList extends ArrayList
{
{ // This is an instance initializer; the code is invoked before the constructor.
add("first");
add("second");
}
public MyList() {
super();
// I believe initializers run here, but I have never specifically tested this
}
}
...
List list=new MyList();
Note that, personally, I do not advise it as an idiom, since it will lead to class-file explosion.
It is an initializer block for instance variables.
From Oracle's documentation:
Initializer blocks for instance
variables look just like static
initializer blocks, but without the
static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer
blocks into every constructor.
Therefore, this approach can be used
to share a block of code between
multiple constructors.
See: http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
When you write new ArrayList() { } you are creating an anonymous subclass of ArrayList. The { } as in the innermost brackets in your code denote an initializer block and is actually copied into every constructor.
EDIT: You guys sure answer fast!

Categories