Java curly braces syntax without method or static block? [duplicate] - java

We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?

First of all, there are two types of initialization blocks:
instance initialization blocks, and
static initialization blocks.
This code should illustrate the use of them and in which order they are executed:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized)
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
Prints:
Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.
Instance initialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.

would like to add to #aioobe's answer
Order of execution:
static initialization blocks of super classes
static initialization blocks of the class
instance initialization blocks of super classes
constructors of super classes
instance initialization blocks of the class
constructor of the class.
A couple of additional points to keep in mind (point 1 is reiteration of #aioobe's answer):
The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.
The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.

nice answer by aioobe
adding few more points
public class StaticTest extends parent {
static {
System.out.println("inside satic block");
}
StaticTest() {
System.out.println("inside constructor of child");
}
{
System.out.println("inside initialization block");
}
public static void main(String[] args) {
new StaticTest();
new StaticTest();
System.out.println("inside main");
}
}
class parent {
static {
System.out.println("inside parent Static block");
}
{
System.out.println("inside parent initialisation block");
}
parent() {
System.out.println("inside parent constructor");
}
}
this gives
inside parent Static block
inside satic block
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside main
its like stating the obvious but seems a little more clear.

The sample code, which is approved as an answer here is correct, but I disagree with it. It does not shows what is happening and I'm going to show you a good example to understand how actually the JVM works:
package test;
class A {
A() {
print();
}
void print() {
System.out.println("A");
}
}
class B extends A {
static int staticVariable2 = 123456;
static int staticVariable;
static
{
System.out.println(staticVariable2);
System.out.println("Static Initialization block");
staticVariable = Math.round(3.5f);
}
int instanceVariable;
{
System.out.println("Initialization block");
instanceVariable = Math.round(3.5f);
staticVariable = Math.round(3.5f);
}
B() {
System.out.println("Constructor");
}
public static void main(String[] args) {
A a = new B();
a.print();
System.out.println("main");
}
void print() {
System.out.println(instanceVariable);
}
static void somethingElse() {
System.out.println("Static method");
}
}
Before to start commenting on the source code, I'll give you a short explanation of static variables of a class:
First thing is that they are called class variables, they belong to the class not to particular instance of the class. All instances of the class share this static(class) variable. Each and every variable has a default value, depending on primitive or reference type. Another thing is when you reassign the static variable in some of the members of the class (initialization blocks, constructors, methods, properties) and doing so you are changing the value of the static variable not for particular instance, you are changing it for all instances. To conclude static part I will say that the static variables of a class are created not when you instantiate for first time the class, they are created when you define your class, they exist in JVM without the need of any instances. Therefor the correct access of static members from external class (class in which they are not defined) is by using the class name following by dot and then the static member, which you want to access (template: <CLASS_NAME>.<STATIC_VARIABLE_NAME>).
Now let's look at the code above:
The entry point is the main method - there are just three lines of code. I want to refer to the example which is currently approved. According to it the first thing which must be printed after printing "Static Initialization block" is "Initialization block" and here is my disagreement, the non-static initialization block is not called before the constructor, it is called before any initializations of the constructors of the class in which the initialization block is defined. The constructor of the class is the first thing involved when you create an object (instance of the class) and then when you enter the constructor the first part called is either implicit (default) super constructor or explicit super constructor or explicit call to another overloaded constructor (but at some point if there is a chain of overloaded constructors, the last one calls a super constructor, implicitly or explicitly).
There is polymorphic creation of an object, but before to enter the class B and its main method, the JVM initializes all class(static) variables, then goes through the static initialization blocks if any exist and then enters the class B and starts with the execution of the main method. It goes to the constructor of class B then immediately (implicitly) calls constructor of class A, using polymorphism the method(overridden method) called in the body of the constructor of class A is the one which is defined in class B and in this case the variable named instanceVariable is used before reinitialization. After closing the constructor of class B the thread is returned to constructor of class B but it goes first to the non-static initialization block before printing "Constructor". For better understanding debug it with some IDE, I prefer Eclipse.

Initializer block contains the code that is always executed whenever
an instance is created. It is used to declare/initialise the common
part of various constructors of a class.
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.
What if we want to execute some code once for all objects of a class?
We use Static Block in Java.

In addition to what was said in previous answers, blocks can be synchronized .. never felt I need to use it, however,it's there

Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. It is not at all necessary to include them in your classes.
They are typically used to initialize reference variables. This page gives a good explanation

The question is not entirely clear, but here's a brief description of ways you can initialise data in an object. Let's suppose you have a class A that holds a list of objects.
1) Put initial values in the field declaration:
class A {
private List<Object> data = new ArrayList<Object>();
}
2) Assign initial values in the constructor:
class A {
private List<Object> data;
public A() {
data = new ArrayList<Object>();
}
}
These both assume that you do not want to pass "data" as a constructor argument.
Things get a little tricky if you mix overloaded constructors with internal data like above. Consider:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
data = new ArrayList<Object>();
name = "Default name";
userFriendlyName = "Default user friendly name";
}
public B(String name) {
data = new ArrayList<Object>();
this.name = name;
userFriendlyName = name;
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
Notice that there is a lot of repeated code. You can fix this by making constructors call each other, or you can have a private initialisation method that each constructor calls:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
this("Default name", "Default user friendly name");
}
public B(String name) {
this(name, name);
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
or
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
init("Default name", "Default user friendly name");
}
public B(String name) {
init(name, name);
}
public B(String name, String userFriendlyName) {
init(name, userFriendlyName);
}
private void init(String _name, String _userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
The two are (more or less) equivalent.
I hope that gives you some hints on how to initialise data in your objects. I won't talk about static initialisation blocks as that's probably a bit advanced at the moment.
EDIT: I've interpreted your question as "how do I initialise my instance variables", not "how do initialiser blocks work" as initialiser blocks are a relatively advanced concept, and from the tone of the question it seems you're asking about the simpler concept. I could be wrong.

public class StaticInitializationBlock {
static int staticVariable;
int instanceVariable;
// Static Initialization Block
static {
System.out.println("Static block");
staticVariable = 5;
}
// Instance Initialization Block
{
instanceVariable = 7;
System.out.println("Instance Block");
System.out.println(staticVariable);
System.out.println(instanceVariable);
staticVariable = 10;
}
public StaticInitializationBlock() {
System.out.println("Constructor");
}
public static void main(String[] args) {
new StaticInitializationBlock();
new StaticInitializationBlock();
}
}
Output:
Static block
Instance Block
5
7
Constructor
Instance Block
10
7
Constructor

Just to add to the excellent answers from #aioobe and #Biman Tripathy.
A static initializer is the equivalent of a constructor in the static context. which is needed to setup the static environment.
A instance initializer is best for anonymous inner classes.
It is also possible to have multiple initializer blocks in class
When we have multiple initializer blocks they are executed (actually copied to constructors by JVM) in the order they appear
Order of initializer blocks matters, but order of initializer blocks mixed with Constructors doesn't
Abstract classes can also have both static and instance initializer blocks.
Code Demo -
abstract class Aircraft {
protected Integer seatCapacity;
{ // Initial block 1, Before Constructor
System.out.println("Executing: Initial Block 1");
}
Aircraft() {
System.out.println("Executing: Aircraft constructor");
}
{ // Initial block 2, After Constructor
System.out.println("Executing: Initial Block 2");
}
}
class SupersonicAircraft extends Aircraft {
{ // Initial block 3, Internalizing a instance variable
seatCapacity = 300;
System.out.println("Executing: Initial Block 3");
}
{ // Initial block 4
System.out.println("Executing: Initial Block 4");
}
SupersonicAircraft() {
System.out.println("Executing: SupersonicAircraft constructor");
}
}
An instance creation of SupersonicAircraft will produce logs in below order
Executing: Initial Block 1
Executing: Initial Block 2
Executing: Aircraft constructor
Executing: Initial Block 3
Executing: Initial Block 4
Executing: SupersonicAircraft constructor
Seat Capacity - 300

Related

Please explain the execution sequence of my program [duplicate]

This question already has answers here:
Java order of Initialization and Instantiation
(2 answers)
java "void" and "non void" constructor
(5 answers)
Closed 3 years ago.
I'm trying to understand the call sequence for my code. Someone, please explain the call sequence.
public class MainWithStaticCalls
{
static
{
String[] str = {"1", "2"};
System.out.println("Static");
main(str);
}
{
System.out.println("Init block");
}
void MainWithStaticCalls()
{
System.out.println("constructor");
}
public static void main(String[] a)
{
MainWithStaticCalls obj = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
class NewClass
{
public void callMe()
{
System.out.println("I'm called");
}
}
As per my understanding, the static block will get executed as soon as the JVM starts its execution, even before main class. and instance init block gets executed after that. then constructor should get executed. But how the call back works if we call the main method from the static field. and which main will gets executed first, the one which JVM executes normally or the one which static field has called explicitly.
My output:
Static
Init block
I'm called
Main
Init block
I'm called
Main
P.S: I have modified my question. Earlier I confused the normal method with a Constructor so a few answers may look irrelevant, but that indeed helped me in understanding the problem.
I'll try to explain the calling sequence with an example, but first of all let's consider that if you add the void access qualifier, this will be a method and not a constructor.
Secondly remember that a class can have two type of initialization block:
Static Initialization Block
Instance Initialization Block
The Static Initialization Block will be called first of all and before the constructor, since is at class level and will be execute even before any class instance (i.e. object of that class type) is created. The second, i.e. the Instance Initialization Block is executed as soon as a new instance of the class is created. After that two blocks, it will be called the constructor. You can see it with the following example:
public class MainWithStaticCalls {
{
System.out.println("Init block called");
}
static {
String[] str = {"1", "2"};
System.out.println("Static called");
}
public MainWithStaticCalls() {
System.out.println("this is constructor");
}
void MainWithStaticCalls() {
System.out.println("this is NOT constructor");
}
public static void nope() {
System.out.println("Nope");
}
public static void main(String[] a) {
MainWithStaticCalls.nope();
System.out.println("************");
MainWithStaticCalls obj = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
The output is:
Static called
************
Init block called
this is constructor
NewClass: I'm called
Main
If I comment out the "nope" static call:
public class MainWithStaticCalls {
... // Same thing as above
public static void main(String[] a) {
// MainWithStaticCalls.nope();
System.out.println("************");
MainWithStaticCalls obj = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
The result is:
Static called
************
Init block called
this is constructor
NewClass: I'm called
Main
So it is the same result if do not comment out the "nope" call. This is to show that the static method is called only once, when the class is firstly faced by the JVM. If we instantiate another object:
public class MainWithStaticCalls {
... // Same thing as above
public static void main(String[] a) {
// MainWithStaticCalls.nope();
System.out.println("************");
MainWithStaticCalls obj1 = new MainWithStaticCalls();
MainWithStaticCalls obj2 = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
The output is:
Static called
************
Init block called
this is constructor
Init block called
this is constructor
NewClass: I'm called
Main
you see that the Instance Initialization Block is called every time a new object fof that class type is created (as well as the constructor), while the Static Initialization Block is called only once.
There is no constructor defined in class, so default constructor gets called.
void MainWithStaticCalls()
is not a constructor. This is method, as constructor don't have return type.
void MainWithStaticCalls() is a method not a constructor.
Change it to,
public MainWithStaticCalls()
{
System.out.println("constructor");
}
There are rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor, not even if it declares that returns a void.
As others have already mentioned you confused constructor with method. Remove 'void' to make it a constructor again. Just for reference - this is how constructor described in the oracle docs: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Why do print statements execute in this order when using initializers, constructors and method calls?

This is the code I'm running , the output of this code is 4 2 1 3 , could someone please explain why the result was printed in this order.
public class goFuncTest {
goFuncTest()
{
System.out.print("1 ");
}
{
System.out.print("2 ");
}
public static void main(String[] args)
{
new goFuncTest().go();
}
void go()
{
System.out.print("3 ");
}
static
{
System.out.print("4 ");
}
}
Based on your recent question edit, your output will be 4 2 1 3. The static initializers are run first, then the instance initializers. If you had multiple initializers of the same type, they would execute in the order they appear in the class.
// static initializer first
static {
System.out.print("4 ");
}
// then instance initializer
{
System.out.print("2 ");
}
Next the constructor fires up, which gives you:
goFuncTest()
{
System.out.print("1 ");
}
finally the method is invoked:
void go()
{
System.out.print("3 ");
}
As JB Nizet pointed out in first comment, result should be 2,4,3,1.
And coming to the order, static blocks executes first and then initialization blocks. In your code there are no static blocks and only inti blocks.
The order of initialization block execution is the order they placed in source code -2,4.
And remaining two results as per constructor and method call. 1,3
Now you can see the answer right ?
Reason:
You have instance block which gets executed in sequence in which appear in your class definition. So 2 comes first and then 4 and hence output 2 4
Next you are calling new goFuncTest(), which is going to call your constructor and hence you will see 1 in the output.
Now on your instance you are calling go method which prints 3.
It seems the main confusion is just due to not understanding the various blocks that a class can have;
this answer gives a nice example and explanation;
Here's the code they give:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized).
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs before the constructor each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
This class has a static initialiser, an instance initialisation block, a constructor, and a class method.
static initialiser: static {...}
instance initialiser: {...}
constructor: Public ClassName(){...}
class method: Public Static Whatever classMethod(String[] args){...}
Each of these is called under different circumstances; the static initialiser is called when the class is loaded, there's no other way to call it, you can't even do it via reflection, as it's never represented by a method instance, it is called by the JVM.
the instance initialiser is called whenever you create an instance of the class - before the constructor.
You can have multiple static initialisers, and multiple instance initialisers, and they are executed in the order they appear in the code.
constructor and class method you presumably already know about.
In your example, it would probably be a little more helpful to rearrange the code slightly, to better reflect that hierarchy;
public class goFuncTest {
//static instance initialiser
static {
System.out.print("4 ");
}
//instance initialiser
{
System.out.print("2 ");
}
//Constructor
goFuncTest(){
System.out.print("1 ");
}
//Class method
void go(){
System.out.print("3 ");
}
public static void main(String[] args){
new goFuncTest().go();
}
}
(editted to add in the static keyword)

Difference between static block and assigning static in class?

Is there any difference between following two initializations of static variables:
class Class1 {
private static Var var;
static {
var = getSingletonVar();
}
}
class Class2 {
private static var = getSingletonVar;
}
Are these two different ways of initializing a static variable functionally the same?
Yes, its functionally the same.
From Java doc
There is an alternative to static blocks — you can write a private static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
// initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
The result will be same.
In both the cases static variable will get initialized with class loading.
static methods and static class blocks are two different things.
static methods need to be called where as static class block automatically gets executed with class loading.
First Thing you haven't declared static methods here.
probably if you want know order of execution
1) constructors
Invoked when you create an instance, totally independent of when #2 happens, or even if it ever happens at all
2)static methods
Invoked when you invoke them, totally independent of when #1 happens, or even if it ever happens at all
3)static blocks
Invoked when the class is initialized, which happens before #1 or #2 can happen.
Static initializers and static blocks both run when the class is initialized. Static blocks exist because sometimes you want to do something at initialization time that can't be characterized as a simple assignment:
static final Logger log = Logger.getLogger(ThisClass.class);
static final String PROPS_FILE = "/some/file.properties";
static final Properties gProps;
static {
gProps = new Properties();
try {
FileReader reader = new FileReader(PROPS_FILE);
try {
gProps.load(reader);
} finally {
reader.close();
}
} catch (IOException e) {
throw new SomeException("Failed to load properties from " + PROPS_FILE, e);
}
log.info(ThisClass.class.getName() + " Loaded");
}

Variable visibility in Java

In the following code, why can't I see the variable "i" from another thread?
public class Main {
public static void main(String[] args) {
int i = 0;
new Thread(new Runnable() {
#Override
public void run() {
System.out.println(i);
}
}).start();
}
}
And why can I see it in the code below?
public class Main {
int i = 0;
public static void main(String[] args) {
new Main().method();
}
private void method() {
new Thread(new Runnable() {
#Override
public void run() {
i = 1;
}
}).start();
}
}
From docs:
As with instance methods and variables, an inner class is associated
with an instance of its enclosing class and has direct access to that
object's methods and fields.
Now taking the second example first, when i is declared in parent class, the inner class can access it, because inner class has access to entire parent object. And i is correctly referenced as Main.this.i from inner class.Now compiler secretly makes a copy of this.i inside inner class. this never changes inside the object, this.i will point to correct object for both inner and outer class. Compiler is happy.
In first example, i is not part of parent class, its declared inside a method hence its reference is now on stack, and not on heap. (In this case, i doesn't get to live on that big outer circle shown in above diagram). Now compiler must secretly make a copy of i inside inner class as well. But it is afraid that method's i may change on stack. Compiler can't use outer class connection to get to i here, and it can't bother to copy i reference from stack every time it changes. So, it is decided that you must make the method's i reference unchangeable, or in other words, final.
The obscure secret tricks Java plays so that you can access outer fields from inner classes is explained in detail here: http://techtracer.com/2008/04/14/mystery-of-accessibility-in-local-inner-classes/
and discussed more "why's" here : http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg04044.html
tl;dr: Instance fields are directly accessible by inner classes, local fields must be made final to be accessible by a inner class.
Java only allows you to access the values of local variables that are declared final in anonymous classes. No writing is allowed. The rationale for this is because the function scope might be (and indeed in this case is) exited while the variable is accessible from within the inner class, the value is actually cached within the anonymous class instances. To avoid confusion and make JIT work, these variables are allowed to be final only. Notice that only the primitive value, or the reference cannot be modified, but anything contained within a referenced object can still be modified.
In the second case it is an instance variable accessible to the thread. Note that i = 1 stands now for Main.this.i; the Main.this. part being implicit.
In the first program you can "see" variable i, but not access it, because it is not declared final. Only member variables and final local variables declared before creating an instance of your anonymous class can be accessed:
public class Main {
public static void main(String[] args) {
final int i = 123; // Make the variable final
new Thread(new Runnable() {
#Override
public void run() {
System.out.println(i); // Now it works, but you cannot assign it
}
}).start();
}
}
Demo on ideone.
Making your variable static would work as well:
public class Main {
private static int i = 321;
public static void main (String[] args) throws java.lang.Exception
{
new Thread(new Runnable() {
#Override
public void run() {
System.out.println(i); // Now it works, but you cannot assign it
}
}).start();
}
}
Demo.

What does this 'static' mean and why is it like that

public class tt {
static{
System.out.println("class tt");
}
}
It the first time ive come across it and im wondering what it is and what it's used for
It is the static initialiser of the class. When the class is loaded, the static initialiser is run. It is like the constructor, but for the class rather than for individual objects.
Multiple static initialisers can appear in a class, as well as direct initialisers for static variables. These will be combined into one initialiser in the order in which they are declared. For example, the following will print "foo" to stdout whenever the class is loaded (usually once per application).
public class Foo {
static String a;
static {
a = "foo";
}
static String b = a;
static {
System.println(b);
}
}
Its initilizer block
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
There is an alternative to static blocks —you can write a private static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
//initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
Resource
here is the static initializer tutorial http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
It runs when the class is loaded before the initialization.
public class A {
static {
System.out.println("A from static initializer"); // first
}
public A(){
System.out.println("A"); // second
}
public static void main(String[] args){
new A();
}
}
It is a static initializer. The code inside that block runs when the JVM loads the class, which is immediately before the first time the program needs to do anything with that class (e.g. look up a static field, call a static method, instantiate an object,...).
It's a static initializer block. It will be executed once when the class is first loaded, along with static field initializers like this:
private static int staticField = someMethod();
The difference is that an initializer block can contain control flow structures like try/catch blocks.

Categories