Is it possible to create object in a static block? - java

I am little bit confused about static block.if we talk about system.out.println method here system is a class,out is the reference variable that have the reference ID of printstream class that declares in a static block then how it is possible to create any object in a static block because a static block always executes at class loading time, while object is created at run time...
how i can make the difference b/w loading time and running time..

Static block
The static block is a static initializer (a class initializer). You can use it to initialize a class or to do some logic during class load. If you remove the static modifier the code block is an instance initializer.
For instance, with static initializers you can initialize a map with db data to be used later during object instantiation.
You can read this link that explains very well about it.
I find useful this quotation:
Static blocks are also called Static initialization blocks. 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. And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes.
For example, this code:
public class StaticExample{
static {
System.out.println("This is first static block");
}
public StaticExample(){
System.out.println("This is constructor");
}
public static String staticString = "Static Variable";
static {
System.out.println("This is second static block and "
+ staticString);
}
public static void main(String[] args){
StaticExample statEx = new StaticExample();
StaticExample.staticMethod2();
}
static {
staticMethod();
System.out.println("This is third static block");
}
public static void staticMethod() {
System.out.println("This is static method");
}
public static void staticMethod2() {
System.out.println("This is static method2");
}
}
Generates this output:
This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2
Static method (alternative to static block)
You can write a private static method to achieve the same, and an advantage of using private static methods is that they can be reused later if you need to reinitialize the class variable.
For instance:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
// initialization code goes here
}
}

Related

Why does printing a static variable value gives error in static block while assigning it doesn't

public class ABC {
static {
System.out.println(i);
}
static int i=10;
static {
System.out.println(i);
}
public static void main(String[] args)
{
System.out.println(3);
ABC a = new ABC();
}
}
gives error;
can not reference a field before it is defined
But following -
public class ABC {
static {
i=20;
System.out.println(ABC.i);
System.out.println(i); //same error as above
}
static int i=10;
static {
System.out.println(i);
}
public static void main(String[] args)
{
System.out.println(3);
ABC a = new ABC();
}
}
doesn't throw any error and compiles and runs fine. Even if I use,
package com.sample.package2;
public class ABC {
static {
System.out.println(ABC.i);
}
static int i=10;
static {
System.out.println("yahan 10" + i);
}
public static void main(String[] args)
{
System.out.println(3);
ABC a = new ABC();
}
}
runs fine. Confused as why this error is coming up. There are similar questions asked and it might sound duplicate to some of you but haven't found a clear answer on it yet. What is the order of initialization. I believed static block executes first before anything else. If I shift the static int i=10; error goes away. Does static variable initialize before static blocks?
What you have used is called as " static initialization block ". If you have read the documentation of initializing fields, you will encounter the following (emphasis on mine)
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.
In your code, you have declared and initialized i after trying to call it. If you have done that before the static initialization, the variable i is then not defined.
static {
System.out.println(i); // <-- where is i ?
}
static int i=10;
The use of ABC.i before defining the i in the class works because when you are calling ABC, the class ABC is being initialized. You have to look at when an initialization occurs. If you check JLS 12.4.1, you will notice
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
...omitted...
A static field declared by T is used and the field is not a constant variable
...omitted...
which means that ABC is being initialized. However, during the initialization, the static { ... } methods are not called anymore because it's used one time. Here, the error isn't thrown. Hence it is possible to retrieve the assigned value when calling ABC.i in the static { ... } method, even if i is defined after that method.
static {
System.out.println(i);
}
static int i=10;
You are intializing the variable later but calling it before.So it throws an error
wheras
static {
i=20;
System.out.println(i);
}
and
static {
System.out.println(ABC.i);
}
static int i=10;
i is initialized first then it is called.

system.out.println statement outside any method in java

