Untitled Document

Subscribe here to get updates on new Videos

 

13. Explain about public static void main(String[] args); (PART- III) ?

 

 

 

previous homenext

 

1.7 Version Enhancements wrt main() method

Case 1:

Until 1.6 version if the class doesn’t contain main() method then we will get runtime exception saying no such method error. But form 1.7version onwards instead of NoSuchMethodError we will get more meaningful error information.

class Test
{
}

1.6version

javac Test.java
java Test
RE: NoSuchMethodError: main

1.7version

Javac Test.java
Java Test
Error: Main method not found in class test, please define main method as
public static void main(String[] args)

Case 2:

From 1.7 version onwards to run a java program main method is mandatory. Hence, even though class contains static blocks they wont be executed if the class doesn’t contain main() method.

Program:

class Test
{
static
{
System.out.println(“static block”);
}
}

1.6version

javac Test.java
java Test
output: static block
RE: NoSuchMethodError: main

1.7version

javac Test.java
java Test
Error: main method not found in class

Example-2:

class Test
{
static
{
System.out.println(“static block”);
System.exit(0);
}
}

1.6version

javac Test.java
java Test
output: static block
RE: NoSuchMethodError: main

1.7version

javac Test.java
java Test
Error: main method not found in class

Example-3:

If the class contains main() method whether it is 1.6 or 1.7 version there is no change in execution sequence.

class Test
{
static
{
System.out.println(“static block”);
}
public static void main(String[] args)
{
System.out.println(“main method”);
}
}

1.6version

javac Test.java
java Test
output: static block
main method

1.7version

javac Test.java
java Test
output: static block
main method


With out writing main() method is it possible to print some statements to the console?
Yes we can print by using static block.
But this rule is applicable until 1.6version only from 1.7version onwards main() method is mandatory to print some statements to the console.