• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on creating classes in Java  RSS feed

 
Vicat Mauricio
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't kill me guys I am a total noob to Java as I come from an AS3.0 background.


I noticed that there are no "Functions" in Java, I guess the Java "main" method is the closest thing to a function. The reason I ask this is because when I create a class in Java I noticed that the main method requires a parameter for me to get the Sample program to execute or I get an error when I run the program if the parameter is missing. Here is the following code:




why do I need to have the "String args[]" parameter in the main method in order to output the text if there is no reference to it inside the "main". "String args[]" looks as if I am creating a String variable with a some sort of array link? can someone explain why I need this parameter in the main method in order for the program to execute correctly?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the ranch Don't worry, nobody's going to kill you here.

The main method is a very special method which defines an entry point to your program (in clear, it allows your class to be executed). Its signature is well defined : public, static, no return value, an array of String to hold command line parameters. Whether or not you're using the parameter, it must be declared that way.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's better explained here.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main method isn't a function; a function is supposed to return a result, and the result should be the same if the input is the same. If you look at the main method, it is marked void, so it doesn't return a result or anything. So it doesn't count as a function.

The JVM is programmed to look for a method headed public static void main(String[] args) and all but the very slightest changes to that will prevent it from identifying it. So you get complaints. Try it with public static void Main(String[] args) and see what sort of error message you get. The keyword public means it can be accessed from any code, the static means it can be accessed before any instance of the class is created, and void means it doesn't return anything. The String[] args bit means you can pass additional information to your program from the command line.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!