Java Programming - Language Fundamentals - Discussion

Discussion Forum : Language Fundamentals - Finding the output (Q.No. 3)
3.
public class F0091 
{    
    public void main( String[] args ) 
    {  
        System.out.println( "Hello" + args[0] ); 
    } 
}

What will be the output of the program, if this code is executed with the command line:

> java F0091 world

Hello
Hello Foo91
Hello world
The code does not run.
Answer: Option
Explanation:

Option D is correct. A runtime error will occur owning to the main method of the code fragment not being declared static:

Exception in thread "main" java.lang.NoSuchMethodError: main

The Java Language Specification clearly states: "The main method must be declared public, static, and void. It must accept a single argument that is an array of strings."

Discussion:
18 comments Page 1 of 2.

Nikhila said:   1 decade ago
@Jyothirmai.

Main method cannot be a instance method so we need need to use static keyword. For clear idea consider instance method or instance variable so to call them we need create an object in main method. If main method itself is in instance method so where we need to create an object for that instance main method.

I think you got my point.

Sudheer said:   1 decade ago
Static methods executes first than the constructor or instance method. Static method will execute in heap when the object of the class is created.

If we do not make the main method as static who will call the main method in our class, that's why when the class object is created the static methods are automatically executed by JVM.

Sambhunath Samanta said:   1 decade ago
When we access anything from any method then first we create object of this method after that we access but if we declare method is static then we can access anything from this method without create object.

That why we use before main static keyword.
(1)

Alex said:   1 decade ago
Even if you put public static void main you will get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
because of exceeding array limit by o/p

Purnima said:   1 decade ago
Here I mentioned as public static void main.

Still I m getting run time exception. What will be the prob? can anyone explain? Please.

Mansha said:   10 years ago
While including static in public static void main it is still giving error that cannot find or load main class.

Akash said:   1 decade ago
Can we use private instead of public in main method this question had been asked in my interview.

Ganesh said:   1 decade ago
If main method contain static keyword. What is the result for that code please explain?

Aniruddh said:   1 decade ago
@Akash : Use of private with psvm() will lead to runtime exception : nosuchmainfound.

Rochu said:   1 decade ago
If main method contain static keyword then what will be the result. Please help me.


Post your comments here:

Your comments will be displayed after verification.