Is there any alternative solution for static constructor in java?

Java 8Object Oriented ProgrammingProgramming

The main purpose of constructors in Java is to initialize the instance variables of a class.

But, if a class have Static variables you cannot initialize them using the constructors (you can assign values to static variables in constructors but in that scenario, we are just assigning values to static variables). because static variables are loaded into the memory before instantiation (i.e. before constructors are invoked)

So, we should initialize static variables from static context. We cannot use static before constructors, Therefore, as an alternation to you can use static blocks to initialize static variables.

Static block

A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Example

In the Following java program, the class Student has two static variables name and age.

In this, we are reading the name, age values from the user using Scanner class and, initializing the static variables from a static block.

import java.util.Scanner;
public class Student {
   public static String name;
   public static int age;
   static {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      age = sc.nextInt();
   }
   public void display(){
      System.out.println("Name of the Student: "+Student.name );
      System.out.println("Age of the Student: "+Student.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Output

Enter the name of the student:
Ramana
Enter the age of the student:
16
Name of the Student: Ramana
Age of the Student: 16
raja
Published on 03-Jul-2019 16:54:38
Advertisements