Showing posts with label Java Tricks. Show all posts
Showing posts with label Java Tricks. Show all posts

Wednesday, 8 October 2014

Explain public static void main(string [] args)

Q. The question comes here is why java's main function has all the keyword like public, static  and void?

Ans. First start with public is because of scope of the main function so that it can be called out of the class . If it would be private or something else compiler can not invoke the main function out of the class.

Second static is because when main function is called there will be no object of the class so if we want to call a method of a class without initializing the object of that class then we have to make that method static. Static function can be called without initializing the object of that class.

Void is the return type of main function we can not change it because main function will not return anything in java. If it would then to whom it will return something?? Think about it......

And the argument is the array of string objects which it expects.

Two main function in java

Q. The question is that can we have two main functions in java?

Ans. Yes, We can have two main function in java but the function's prototype should be different.

 For example we can have two functions like-
public static void main(string[] args);

and second one may be

public static void main(int a);


The reason for this is that when compiler/interpreter starts executing it starts with finding a function whose prototype is similar to the first one i have written have which takes argument as a array of string objects. It does not consider the second main function because it has different argument then the one which is needed. So we can have two main functions with two different arguments and one of them should be similar to the first one.

Related Posts

Related Posts Plugin for WordPress, Blogger...