Java - Interview Questions and Answers on Main Method

Q1.  What will happen if we remove the static keyword from main method ?

Ans. Program will compile but will give a "NoSuchMethodError" during runtime.

Q2.  How are classes loaded by JVM ?

Ans. Class loaders are hierarchical. The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. 

Q3.  Is it possible to compile and run a Java program without writing main( ) method?

Ans. Yes, it is possible by using a static block in the Java program.

Q4.  public class a {
     public static void main(String args[]){
          final String s1="job";
          final String s2="seeker";
          String s3=s1.concat(s2);
          String s4="jobseeker";
          System.out.println(s3==s4); // Output 1
          System.out.println(s3.hashCode()==s4.hashCode()); Output 2

What will be the Output 1 and Output 2 ?

Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.