My question is can't we write an output statement outside the main in java? If I enclose it in { } braces then I don't get error, but if I directly write it, I get an error. why so?
public class abc
{
int a=3;
int b=0;
System.out.println("this statement gives error"); //Error!!
{System.out.println("this works fine");}
public static void main(String args[]) {
System.out.println("main");
abc t=new abc();
}
}
I tried writing it in main, it works. Why doesn't it work without a method?
When you enclose it in braces, you are putting it in an initializer block, which runs when the class is instantiated. No statements except variables declarations/initialization may take place outside of methods or initialization blocks in Java.
A Class can only have attributes or methods.
A class is the blueprint from which individual objects are created.
int a=3; // attributes
int b=0; // attributes
System.out.println("this statement gives error"); //Error!!
{System.out.println("this works fine");} // init block whenever an object is created.
// since it is inside { }
{...} is called an instance initializer . It runs in addition to the constructor each time an instance object is created .
static{...} is another type of block that is called Static Initializer it is when you add a static keyword before { } . This static initializer only runs when the class is first loaded.
So you can write code in these two block and class member functions.
Other than that the only place left is meant for the class data members declaration and initialization.
Basics/Fundamentals
Java Class contains only member functions and class variables and few other exceptions like instance initliazer, static blocks etc.
You can't just sprinkle executables(like System.out.println()) anywhere you wish inside Class.
Instance initliazer
{...} in Java is instance initializer which gets called whenever an object is created. Because it is instance initializer, it actually gets called before constructor.
You can write System.out.println() inside {...} or instance initializer.
Static block
static{...} is called static block in Java, which contains lines of code which gets called ONLY ONCE when the class is loaded by JVM.
Again, You can write System.out.println() inside {...} or static block.
Simple executable example below
public class JavaExample {
public JavaExample (String name){
System.out.println("Inside constructor" + name);
}
{
System.out.println("Inside instance initializer");
}
static{
System.out.println("Inside static block");
}
//System.out.println("Will give error"); //ERROR
public static void main(String[] args) {
JavaExample obj1 = new JavaExample ("obj1");
JavaExample obj2 = new JavaExample ("obj2");
System.out.println("Inside the public static void main");
}
}
Output
> Inside static block
> Inside instance initializer
> Inside constructor: obj1
> Inside instance initializer
> Inside constructor: obj2
> Inside the public static void main
Please note the order of execution.
Static block (gets called once when JVM loads Class, hence first of all)
Instance initializer (before the call of any object instantiation)
Constructor (during object creation/initialization)

Regarding static and final variable effect on class

If you execute this program you will get only the i value but not SIB, my question is when class loading into the memory SIB should execute and should give ooutput, but here I am getting only the i value? Then keep one method in class test then call that method from another class then you will get output of SIB, i method ( keep method also as static final)
class Test
{
static final int i =3;
static
{
System.out.println("SIB");
}
{
System.out.println("IIB");
}
}
class A1
{
public static void main(String[] args)
{
System.out.println(Test.i);
}
}
A static final variable is a compile-time constant and its value is copied into the other class referencing it. Therefore your class Test won't load and no initializers will be executed. When the variable is only static, then the class must be loaded to read the current value and your SIB block will be executed. The IIB block will be executed only when you instantiate Test with new Test().

Java syntax question

What does
static{
//something
}
declared inside a class definition body mean?
public class A extends B{
static {
C.register(new C(A.class,
(byte) D.x.getCode()) {
public DataSerializable newInstance() {
return new A();
}
}
);
}
}
The static block is called a "static initialization block." It is very similar to a regular constructor except that it can only initialize static variables.
I have found it to be useful when initialization of some static variable may throw an exception that you would like to handle or at least log. It is especially useful in the initialization of static final variables.
You may read more about static initialization blocks here: Initializing Fields
It executes a block of code without requiring an instance of this class, i.e. as soon as the class loader loads the class.
That becomes a static initialisation block, which can be written as a static method.
It's a static initializer. It's run once the class is loaded and it's results can be stored in static members. It's used to initialize static members that require more than the regular new Xyz() (like Lists or Maps)...
It's a static initializer. It lets you specify things that happen at the time that the class is loaded, before any instance is created.
If an exception is thrown from a static initializer it's very confusing, it's hard to tell where it came from. Anything that you do in a static initializer should have a try-catch around it and have the exception get logged. It's a good language feature to avoid if you can.
It means that you will have this section which is inside the static block extecuted FIRST on load of the class into the JVM.
Execute the following simple program might make things clearer
public class Test123 {
static{
System.out.println("Hello from static block");
}
public static void main(String[] args) {
System.out.println("In main");
}
}
The output to the above will be
Hello from static block
In main

Static Initialization Blocks

