Showing posts with label Java static. Show all posts
Showing posts with label Java static. Show all posts

Thursday, October 30, 2025

static Import in Java With Examples

In order to access any static member (static field or method) of a class, it is necessary to qualify references with the class they have come from.

ClassName.static_method()

With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. So, static import in Java allows unqualified access to the static member. This shortens the syntax required to use a static member.

Syntax of static import in Java

Any Java program can import the members individually or en masse-

// accessing specific static variable of a class
import static package_name.class_name.static_variable;

// accessing specific static method of a class
import static package_name.class_name.static_method;

// accessing all the static members of a class en masse
import static package_name.class_name.*;

Saturday, March 23, 2024

static Block in Java

Static block in Java is used for static initializations of a class. Consider a scenario where initialization of static variables requires some logic (for example, error handling or a for loop to fill a complex array). In such scenarios, simple assignment is inadequate.

In case of instance variables, initialization can be done in constructors, where exception handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Refer Initializer block in Java to see another way to initialize instance variables.

static Block is Executed Only Once

A static block in a class is executed only once, when the class is first loaded, even before the main method.

Note that class can be loaded when you create an object of that class or when you access the static member of that class for the first time.

General form of the Java static block

static{
  // whatever code is needed for initialization goes here
}

static Block Java Example

public class StaticBlockDemo {
  // static blank final variable
  static final int i;
  static int b;
  //static block
  static {
   System.out.println("in static block");
   i = 5;
   b = i * 5;
   System.out.println("Values " + i + " " +  b);
  }
  
  public static void main(String[] args) {
     System.out.println(" in main method ");
  }
}

Output of the program

in static block
Values 5 25
in main method

It can be seen that main method is called only after executing the static block. In static block the static blank final variable is initialized. Also another static variable too is initialized with in the block after some computation.

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 in Java are called in the order that they appear in the source code.

Since static blocks are used to initialize the class variables so static blocks in Java are called before the constructor of the class.

public class StaticBlockDemo {
  // static blank final variable
  static final int i;
  static int b;
  //static block
  static {
   System.out.println("in static block");
   i = 5;
   b = i * 5;
   System.out.println("Values " + i + " " +  b);
  }
  
  StaticBlockDemo(){
   System.out.println("In constructor");
  }
  
  public static void main(String[] args) {
    System.out.println("in main method ");
    StaticBlockDemo sb = new StaticBlockDemo();
  }
  
  static {
   System.out.println("In another static block");
  }

}

Output

in static block
Values 5 25
In another static block
in main method 
In constructor

Java static block exception handling

static block can throw only RunTimeException, or there should be a try-catch block to catch checked exception.

static int i;
static int b;
static {
 System.out.println("in static block");
 try{
  i = 5;
  b = i * 5;
 }catch(Exception exp){
  System.out.println("Exception while initializing" + exp.getMessage());
  throw new RuntimeException(exp.getMessage()); 
}
 //System.out.println("Values " + i + " " +  b);
}

That's all for this topic static Block in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. static Keyword in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. Interface Static Methods in Java
  4. Initializer block in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. super Keyword in Java With Examples
  2. this Keyword in Java With Examples
  3. Constructor overloading in Java
  4. Java Abstract Class and Abstract Method
  5. final Vs finally Vs finalize in Java
  6. How to Sort ArrayList of Custom Objects in Java
  7. Java Multithreading Interview Questions And Answers
  8. Java Stream API Examples

Saturday, July 17, 2021

static Method Overloading or Overriding in Java

Can we overload static Method in Java and can we override static method in Java are important Java interview questions, in this tutorial we'll try to understand whether that is possible or not. To set the context for understanding static method overloading and static method overriding in Java, first let's have a little introduction of what is overloading and what is overriding.

  • Method Overloading- When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded.
    Refer Method overloading in Java for better understanding.
  • Method Overriding- In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
    Refer Method overriding in Java for better understanding.

Static method overloading in Java

Static methods in Java can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.

Saturday, May 15, 2021

static Keyword in Java With Examples

When we want to define a class member that can be used independently of any object of that class we use static keyword in Java. When a class member is defined as static it is associated with the class, rather than with any object.

The static keyword in Java can be used with-

Static Variable in Java

A variable declared as static in Java is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable. A static variable can be accessed directly using the class and doesn't need any object.

Since static variables are associated with the class, not with instances of the class, they are part of the class data in the method area.

Usage of Static variable

One common use of static keyword in Java is to create a constant value that's at a class level and applicable to all created objects, it is a common practice to declare constants as public final static. static so that it is at class level, shared by all the objects, final so that the value is not changed anytime.

static field example

public class Employee {
 int empId;
 String name;
 String dept;
 // static constant
 static final String COMPANY_NAME = "XYZ";
 Employee(int empId, String name, String dept){
  this.empId = empId;
  this.name = name;
  this.dept = dept;
 }
 
