Site icon DataFlair

Java Static Keyword – Master the Concept of Static Methods in Java

Java-Static-Method-Class-Variable-Block

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

In Java, using the static keyword, we can have a static method, a static class, a static block, and a static variable. This keyword is mainly used for the management of memory. We can use the static keyword with methods, variables, classes, and blocks. It belongs to a class rather than an instance of the class. It simply means that if you make any variable static to can access it without its object.

Static can be:

1. Block

2. Variable (also known as a class variable)

3. Method (also known as a class method)

4. Class

Static Block in Java

A static block initializes the static variables. It executes whenever the class is loaded in memory. One class can have numerous static blocks, which will be executed in the same sequence in which they are written.

Example of Static Block in Java-

package com.dataflair.statickeyword;
public class StaticBlock 
{
   static String sentence;
   static int number;
   static
    {
         sentence = "Welcome to DataFlair";
         number = 69;
    }
    public static void main(String args[])
    {
         System.out.println(sentence);
         System.out.println("Value of Integer: "+number);
    }
}

Output-

Static Variable in Java

Any variable that is declared using the ‘static’ keyword is static. Memory allocation for a static variable happens only once in the class area when the class is loaded into memory. It is also known as a class variable. It is common to all the objects of the class.

In this, a single copy of a static variable is created and shared among all the objects of the class.

Example of Static Variable in Java-

package com.dataflair.statickeyword;
class Employee
 { 
   int empId; 
   String empName; 
   static String companyName = "TCS"; 
   //constructor to initialize the variable 
   Employee(int id, String name){ 
      empId = id; 
      empName = name; 
   } 
   //method to display values 
   void display()
   {
      System.out.println(empId+" "+empName+" "+companyName);
   } 
} 
//class to create and display the values of object 
public class StaticVariable 
{ 
      public static void main(String args[])
      { 
         Employee EmployeeObj = new Employee(218,"Kushal"); 
         Employee EmployeeObj1 = new Employee(635,"Bhumika"); 
         Employee EmployeeObj2 = new Employee(147,"Renuka"); 
         //calling display method 
         EmployeeObj.display(); 
         EmployeeObj1.display(); 
         EmployeeObj2.display(); 
      } 
}

Output-

Static Methods in Java

Static methods in Java belong to classes; unlike other classes, it doesn’t belong to the instance of the class. This method can be accessible to every instance, but the methods defined in the instance are only accessed by that member of the class. It can access only static data.

1. These are declared with the keyword “static” when defining a method

2. This method belongs to the class and not to the object.

3. It can access only static data. It can not access instance variables.

4. A static method can call only static methods; non-static methods are not called by a static method.

5. Static methods in Java are accessed by using the method name with the (.) dot operator and the class name.

Example of Java Static Methods-

//Java Program to demonstrate the use of a static method.
package com.dataflair.staticmethod;
class Employee
{ 
   int empId; 
   String empName; 
   static String companyName = "TCS"; 
   //static method to valueChange the value of static variable 
   static void valueChange()
   { 
      companyName = "DataFlair"; 
   } 
   //constructor to initialize the variable 
   Employee(int id, String name){ 
      empId = id; 
      empName = name; 
   } 
//method to display values 
void display()
   {
      System.out.println(empId+" "+empName+" "+companyName);
   } 
} 
//class to create and display the values of object 
public class Demo 
{ 
   public static void main(String args[])
      { 
         Employee.valueChange();//calling valueChange method 
         //creating objects 
         Employee EmployeeObj = new Employee(218,"Kushal"); 
         Employee EmployeeObj1 = new Employee(635,"Bhumika"); 
         Employee EmployeeObj2 = new Employee(147,"Renuka"); 
         //calling display method 
         EmployeeObj.display(); 
         EmployeeObj1.display(); 
         EmployeeObj2.display(); 
      } 
}

Output-

Advantages of Using Static Methods

Static methods offer several benefits in Java programming these are:

1. Improved Code Readability: By grouping utility methods or helper functions that don’t rely on object state as static, you can enhance code readability and maintainability. Static methods indicate their purpose and independence from object creation.

2. Enhanced Performance: In some scenarios, static methods can lead to performance optimizations. Since they are resolved at class loading time, static method calls can avoid the overhead of object creation and method lookup. This can be especially beneficial for frequently used utility functions.

Java Static Class

Java allows us to define a class but not a static class, which simply means that we can define a class as static only if it is a nested class. In Java, a class can be static when it is a nested class. Therefore, A nested static class doesn’t need any reference to the Outer class. Non-static members are not accessed by a static class.

In Java, an outer class cannot be declared as static because the use of static represents that it is dedicated to the class. If the outer class is declared as static, then which class properties will it be using?. That’s why we define the static class in the nested class.

