how static method works in java code example
Example 1: static in java
using static before a method or variable we can access it by not creating a
instance of it.in the program we directly used student.cube(5)
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Example 2: 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 3: 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 4: 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();
}
}