what does static { // some code } mean? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static Initialization Blocks
What does the following mean in java?
static {
WritableComparator.define(IntPair.class, new Comparator());
}

That means static initialization block which will be executed on class load.
If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

It means that the code within that block will run once, when the type is loaded, before any constructors are called, but after any field initialisers are run.
Note that you cannot set any instance fields in the static block. There is no concept of this in there, just as in any other static methods.

Related

Does Java have an equivalent keyword to static in C? [duplicate]

This question already has answers here:
How do I create a static local variable in Java?
(8 answers)
Closed 6 years ago.
I know that in C, when the keyword static is used on a local variable, it causes that variable to remain initialized between function calls (i.e. when the variable goes out of scope). For example:
int myFunction() {
static int i = 3;
i++;
return i;
}
If myFunction() is called twice, it will return 4 the first time and 5 the second time (because i keeps its value between the two calls rather than being reinitialized the second time).
My question is this: does Java have an equivalent keyword to static in C? Java also has the keyword static, but it is used completely differently than in C.
Not exactly, but a private static class level variable will almost do the same thing.
But
it will be visible to all other methods of the class as well
it will be initialized not on first method call, but when the class itself is loaded
I suppose that is workable.
All variables in a method are local to the function and placed on the stack. The closest you have is a static variable in a class.
If you make the variable private and place the method in a class of it's own you will achieve much the same result.
(With a private constructor)
It's somewhat similar to the private keyword, as in C a static global variable or a function is visible only in the file it's declared in...
So that's probably the closest you will find :)
No, because all methods and functions are bound to classes in Java, so there is no "global space" as there is in C. The static keyword in Java has different semantics.
See the docs for static and this post for more detail on the differences.
Java uses static in a different manner. To get the same result you want here, you should use a private field instead.

Why is the code within empty braces getting executed first even before the constructor of the class? [duplicate]

This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Static block vs. initializer block in Java? [duplicate]
(2 answers)
How is an instance initializer different from a constructor?
(7 answers)
Closed 6 years ago.
Though this is a small question to ask, wanted to understand this strange behavior! Following is the code and the behavior of the code that's in discussion (through the console output).
public class EmptyBracesWithinClass {
public static void main(String[] args) {
EmptyBraces eb = new EmptyBraces();
System.out.println("SYSO within main() method");
}
}
class EmptyBraces {
{
System.out.println("SYSO within empty braces");
}
public EmptyBraces() {
System.out.println("SYSO within constructor() method");
}
}
Console output:
SYSO within empty braces
SYSO within constructor() method
SYSO within main() method
The question here is, why would the piece of code within the empty braces get executed first during the object instance creation of EmptyBraces class (though it is never declared as STATIC explicitly)?
the piece of code within the empty braces is called instance initializer block. It gets executed before the constructor body (and after the super class constructor is executed) whenever an instance of the class is created.
This is because before print method excecuted of EmptyBracesWithinClass, you're calling EmptyBraces by instantiate it. so static initializer block run at first and then constructor will run.

What is the purpose of the {} outside of any methods? [duplicate]

This question already has answers here:
Why is this Java code in curly braces ({}) outside of a method?
(3 answers)
Java empty block scope
(3 answers)
Closed 9 years ago.
I accidently made a pair of {} outside of all method and worked.
public static void main(String[] args) {
System.out.println("ddd");
}
{
System.out.println("ttt");
}
Of course if you run this code the result is "ddd" and it writes "ttt" only if I create a new instance of it.
And if I make it static {System.out.println("ttt");} it works as designed and the result is "ttt" then "ddd"
Is there any practical use of this? Why would anyone use it with contructor or without a written constructor?
My impressions are: it seems working, but smells like bad and strange practice. Am I right?
{} define the scope of a module or block of code (like a method, static block, class, etc.)
And every module should have a name of something to identify it from other modules.
In your case, simply putting {} means you are creating a block of code but not naming, hence it gives error. But putting {} inside a method will work fine.
But when you put static keyword before it, you are making a static block that has got special meaning in java. it means that everything inside static block will be executed when your class gets loaded first time.
See this link for initializer blocks from Java Tutorials website
Is there any practical use of this?
There is one "idiom" that makes use of instance initializer blocks:
Map mymap = new HashMap() {{put("a", 1); put("b", 2);}};
This is a concise way to create a map that is initialized with a given set of entries. And when you break it down, it is declaring and instantiating an anonymous subclass of HashMap which uses an instance initializer block to populate the new map.
My impressions are: it seems working, but smells like bad and strange practice.
That's a subjective statement. The only rational argument I can think of for initializer blocks being bad / strange is that people don't use them. And that argument smells of circular logic.
Its all about Initializer blocks
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// will execute when intialization
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
These are called initializer blocks. They are called along with all constructor. So any constructor call will invoke this code.
A static block is called only when class is loaded.
Normally, you have to put the code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
Source: here
It may be unfamiliar, but it is not bad per se. It's an initializer block that is executed on construction. See here for a more detailed explanation that includes static initialization blocks also.

How does a method signature of only "static" work? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static initializer in Java
I have a few years' experience with Java, but I've recently run across something I've never seen before:
public class Project{
...
static{
initDataTypeMapping();
}
...
}
How does this method signature work? Is this in fact even technically a method? I'm wondering why one wouldn't simply put the the method call to initDataTypeMapping() in the constructor. Just trying to increase my understanding so I don't mess something up. Thanks!
This is known as a static initializer.
The code in the static { } block is run when the class is first loaded by the classloader (which is usually, but not always, when code that refers to the class is first loaded/executed), and is guaranteed to be run in a thread-safe manner.
See this question also.

Static Block in Java [duplicate]

This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 8 years ago.
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
It can be thought of as a "class constructor".
Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
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.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
A static block executes once in the life cycle of any program,
another property of static block is that it executes before the main method.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.
http://www.jusfortechies.com/java/core-java/static-blocks.php
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.

Categories