 public void displayData(){
  System.out.println("EmpId = " + empId + " name= " + name + " dept = " + 
  dept + " company = " + COMPANY_NAME);
 }
 public static void main(String args[]){  
  Employee emp1 = new Employee(1, "Ram", "IT");
  Employee emp2 = new Employee(2, "Krishna", "IT");
  emp1.displayData();
  emp2.displayData();
 }
}
Output
EmpId = 1 name= Ram dept = IT company = XYZ
EmpId = 2 name= Krishna dept = IT company = XYZ

Another usage is when there is a requirement to have a counter at the class level. Since static variable is associated to the class and will have the same value for every instance of the class, where as value of non static variable will vary from object to object. So any counter which should be at the class level has to be declared as static.

class Counter{
 // at class level and gets memory only once
 static int count = 0;
 
 Counter(){
  count++;
 }
}

Static Method in Java

Same as static variable, static method is also associated with the class rather than objects of the class. Static method can be called directly using the class name like ClassName.static_method() rather than with the object of the class.

main() method is the most common example of static method, main() method is declared static because main() must be called before any object of the class exists.

Usage of Static method

The most common usage of static method is to declare all the utility methods (like date formatting, conversion of data types) as static. Reason being these utility methods are not part of actual business functionality so should not be associated with individual objects.

Example of Static method

public class StaticDemo {
 static void staticMethod(int i){
  System.out.println("in static method " + i);
 }
 
 public static void main(String[] args) {  
  StaticDemo.staticMethod(5);
 }
}

It can be seen here that the staticMethod is accessed with the class itself.

StaticDemo.staticMethod(5);

Please note that it won't be an error if class object is used to access a static method, though compiler will warn to use class instead.

Restrictions with static method in Java

  1. static method can directly call other static methods only.
    public class StaticDemo {
     // Non Static method
     void staticMethod(int i){
      System.out.println("in static method " + i);
     }
     
     public static void main(String[] args) {  
      staticMethod(5); // Compiler error
     }
    }
    
    It will throw compiler error "Can not make static reference to the non-static method".
  2. static method can directly access static data only
    public class StaticDemo {
     // non static field
     int i;
     
     public static void main(String[] args) {  
      i = 10; // Compiler error
     }
    }
    
    It will throw compiler error "Cannot make a static reference to the non-static field".
  3. Static methods cannot refer to this or super in any way.

Static Block in Java

A static block in a class is executed only once, when the class is first loaded, even before the main method.

Usage of Static Block in Java

A static final variable that is not initialized at the time of declaration is known as static blank final variable in Java. It can be initialized only in static block.
If some computation is needed, in order to initialize a static variable, that can be done in static block.

public class StaticDemo {
 // static blank final variable
 static final int i;
 static int b;
 static {
  System.out.println("in static block");
  i = 5;
  b = i * 5;
  System.out.println("Values " + i + " " +  b);
 }
 
 public static void main(String args[]){  
  System.out.println(" in main method ");
 }
}
Output of the program
in static block
Values 5 25
in main method

It can be seen that main method is called only after executing the static block. In static block the static blank final variable is initialized. Also Another static variable too is initialized with in the block after some computation.

static nested class

Top level class can't be declared as static but a nested class can be declared as static, such a nested class is known as static nested class in Java.

Points to note about static keyword in Java-

  • static keyword in Java can be used with variables, methods and nested class in Java. There can also be a static block.
  • static variables and methods are associated with class itself rather than with any object.
  • static variables will have a single copy that will be used by all the objects.
  • static members of a class can be accessed even before object of a class is created.
  • static fields are not thread safe so proper synchronization should be done in case of several threads accessing the static variable.
  • static methods can directly call other static methods only and directly access static fields only.
  • static methods can be overloaded but can not be overridden.
  • static block is executed in a class at the time of class loading even before the main method.
  • With static import it is possible to access any static member (static field or method) of the class with out qualifying it with class name.

That's all for this topic static Keyword in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. static Import in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. Why main Method static in Java
  4. Interface Static Methods in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. super Keyword in Java With Examples
  2. this Keyword in Java With Examples
  3. Constructor Overloading in Java
  4. Exception Handling in Java Lambda Expression
  5. Difference Between throw And throws in Java
  6. final Vs finally Vs finalize in Java
  7. Java ReentrantReadWriteLock With Examples
  8. How HashMap Works Internally in Java

Monday, February 22, 2021

Fix Cannot make a static Reference to The Non-static Method Error

When a person moves beyond the "Hello world" program where everything is with in a main method and writes a program with more than one method, one error he or she surely will encounter is "Cannot make a static reference to the non-static method or a non-static field".

Not only beginners even experienced programmers unknowingly keep making the mistake of trying to access a non-static method or field from a static context and get a reminder from compiler that they have forgotten the basics! At least I do that many times when I write a program to test something and from main method (which is static) I try to access some non-static method and get the error "Cannot make a static reference to the non-static method or a non-static field".