Hence, the members that are not static in the outer class cannot be accessed by a static class.

Example of a static class in Java-

// Java program to demonstrate how to implement static class
package com.dataflair.statickeyword;
class OuterClass{ 
      private static String messageToReaders = "Hello Readers! Welcome to DataFlair"; 
      // Static nested class 
      public static class NestedStaticClass{ 
            // static class 
            public void myMessage() 
            { 
                  System.out.println("Message from nested static class: " + messageToReaders); 
            } 
      } 
      // non-static nested class 
      public class InnerClass{ 
            public void display(){ 
            System.out.println("Message from non-static nested class: "+ messageToReaders); 
            } 
      } 
} 
public class StaticClass {
      public static void main(String args[]){ 
      // instance of nested Static class 
      OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass(); 
      // call non static method of nested static class 
      printer.myMessage(); 
      OuterClass outer = new OuterClass(); 
      OuterClass.InnerClass inner = outer.new InnerClass(); 
      // calling non-static method of Inner class 
      inner.display(); 
      OuterClass.InnerClass innerObject = new OuterClass().new       InnerClass(); 
      innerObject.display(); 
      } 
}

Output-

What is a Java Instance Method?

An instance method in Java is basically a method of the class. In other words, a non-static method that is declared inside a class is an instance method. Therefore, this kind of method requires an object of its class to be created before it can be called. To invoke an instance method, we have to create an object of the class.

public void Dataflair(String name)
{
// code to be executed....
}

Instance Methods vs Static Methods in Java

1. The instance method requires the object of its class to be created before it can be called. However, Static methods in Java can be called without creating an object of the class.

2. A Java static method is declared using the static keyword. Therefore, an instance method does not need any keyword.

3. The static method has a single copy for a class. But instance methods have multiple copies depending on the number of instances created for that particular class.

4. We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.

5. We can’t access instance methods and instance variables with the help of Static methods in Java. Although we can access static variables and static methods with the help of the Instance method.

Quiz on Java Static Methods

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    Which of the following is the correct way to invoke a static method ?

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    class Method {

    static void square(int a)

    {

    return(a*a);

    }

    public static void main ( String args [ ] )

    {

    System.out.println(square(5));

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    class Function {

        void display()

    {

    system.out.println(“Non-static method”);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Function.display();

    }

    }

    What will be the output of the program ?

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    Which of the following cannot be done using the static methods in java?

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    class One {

    static addition(int a , int b)

    {

    return a+b;

    }

    static subtraction(int a , int b)

    {

    return a-b;

    }

    public static void main ( String args [ ] )

    {

    System.out.println(addition(2,3)+”,”+subtraction(3,2));

    }

    }

    What will be the output of the program ?

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

     class A {

    static method1()

    {

    System.out.println(“Static method”);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    method1();

    }

    }

    What is the error in the program ?

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    Which of the following keywords raise an error in static methods ?

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

     class Text {

    String name = “ ”;

    static void display(string a)

    {

    name = a;

    System.out.println(name);

    }

    public void print(String b)

    {

    name = b;

    System.out.println(name);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Text.display(“DataFlair”);

    Text t = new Text();

    t.print(“Webservices”);

    }

    }

    What should be the output of the program ?

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

     class Main {

    public static void main ( String args [ ] )

    {

    static void method(int a , int b , int c )

    {

    return a*b*c*;

    }

    method(10.9.8);

    }

    }

    What will be the output of the program ?

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    Which of the following is the syntax for invoking static methods ?

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    class Objects {

    Static void display()

    {

    System.out.println(“static class method”);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Objects obj = new Objects();

    obj.display();

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

     class Method {

        int b;

    Method(static int a)

    {

    b = this.a;

    system.out.println(b);

    }

    public static void main ( String args [ ] )

    {

    Method m = new Method(10);

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

     Which of the following concepts are used in static methods ?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    class StaticMethods {

    public static void main  ( String args [ ] )

    {

    static int b = 10;

    static void value( b)

    {

    Static int a = b*b;

    }

    System.out.println(a);

    }

    }

    What is the output of the program ?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

     class Sample {

    static void calculate( int x )

    {

    System.out.println(3.14*x*x);

    }

    }

    class Main {

    public static void main ( String args [ ] )

    {

    Sample.calculate(4);

    }

    }

    What will be the output of the program ?

    Correct
    Incorrect

Summary

It’s time to summarize the Java static keyword. We can use this feature in static blocks, static variables, static classes, and static methods in Java. In addition, you have to know the main difference between Instance methods and static methods in Java.

We hope you like the explanation.

Please drop all the queries and suggestions in the comment section.

Exit mobile version