Static Method in Java



Static Method

  • By declaring a method using the static keyword, you can call it without first creating an object because it becomes a class method (i.e. a method that belongs to a class rather than an object).
  • Static methods are used for methods that do not need to access to an object's state or only use static fields. For example, the main method is a static method.
public static void main(String[] args)
  • It is the starting point for a Java application and does not need to access an object's state. In fact, there aren't any objects created at this point. Any parameters that it needs can be passed as a String array.
 Static Method in Java

Learn Java - Java tutorial - Static Method in Java - Java examples - Java programs

How do you call a static method ?

  • If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined.
  • For instance methods, this is the object that the method will access. For static methods, the class name should be specified.

What is static method in Java with example ?

  • 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 staticdata. It can not access non-static data (instance variables)

Syntax:

static return_type method_name();

Static method main is accessing static variables without object

Sample Code

class StaticJavaExample{
   static int x = 27;
   static String y = "welcome to wikitechy";
   //This is a static method
   public static void main(String args[]) 
   {
       System.out.println("x:"+x);
       System.out.println("y:"+y);
   }
}

Output

x:27
y:welcome to wikitechy

Static method accessed directly in static and non-static method

Sample Code

class StaticJavaExample{
  static int x = 276;
  static String y = "welcome to wikitechy";
  //Static method
  static void display()
  {
     System.out.println("x:"+x);
     System.out.println("x:"+y);
  }

  //non-static method
  void funcn()
  {
      //Static method called in non-static method
      display();
  }
  //static method
  public static void main(String args[])
  {
	  StaticJavaExample object = new StaticJavaExample();
	  //You need to have object to call this non-static method
	  object.fn();
	  
      //Static method called in another static method
      display();
   }
}

Output

x:276
x:welcome to wikitechy
x:276
x:welcome to wikitechy

What is the use of static method ?

  • If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class.
  • A static method invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.

Related Searches to Static Method in Java