Java interview questions with answers
Home Java Interview Questions Revision Notes Resources Interview Tips Interview Samples

Valid HTML 4.01 Transitional

Java Interview Questions & Answers
Part 3 - Main method and Java File Structure

Should a main method be compulsorily declared in all java classes?
No not required. main method should be defined only if the source class is a java application.

What is the return type of the main method?
Main method doesn't return anything hence declared void.

Why is the main method declared static?
main method is the entry point for a Java application and main method is called by the JVM even before the instantiation of the class hence it is declared as static. static methods can be called even before the creation of objects.

What is the argument of main method?
main method accepts an array of String objects as argument.

How to pass an argument to main method?
You should pass the argument as a command line argument. Command line arguments are seprated by a space. The following is an example:

java Hello Tom Jerry

In the above command line Hello is the class, Tom is the first argument and Jerry is the second argument.

What will happen if no argument is passed to the main method?
If you dont access the argument, the main method will execute without any problem. If try to access the argument, NullPointerException will be thrown.

Can a main method be overloaded?
Yes. You can have any number of main methods with different method signature and implementation in the class.

Can a main method be declared final?
Yes. Any inheriting class will not be able to have it's own default main method.

Does the order of public and static declaration matter in main method?
No it doesn't matter but void should always come before main().

Can a source file contain more than one Class declaration?
Yes. A single source file can contain any number of Class declarations but only one of the class can be declared as public.

If a source file has 2 class declaration in it, on compilation how many class files will be created?
2 class files will be generated by the compiler.

Can the first line of the source code be a comment?
Yes. Comments can appear anywhere in the code. It is just a "skip this line" instruction to the conpiler.

Can the source file name and the class name in the file be different?
If the class in the source is not of public access, then the name can be anything but should confirm to identifier rules.

Will the below statement result in compilation error or runtime error?
         System.out.println("Hi");;;
The statement will compile and execute without any problem. Semicolon is just a statement terminator.



Pls send your questions, suggestions and feedback to j2eeguide@yahoo.com

© Copyright JGuide 2006, All Rights Reserved.