What is java static block

Static Variable in Java: What is Static Block & Method [Example]

Let’s look at static variables and static methods first.

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution. 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

What is Static Method in Java?

Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. It is a method which belongs to the class and not to the object(instance). A static method can access only static data. It cannot access non-static data (instance variables).

  • A 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
  • A static method cannot refer to “this” or “super” keywords in anyway
Читайте также:  Public static classes java

Note: main method is static, since it must be accessible for an application to run, before any instantiation takes place.

Example: How to call static variables & methods

Step 1) Copy the following code into a editor

public class Demo < public static void main(String args[])< Student s1 = new Student(); s1.showData(); Student s2 = new Student(); s2.showData(); //Student.b++; //s1.showData(); >> class Student < int a; //initialized to zero static int b; //initialized to zero only when class is loaded not for each object created. Student()< //Constructor incrementing static variable b b++; >public void showData()< System.out.println("Value of a = "+a); System.out.println("Value of b text-align:center"> 
Java Static Methods and Variables

Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.


Java Static Methods and Variables

Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.


Java Static Methods and Variables

Step 4) It is possible to access a static variable from outside the class using the syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile & Run . Observe the output.

Value of a = 0 Value of b = 1 Value of a = 0 Value of b = 2 Value of a = 0 Value of b = 3

Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.

error: non-static variable a cannot be referenced from a static context a++;

Step 6) Error = ? This is because it is not possible to access instance variable “a” from java static class method “increment“.

What is Static Block in Java?

The static block is a block of statement inside a Java class that will be executed when a class is first loaded into the JVM. A static block helps to initialize the static data members, just like constructors help to initialize instance members.

Following program is the example of java static block.

Example: How to access static block

Источник

Static Blocks in Java

In simpler language whenever we use a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory.

Calling of static block in java?

Now comes the point of how to call this static block. So in order to call any static block, there is no specified way as static block executes automatically when the class is loaded in memory. Refer to the below illustration for understanding how static block is called.

Illustration:

class GFG < // Constructor of this class GFG() <>// Method of this class public static void print() < >static<> public static void main(String[] args) < // Calling of method inside main() GFG geeks = new GFG(); // Calling of constructor inside main() new GFG(); // Calling of static block // Nothing to do here as it is called // automatically as class is loaded in memory >>

Note: From the above illustration we can perceive that static blocks are automatically called as soon as class is loaded in memory and there is nothing to do as we have to in case of calling methods and constructors inside main().

Can we print something on the console without creating main() method?

It is very important question from the interview’s perceptive point. The answer is yes we can print if we are using JDK version 1.6 or previous and if after that it will throw an. error.

Example 1-A: Running on JDK version 1.6 of Previous

Источник

static keyword in java

static keyword in java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

static keyword in Java is used a lot in java programming. Java static keyword is used to create a Class level variable in java. static variables and methods are part of the class, not the instances of the class.

static keyword in java

java static, static keyword in javaJava static keyword can be used in five cases as shown in below image. static keyword in java We will discuss four of them here, the fifth one was introduced in Java 8 and that has been discussed at Java 8 interface changes.

Java static variable

We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe. Usually, static variables are used with the final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName

 //static variable example private static int count; public static String str; public static final String DB_USER = "myuser"; 

Java static method

Same as static variable, static method belong to class and not to class instances. A static method can access only static variables of class and invoke only static methods of the class. Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. For example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

 //static method example public static void setCount(int count) < if(count >0) StaticExample.count = count; > //static util method public static int addInts(int i, int. js)

Java static block

Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. Static block is used to initialize the static variables of the class. Mostly it’s used to create static resources when the class is loaded. We can’t access non-static variables in the static block. We can have multiple static blocks in a class, although it doesn’t make much sense. Static block code is executed only once when the class is loaded into memory.

Java Static Class

Let’s see all the static keyword in java usage in a sample program. StaticExample.java

package com.journaldev.misc; public class StaticExample < //static block static< //can be used to initialize resources when class is loaded System.out.println("StaticExample static block"); //can access only static variables and methods str="Test"; setCount(2); >//multiple static blocks in same class static < System.out.println("StaticExample static block2"); >//static variable example private static int count; //kept private to control its value through setter public static String str; public int getCount() < return count; >//static method example public static void setCount(int count) < if(count >0) StaticExample.count = count; > //static util method public static int addInts(int i, int. js) < int sum=i; for(int x : js) sum+=x; return sum; >//static class example - used for packaging convenience only public static class MyStaticClass < public int count; >> 

Let’s see how to use static variable, method and static class in a test program. TestStatic.java

package com.journaldev.misc; public class TestStatic < public static void main(String[] args) < StaticExample.setCount(5); //non-private static variables can be accessed with class name StaticExample.str = "abc"; StaticExample se = new StaticExample(); System.out.println(se.getCount()); //class and instance static variables are same System.out.println(StaticExample.str +" is same as "+se.str); System.out.println(StaticExample.str == se.str); //static nested classes are like normal top-level classes StaticExample.MyStaticClass myStaticClass = new StaticExample.MyStaticClass(); myStaticClass.count=10; StaticExample.MyStaticClass myStaticClass1 = new StaticExample.MyStaticClass(); myStaticClass1.count=20; System.out.println(myStaticClass.count); System.out.println(myStaticClass1.count); >> 

The output of the above static keyword in java example program is:

StaticExample static block StaticExample static block2 5 abc is same as abc true 10 20 

Notice that static block code is executed first and only once as soon as class is loaded into memory. Other outputs are self-explanatory.

Java static import

Normally we access static members using Class reference, from Java 1.5 we can use java static import to avoid class reference. Below is a simple example of Java static import.

package com.journaldev.test; public class A < public static int MAX = 1000; public static void foo()< System.out.println("foo static method"); >> 
package com.journaldev.test; import static com.journaldev.test.A.MAX; import static com.journaldev.test.A.foo; public class B < public static void main(String args[])< System.out.println(MAX); //normally A.MAX foo(); // normally A.foo() >> 

Notice the import statements, for static import we have to use import static followed by the fully classified static member of a class. For importing all the static members of a class, we can use * as in import static com.journaldev.test.A.*; . We should use it only when we are using the static variable of a class multiple times, it’s not good for readability. Update: I have recently created a video to explain static keyword in java, you should watch it below. https://www.youtube.com/watch?v=2e-l1vb\_fwM

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью