Menu

Static block and method in Java?

Can a class be static in Java?

We can not make top level class static. Only nested or inner classes can be static.

Can we call main method explicitly in Java?

Yes, we can call main method explicitly.

Can we execute a program without main method?

No, we can not execute a program without main method. Up to Java 6 we were able to run a program using static block.

How to create a static method in Java? How to create a static block in Java? Inner Class in Java?
Below is the example code:


package abctest;

public class testExa {
public static void main(String[] args) {
System.out.println("Main method is working!!");

//Explicitly call main method of other class
   rashid.main(args);
       }
/* static block start*/
static {
       System.out.println("static block called ");
       
       //Call static method inside static block
       nameUser();     
       String[] val={"ABCD","CDE"};
       
       //Explicitly call main method from static block
       main(val);
       System.out.println("exiting static block called ");
}
/* static block end*/

//Static method
public static String nameUser()
{
String UserName="Name";
System.out.println("Static method executing");
return UserName;
}

//Static class declaration; Only inner class could be declare as a static
public static class rashid{
public static void main(String args[])
{
System.out.println("Main from class Rashid");
}
}
}

Output:


static block called 
Static method executing
Main method is working!!
Main from class Rashid
exiting static block called 
Main method is working!!

Main from class Rashid


No comments:

Post a Comment