Showing posts with label main function. Show all posts
Showing posts with label main function. 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.

Argument to main function in C/C++

Q. What is the use of passing argument to main function?
Ans.
      First of all we can define main function in three different format in c/c++.
      int main(int argc,char * argv[]);
      int main(void);
      int main();

Instead of int return type we can have any other pre defined data type as return type of main function.

We start with the first prototype, here main function excepts two arguments one is of type int and other is of type array of pointers. First of all these arguments are used for passing the input together when we start executing the program. We don't have to pass the first argument it automatically counts how many argument we have passed while executing the program and that will be stored in argc.

Second argument argv[] is array of character pointers which stores the inputs which we have sent with execution. for ex. argv[0] will have first argument and argv[1] will have second argument .


In the second prototype it does not except any argument if we passes a argument the compiler will give an error.

Third one is similar to the second one but the difference is that in third one we can pass as many argument we want it will not give an error but in the second one it will give an error while we pass an argument to main function using terminal (linux users).

Related Posts

Related Posts Plugin for WordPress, Blogger...