Tuesday, 30 August 2016

Is it possible to execute any java application without using main method?

Q) Is it possible to display a line of text on command prompt without using main() method? 
Ans);-
Yes, it is possible to display a line of text on commend prompt without using main() method, but, by using static variable and static method combination.
D:\java1130\Test.java
Ex code :-
class Test
{
                static int i=m1();
                static int m1()
                {
                                System.out.println("Welcome to Sai Software Solutions");
                                System.exit(0);
        return 10;
                }
}
On command prompt
D:\java1130>javac Test.java
D:\java1130>java Test
Welcome to Sai Software solutions
If we providing “Test” class [main class] Name along with “java” command on command prompt then JVM will load main class byte code to the memory, at the time of loading main class byte code to the memory, JVM will recognized and initialized static variable[i], as part of initializing static variable JVM will access m1() method, with this m1() method call JVM will execute m1() method and display the required massage on command prompt then JVM will stop program execution abnormally as per “System.exit(0);” instruction.
Note :-      
The question and Answers are valid up to JAVA6 version, they are invalid in JAVA7 version, because, in java6 VERSION JVM will load main class byte code to the memory without checking main() method availability, but in JAVA7 version, first JVM will check whether main() method is available or not, in main class, if it is available then only JVM will load main class byte code to the memory, if main() method is not available then JVM will provide the following Error Message.
Error:- 
Main method not found in class Test, please define the main method as:

public static void main(String[] args)

No comments:

Post a Comment