okay. I wrote the above code and I need to call it from another class. how can I do it?
plus it gives me this error with DefaultTableModel prodt = (DefaultTableModel) protable.getModel(); . the error is non-static variable protable cannot be referenced from a static context.
public static void refreshProtable() {
try {
Statement s1 = Db.connectDb().createStatement();
ResultSet rs1 = s1.executeQuery("SELECT * FROM product WHERE status='" + 0 + "'");
DefaultTableModel prodt = (DefaultTableModel) protable.getModel();
while (rs1.next()) {
Vector v1 = new Vector();
v1.add(rs1.getString("pid"));
v1.add(rs1.getString("pname"));
v1.add(rs1.getString("sp_rt"));
v1.add(rs1.getString("sp_wh"));
v1.add(rs1.getString("um"));
Statement s2 = Db.connectDb().createStatement();
ResultSet rs2 = s2.executeQuery("SELECT * FROM stock WHERE pid='" + rs1.getString("pid") + "'");
if (rs2.next()) {
v1.add(rs2.getString("qty"));
}
prodt.addRow(v1);
s2.close();
}
s1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Either mark your variable protable static or make the method non-static.
private static DefaultTableModel protable;
public static void refreshProtable() { ... }
Since the method is static, you call it using the class name that it is within.
E.g
class A {
public static void b() {
// do something
}
}
Would be called as follows:
A.b();
It might be handy to refresh yourself on how static variables work, here would be a starting point: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
You can make your function as non-static or make protable object static.
In a word, you can not reference non-static variable in static function.
but you can reference static variable in non-static function
you need to make protable as static as you can access only static variables from a static method.
private static DefaultTableModel protable;
public static void refreshProtable() { }
the variable you are trying to call is an instance-level variable;
static variable
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object
Syntax : .
static method
It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data (instance variables)
static method can call only other static methods and can not call a non-static method from it.
A static method can be accessed directly by the class name and doesn’t need any object
Syntax : .
A static method cannot refer to “this” or “super” keywords in anyway
Related
I have main method in my java program, I want to store values in global variable because i want to access that values from different methods of the class, however I am not convinced to use static global variable, as the values in the variable keep on changing, so am afraid values which are declared as static may not change as it is defined on the class level, so I am looking for non static global variable. Can someone give an idea, how to achieve this.
I suggest you make a separate class with with variables you want to store, with proper getter and setter methods. That way you keep the code more clean and maintainable and you follow the Separation of concerns principle, which tells us that every class should have it's own purpose.
EG:
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName()); //Prints out name value
}
}
Since Java promotes the use of classes rather than global variables, I would highly recommend you to use a class for storing the data. That way, you do not need to use static methods or static variables.
One example of this is shown below:
import java.util.*;
public class Main{
public static void main(String[] args) {
int initialValue = 1;
Holder holder = new Holder(initialValue);
int currentValue = holder.getValue();
System.out.println("Value after initial creation: " + currentValue);
System.out.println("Set value to 10");
holder.setValue(10);
currentValue = holder.getValue();
System.out.println("New value is " + currentValue);
}
}
Holder class:
public class Holder {
private int val;
public Holder(int value){
setValue(value);
}
public void setValue(int value){
this.val=value;
}
public int getValue(){
return this.val;
}
}
To start a java class uses the "main" static method present in all normal java programs.
HOWEVER, the "constructor" method (really just "constructor") is named after the "main class" name and is where you initialise variables whether you call a declared method in the class or retrieve a static variable from the starter method "main".
The main method does not require any passer method to obtain a static variable from it to either set a global static variable in the class because it is only 1 step in hierarchy "scope" in the class (this is why some frameworks pass variables to global without typing of the method but rather instead using "void" on the method declaration) BUT you cannot put a non static method call in a static section of code such as the main method.
The way you remove static context from a variable is to make another variable with the same name in a non static context and cast the static variable to the non static instance.
e.g. for a global String primitive type variable from main method at construction time globally declare
static String uselessRef1 = ""; // declared globally initialised
// following is declared inside the static method main
uselessRef1 = args[1]; // static argument 1 from the main method args[] array
// following is declared in global scope code or in the constructor code
String uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type
While committed inline in the global declarations not in the constructor they are deemed to be loaded in the class constructor in sequence.
NB: You can put or make a static method in a non-static class but not the make a non static method in a static class.
import.javax.swing.*;
public class ExampleStaticRemoval{
static String uselessRef1 = ""; // declared globally initialised
String uselessRef1b = "";
ExampleStaticRemoval(){
// following is declared in global scope code or in the constructor code
uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type
printOut();
}// end constructor
// program start method
public static void Main(String[] args){
new ExampleStaticRemoval();
// static global class variable uselessRef1 is assigned the local method value
// MUST BE OUTSIDE AT TOP TO BE GLOBAL
uselessRef1 = args[0] +" "+args[1]; // join static arguments 0 and 1 from the main method args[] array
}// end main
public void printOut(){
JOptionPane.showConfirmDialog(null,uselessRef1b, uselessRef1b, 0);
}//end method
} // end class
public class InstanceBuilder {
private static final InstanceBuilder INSTANCE = new InstanceBuilder();
private static String name = null;
private InstanceBuilder() {
System.out.println("Setting cons()");
name = "Testing";
}
public static String getName() {
return name;
}
}
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("value is " + InstanceBuilder.getName());
}
}
Output:
Setting cons()
value is null
Why does it print value as null even though I have set the static variable in constructor and it is called as expected. If I try to print in constructor, it is printing Testing, but if I call from public static method, it is null. I know if I change it to INSTANCE.name, it works.
But I want to understand why it is not working if I directly access static variable since same copy should be shared.
What I am missing here?
Because the value of name is getting modified after the constructor invocation as per the declaration order.
Lets see what is happening:
1) When you call InstanceBuilder.getName(), InstanceBuilder class is getting loaded. As part of that process INSTANCE and name instance variables are getting initialized.
2) While initializing INSTANCE,
private static final InstanceBuilder INSTANCE = new InstanceBuilder();
constructor of InstanceBuilder class is getting invoked & Setting cons() statement is getting printed and name variable is initialized with Testing.
3) Next name is again getting re-initialized with null due to the below statement
private static String name = null;
so when the method call returns to Driver class, value of name is null and null is getting printed. So even though name is declared as static, static has no role in that context.
Note:
Check the below link on the order of which class members should be declared
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#1852
Here value is null because static initialization occurs as its declare in order,
So First your
`private static final InstanceBuilder INSTANCE = new InstanceBuilder();`
code execute and assign value to "testing", then your
`private static String name = null;`
code exceute and override value to null(as static variable have coppy per class only), so final value will be null.
So here this behavior is just beacuse of order of execution of static variable
This question already has answers here:
Are fields initialized before constructor code is run in Java?
(5 answers)
Closed 7 years ago.
I'm learning java and accidentally I came across following code where default constructor is executed after the method.
public class ChkCons {
int var = getVal();
ChkCons() {
System.out.println("I'm Default Constructor.");
}
public int getVal() {
System.out.println("I'm in Method.");
return 10;
}
public static void main(String[] args) {
ChkCons c = new ChkCons();
}
}
OUTPUT :
I'm in Method.
I'm Default Constructor.
Can anyone please explain me why this happened?
Thanks.
Instance variable initialization expressions such as int var = getVal(); are evaluated after the super class constructor is executed but prior to the execution of the current class constructor's body.
Therefore getVal() is called before the body of the ChkCons constructor is executed.
Constructor is called prior to method. The execution of method occurs after that which is a part of object creation in which instance variables are evaluated. This could be better understand from following code.
class SuperClass{
SuperClass(){
System.out.println("Super constructor");
}
}
public class ChkCons extends SuperClass{
int var = getVal();
ChkCons() {
System.out.println("I'm Default Constructor.");
}
public int getVal() {
System.out.println("I'm in Method.");
return 10;
}
public static void main(String[] args) {
ChkCons c = new ChkCons();
}
}
The above code has following output
Super constructor
I'm in Method.
I'm Default Constructor.
Here the compiler automatically adds super(); as the first statement in ChkCons() constructor, and hence it is called prior to the getVal() method.
We can refer the following oracle documentation on Initializing instance variables (Emphasis is mine):
Initializing Instance Members
Normally, you would put 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:
{
// 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.
A final method cannot be overridden in a subclass. This is discussed
in the lesson on interfaces and inheritance. Here is an example of
using a final method for initializing an instance variable:
class Whatever {
private varType myVar = initializeInstanceVariable();
protected final varType initializeInstanceVariable() {
// initialization code goes here
}
}
https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Whenever you create an instance of a class instance variables are initialized first followed by execution of the Constructor
Ref : Are fields initialized before constructor code is run in Java?
public class InitializerIndex {
public InitializerIndex() {
// TODO Auto-generated constructor stub
System.out.println("Default Constructor");
}
static {
System.out.println("Static Block one");
}
{
System.out.println("Init one");
}
void letsRoll() {
}
public static void main(String[] args) {
new InitializerIndex().letsRoll();
new InitializerIndex().letsRoll();
}
{
System.out.println("Init Two");
}
static {
System.out.println("Static Block two");
}
}
Will have following output:
Static Block one
Static Block two
Init one
Init Two
Default Constructor
Init one
Init Two
Default Constructor
First all the static content is loaded, then the instance content. Static content is loaded only once.
Even when two objects are created, the static block is called only when the first object is created.
Also, at the time of object creation or in constructors, if you want to use methods like this
int var = getVal();
You should use static methods.
It's because you are initializing the method into a field using int var = getVal();, so it will execute before constructor call.
Static block have the first priority, it executes during loading of class.
Does calling a static method on a class in Java trigger the static initalization blocks to get executed?
Empirically, I'd say no. I have something like this:
public class Country {
static {
init();
List<Country> countries = DataSource.read(...); // get from a DAO
addCountries(countries);
}
private static Map<String, Country> allCountries = null;
private static void init() {
allCountries = new HashMap<String, Country>();
}
private static void addCountries(List<Country> countries) {
for (Country country : countries) {
if ((country.getISO() != null) && (country.getISO().length() > 0)) {
allCountries.put(country.getISO(), country);
}
}
}
public static Country findByISO(String cc) {
return allCountries.get(cc);
}
}
In the code using the class, I do something like:
Country country = Country.findByISO("RO");
The problem is that I get a NullPointerException because the map (allCountries) is not initialized. If I set up breakpoints in the static block I can see the map getting populated correctly, but it's as if the static method has no knowledge of the initializer being executed.
Can anyone explain this behavior?
Update: I've added more detail to the code. It's still not 1:1 (there are several maps in there and more logic), but I've explicitly looked at the declarations/references of allCountries and they are as listed above.
You can see the full initialization code here.
Update #2: I tried to simplify the code as much as possible and wrote it down on the fly. The actual code had the static variable declaration after the initializer. That caused it to reset the reference, as Jon pointed out in the answer below.
I modified the code in my post to reflect this, so it's clearer for people who find the question. Sorry about the confusion everyone. I was just trying to make everyone's life easier :).
Thanks for your answers!
Does calling a static method on a class in Java trigger the static initalization blocks to get executed?
Empirically, I'd say no.
You're wrong.
From the JLS section 8.7:
A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.
Section 12.4.1 of the JLS states:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
This is easily shown:
class Foo {
static int x = 0;
static {
x = 10;
}
static int getX() {
return x;
}
}
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(Foo.getX()); // Prints 10
}
}
Your problem is in some part of the code that you didn't show us. My guess is that you're actually declaring a local variable, like this:
static {
Map<String, Country> allCountries = new HashMap<String, Country>();
// Add entries to the map
}
That hides the static variable, leaving the static variable null. If this is the case, just change it to an assignment instead of a declaration:
static {
allCountries = new HashMap<String, Country>();
// Add entries to the map
}
EDIT: One point worth noting - although you've got init() as the very first line of your static initializer, if you're actually doing anything else before then (possibly in other variable initializers) which calls out to another class, and that class calls back into your Country class, then that code will be executed while allCountries is still null.
EDIT: Okay, now we can see your real code, I've found the problem. Your post code has this:
private static Map<String, Country> allCountries;
static {
...
}
But your real code has this:
static {
...
}
private static Collection<Country> allCountries = null;
There are two important differences here:
The variable declaration occurs after the static initializer block
The variable declaration includes an explicit assignment to null
The combination of those is messing you up: the variable initializers aren't all run before the static initializer - initialization occurs in textual order.
So you're populating the collection... and then setting the reference to null.
Section 12.4.2 of the JLS guarantees it in step 9 of the initialization:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
Demonstration code:
class Foo {
private static String before = "before";
static {
before = "in init";
after = "in init";
leftDefault = "in init";
}
private static String after = "after";
private static String leftDefault;
static void dump() {
System.out.println("before = " + before);
System.out.println("after = " + after);
System.out.println("leftDefault = " + leftDefault);
}
}
public class Test {
public static void main(String[] args) throws Exception {
Foo.dump();
}
}
Output:
before = in init
after = after
leftDefault = in init
So the solution is either to get rid of the explicit assignment to null, or to move the declarations (and therefore initializers) to before the static initializer, or (my preference) both.
The static initializer will get called when the class is loaded, which is normally when it is first 'mentioned'. So calling a static method would indeed trigger the initializer if this is the first time that the class gets referenced.
Are you sure the null pointer exception is from the allcountries.get(), and not from a null Country returned by get()? In other words, are you certain which object is null?
Theoretically, static block should get executed by the time classloader loads the class.
Country country = Country.findByISO("RO");
^
In your code, it is initialized the first time you mention the class Country (probably the line above).
I ran this:
public class Country {
private static Map<String, Country> allCountries;
static {
allCountries = new HashMap<String, Country>();
allCountries.put("RO", new Country());
}
public static Country findByISO(String cc) {
return allCountries.get(cc);
}
}
with this:
public class Start
{
public static void main(String[] args){
Country country = Country.findByISO("RO");
System.out.println(country);
}
}
and everything worked correctly. Can you post the stack trace of the error?
I would say that the problem lies in the fact that the static block is declared before the actual field.
Do you have allCountries = new HashMap(); in your static initializer block? The static initializer block is actually called upon class initialization.
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");
}
}