Java Programming - Language Fundamentals - Discussion

Discussion Forum : Language Fundamentals - Finding the output (Q.No. 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 Foo91
Hello world
The code does not run.
Answer: Option

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."

18 comments Page 1 of 2.

Shiwam said:   1 decade ago
If it is declared as static then o/p is ?

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.

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

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

Rupa said:   1 decade ago
It is declared as static then o/p is Helloworld.

Jyothirmai said:   1 decade ago
Why should we use static in before main method?

Nikhila said:   1 decade ago

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.

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

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.

Post your comments here:

Your comments will be displayed after verification.