java static method code example
Example 1: what is static method
A static method belongs to the class rather than the object.
There is no need to create the object to call the static methods.
A static method can access and change the value of the static variable
Example 2: static in java
static keyword is a non-access modifier. static keyword can be used with
class level variable, block, method and inner class or nested class.
Example 3: do i have to use static methods in java main
Use a static method
when you want to be able to access the method
without an instance of the class
Example 4: how to call a static method in java
class scratch{
public static hey(){
System.out.println("Hey");
}
public static void main(String[] args){
hey();
}
Example 5: Static method in java
We can declare a method as static by adding keyword “static” before method name.
Let’s see example on static method in java.
public class StaticMethodExample
{
static void print()
{
System.out.println("in static method.");
}
public static void main(String[] args)
{
StaticMethodExample.print();
}
}
Example 6: static data and static methods in java
class JavaExample{
private static String str = "BeginnersBook";
static class MyNestedClass{
public void disp() {
System.out.println(str);
}
}
public static void main(String args[])
{
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
}