All About Static and Nonstatic method in Java - Selenium Tutorials Beginners

Java is one of the most widely used programming languages in the world and it has many advantages over other programming languages. There are many features in Java that makes it user-friendly and one among them is Java methods.

A group of statements collected together to perform an operation is called as a java method. Basically, there are two different types of methods in Java static method and nonstatic method.

As you are aware, Java is an Object Oriented Programing language. In other sense, we need an object to access a method or variables in Java but in certain cases, there is no need of an object. Yes, there is no need of an object to access static methods in Java. Given below is an example of a static method in java.

class StaticDemo
{
public static void copyArg(String str1, String str2)
{
//copies argument 2 to arg1
str2 = str1;
System.out.println(“First String arg is: “+str1);
System.out.println(“Second String arg is: “+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg(“XYZ”, “ABC”);
copyArg(“XYZ”, “ABC”);
}
}

Output
First String arg is: XYZ
Second String arg is: XYZ

Here you can see that no object has been used to call a static method.

However, you need an object to call non static method in java and here is an example.

class Test
{
public void display()
{
System.out.println(“I’m non-static method”);
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}

Output
I’m non-static method

This example clearly indicates that you need an object of the class to call a non static method.

There are some major differences between static methods and no static methods in java.

  • Whenever a nonstatic method is called, memory is allocated multiple times but it will be allocated only at the time of class loading in the case of a static method.
  • Nonstatic methods are specific for an object and hence they are also known as object instances where are as static methods are common to all objects.
  • Nonstatic methods always access with object reference while static methods always access with class reference.
  • Nonstatic methods can be executed multiple times in a program while static method can be executed only once.

Now you might have a basic idea about methods in java and about the differences between static and nonstatic methods. More will be taught in java tutorials. This part of the tutorial is more important as one should have thorough knowledge in methods and variables in java to work with it successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *