Thursday, 20 November 2014

Upload Main() Method in JAVA

Standard

This is one of the mostly asked question in interviews .So, for this question you can say answer is "Yes" with confidently why because main() method is a just like a normal method but the only difference is the JVM automatically calls this method  when we given .class file to JVM as a input.Method overloading says overloaded methods contains method names as same and with different type of arguments or different number of arguments and  return type you may have same or different one with in the same class.So That we can overload main() just like other methods. To make it clear i will demonstrate with example.





Example:-


  1. public class Test {  
  2.    
  3.  public static void main(String args[]) {  
  4.     
  5.   System.out.println("I am in predefined main() method");  
  6.   Test t=new Test();  
  7.   //from here we are calling overloaded main() with empty arguments  
  8.   t.main();  
  9.     
  10.    }  
  11.    
  12.  public void main(){  
  13.     
  14.   System.out.println("I am in overloaded main() Method");  
  15.   //Here we are calling overloaded main() with two two integer type arguments  
  16.   int value =main(5,6);  
  17.   System.out.println("The value is "+value);  
  18.  }  
  19.     
  20.  public static int main(int a , int b){  
  21.   System.out.println("We are in main() with two int type arguments");  
  22.   int c=a+b;  
  23.   return c;  
  24.  }  
  25.    


Output:


  1. I am in predefined main() method  
  2. I am in overloaded main() Method  
  3. We are in main() with two int type arguments  
  4. The value is 11  

0 comments:

Post a Comment