As far as I understood the "static initialization block" is used to set values of static field if it cannot be done in one line.
But I do not understand why we need a special block for that. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.
Why do we need this lines in a special block like: static {...}?
The non-static block:
{
// Do Something...
}
Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.
Example:
public class Test {
static{
System.out.println("Static");
}
{
System.out.println("Non-static block");
}
public static void main(String[] args) {
Test t = new Test();
Test t2 = new Test();
}
}
This prints:
Static
Non-static block
Non-static block
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first and second weren't in a block, they'd look like fields. If they were in a block without static in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
Here's an example:
private static final HashMap<String, String> MAP = new HashMap<String, String>();
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere). That way you can make sure that the class resources are all ready to use.
It's also possible to have non-static initializer blocks. Those act like extensions to the set of constructor methods defined for the class. They look just like static initializer blocks, except the keyword "static" is left off.
It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.
E.g.
static {
try {
Class.forName("com.example.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
}
}
Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:
private static Object stuff = getStuff(); // Won't compile: unhandled exception.
then a static initializer is useful here. You can handle the exception there.
Another example is to do stuff afterwards which can't be done during assigning:
private static Properties config = new Properties();
static {
try {
config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
} catch (IOException e) {
throw new ExceptionInInitializerError("Cannot load properties file.", e);
}
}
To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.
I would say static block is just syntactic sugar. There is nothing you could do with static block and not with anything else.
To re-use some examples posted here.
This piece of code could be re-written without using static initialiser.
Method #1: With static
private static final HashMap<String, String> MAP;
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
Method #2: Without static
private static final HashMap<String, String> MAP = getMap();
private static HashMap<String, String> getMap()
{
HashMap<String, String> ret = new HashMap<>();
ret.put("banana", "honey");
ret.put("peanut butter", "jelly");
ret.put("rice", "beans");
return ret;
}
There are a few actual reasons that it is required to exist:
initializing static final members whose initialization might throw an exception
initializing static final members with calculated values
People tend to use static {} blocks as a convenient way to initialize things that the class depends on within the runtime as well - such as ensuring that particular class is loaded (e.g., JDBC drivers). That can be done in other ways; however, the two things that I mention above can only be done with a construct like the static {} block.
You can execute bits of code once for a class before an object is constructed in the static blocks.
E.g.
class A {
static int var1 = 6;
static int var2 = 9;
static int var3;
static long var4;
static Date date1;
static Date date2;
static {
date1 = new Date();
for(int cnt = 0; cnt < var2; cnt++){
var3 += var1;
}
System.out.println("End first static init: " + new Date());
}
}
It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):
public enum Language {
ENGLISH("eng", "en", "en_GB", "en_US"),
GERMAN("de", "ge"),
CROATIAN("hr", "cro"),
RUSSIAN("ru"),
BELGIAN("be",";-)");
static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>();
static {
for (Language l:Language.values()) {
// ignoring the case by normalizing to uppercase
ALIAS_MAP.put(l.name().toUpperCase(),l);
for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l);
}
}
static public boolean has(String value) {
// ignoring the case by normalizing to uppercase
return ALIAS_MAP.containsKey(value.toUpper());
}
static public Language fromString(String value) {
if (value == null) throw new NullPointerException("alias null");
Language l = ALIAS_MAP.get(value);
if (l == null) throw new IllegalArgumentException("Not an alias: "+value);
return l;
}
private List<String> aliases;
private Language(String... aliases) {
this.aliases = Arrays.asList(aliases);
}
}
Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.
As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:
The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
static block and initialization of static fields in the order of occurrence.
This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):
public class Foo {
static { System.out.println("Static Block 1"); }
public static final Foo FOO = new Foo();
static { System.out.println("Static Block 2"); }
public Foo() { System.out.println("Constructor"); }
static public void main(String p[]) {
System.out.println("In Main");
new Foo();
}
}
What we see is the following output:
Static Block 1
Constructor
Static Block 2
In Main
Constructor
Clear is that the static initialization actually can happen before the constructor, and even after:
Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.
For more info on this see the book "Effective Java".
So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:
1- Just initialize it when you declare the variable:
static int x = 3;
2- Have a static initializing block:
static int x;
static {
x=3;
}
3- Have a class method (static method) that accesses the class variable and initializes it:
this is the alternative to the above static block; you can write a private static method:
public static int x=initializeX();
private static int initializeX(){
return 3;
}
Now why would you use static initializing block instead of static methods?
It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.
let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.
Note: the static blocks are called in the order they appear in the code.
Example 1:
class A{
public static int a =f();
// this is a static method
private static int f(){
return 3;
}
// this is a static block
static {
a=5;
}
public static void main(String args[]) {
// As I mentioned, you do not need to create an instance of the class to use the class variable
System.out.print(A.a); // this will print 5
}
}
Example 2:
class A{
static {
a=5;
}
public static int a =f();
private static int f(){
return 3;
}
public static void main(String args[]) {
System.out.print(A.a); // this will print 3
}
}
If your static variables need to be set at runtime then a static {...} block is very helpful.
For example, if you need to set the static member to a value which is stored in a config file or database.
Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.
It is important to understand that classes are instantiated from java.class.Class during runtime. That is when static blocks are executed, which allows you to execute code without instantiating a class:
public class Main {
private static int myInt;
static {
myInt = 1;
System.out.println("myInt is 1");
}
// needed only to run this class
public static void main(String[] args) {
}
}
The result is myInt is 1 printed to the console.
As supplementary, like #Pointy said
The code in the "static" section(s) will be executed at class load
time, before any instances of the class are constructed (and before
any static methods are called from elsewhere).
It's supposed to add System.loadLibrary("I_am_native_library") into static block.
static{
System.loadLibrary("I_am_a_library");
}
It will guarantee no native method be called before the related library is loaded into memory.
According to loadLibrary from oracle:
If this method is called more than once with the same library name,
the second and subsequent calls are ignored.
So quite unexpectedly, putting System.loadLibrary is not used to avoid library be loaded multi-times.
static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member
Eg:-class Solution{
// static int x=10;
static int x;
static{
try{
x=System.out.println();
}
catch(Exception e){}
}
}
class Solution1{
public static void main(String a[]){
System.out.println(Solution.x);
}
}
Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..
}
static int B,H;
static boolean flag = true;
static{
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
scan.nextLine();
H = scan.nextInt();
if(B < 0 || H < 0){
flag = false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
}
}

Categories

Resources