Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 136,167 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,892 people online right now. Registration is fast and FREE... Join Now!




A closer look at the main method

 
Reply to this topicStart new topic

> A closer look at the main method

Rating  5
Programmist
Group Icon



post 6 Dec, 2007 - 09:01 AM
Post #1


I've seen many beginner tutorials that give main method examples, but gloss over the details. That's understandable as it's probably confusing to a beginner. So, I'm here to fill in the blanks for those who want to know.

The Java main method looks like this:

public static void main(String args[])

We've all seen it I'm sure. As you can see it has three modifiers and one parameter, which is a string array. I will explain each, in detail where neccessary, below.

public - well, it has to be accessible outside the class, so it obviously has ot be public or Java cannot "see" it.

void - This means it returns no value. In C++ main can return an int value. This was usually used in unix systems to tell the thread that forked the process t hat is running the program, the exit status. Usually an exit status of 0 indicated normal termination. A non-zero exit status usually signified an abnormal termination with different integers corresponding to different "errors."

static - To understand why the main method must be static think about it this way. If a method is not marked static, then a class instance must be instantiated to call it. If it's static, you can call the method without instantiating an object.

CODE
public class SomeClass
{
  public int getInt() {return 0;}
  public static float getFloat() { return 1.0; }
}


Given this, I can call SomeClass.getFloat() directly, without creating a new instance of SomeClass. But, to call getInt() I must:

CODE
SomeClass c = new SomeClass();
c.getInt();


So, when Java looks for the entry point in a program (the main method), it must be able to call it without instantiating an object, hence the method must be static.

String args[] - This is used for command-line arguments. Say I have the following class:

CODE
public class Person
{
  private String firstName;
  private String lastName;

  public Person(String firstName, String lastName)
  {
     this.firstName= firstName;
     this.lastName= lastName;
  }

  public String toString()
  {
      System.out.printf("Hello.  My name is %s %s/n", firstName, lastName);
  }

  public static void main(String args[])
  {
     Person p = new Person(args[0], args[1]);
         p.toString();
  }
}


If I now execute this class from the command-line, as follows, java Person John Smith, then the strings "John" and "Smith" will be passed to main (in the args[] array) in the left-to-right order in which they were written. In other words args[0] == "John" and args[1] == "Smith". So the output of that should be, Hello. My name is John Smith.

As an extra aside, the main method of a class cal be called from another class. That's right. Java uses it as the entry point of a program, but it is still just a static method. So, from within another class I can do the following:

CODE
...
String myArgs = new String[] {"John", "Smith"};
Person.main(myArgs);
...


This is equivalent to the previous command-line execution, java Person John Smith, and should output the same thing: Hello. My name is John Smith. I've used this method of calling another program before, but at the moment I can't recall why. It can be useful for testing purposes, I suppose, although many IDE's provide a way to pass in command-line args.

Hopefully someone finds this useful. If you see any errors, please let me know. Thanks,
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Martyr2
Group Icon



post 6 Dec, 2007 - 09:13 AM
Post #2
Good job! Simple and straight to the point. I am sure many beginners have always wondered about that. Your explanations also offer a glimmer of light into other programming ideas including object instantiation, calling functions with parameters, and the idea behind static method calls.

smile.gif
Go to the top of the page
+Quote Post

bhandari
Group Icon



post 1 Feb, 2008 - 07:56 AM
Post #3
Some important facts
1) main method can be overloaded by providing a different argument list, but that overloaded method won't be called by JVM
2) you can't return any thing from main method , if you do, compiler has no problems but JVM has. The return type has to be void for the main version called by JVM
3) Only static member variables (primitives or object references) can be accessed by the main method as it itself is a static method. (Though you can always create an instance of the this class and then use the non-static members)

In a nutshell, JVM always looks for public static void main(String arg[]) as the starting method.
Go to the top of the page
+Quote Post

myra
*



post 27 Apr, 2008 - 04:12 AM
Post #4
Great tutorial icon_up.gif Keep it up biggrin.gif
Go to the top of the page
+Quote Post

herefishyfishy
Group Icon



post 6 May, 2008 - 01:16 PM
Post #5
QUOTE
String args[] - This is used for command-line arguments. Say I have the following class:

CODE
public class Person
{
  private String firstName;
  private String lastName;

  public Person(String firstName, String lastName)
  {
     this.firstName= firstName;
     this.lastName= lastName;
  }

  public String toString()
  {
      System.out.printf("Hello.  My name is %s %s/n", firstName, lastName);
  }

  public static void main(String args[])
  {
     Person p = new Person(args[0], args[1]);
         p.toString();
  }
}


If I now execute this class from the command-line, as follows, java Person John Smith, then the strings "John" and "Smith" will be passed to main (in the args[] array) in the left-to-right order in which they were written. In other words args[0] == "John" and args[1] == "Smith". So the output of that should be, Hello. My name is John Smith.


Why does the line say
CODE
p.toString();

rather than
CODE
System.out.print(p);
?
p.toString(); doesn't really do anything.

Anyways, great tutorial otherwise.
Go to the top of the page
+Quote Post

Ellie
Group Icon



post 8 May, 2008 - 02:44 AM
Post #6
QUOTE(herefishyfishy @ 6 May, 2008 - 10:16 PM) *


Why does the line say
CODE
p.toString();

rather than
CODE
System.out.print(p);
?
p.toString(); doesn't really do anything.

Anyways, great tutorial otherwise.


It says that because Programmist has overridden the toString method such that is does print the string.

QUOTE
public String toString()
{
System.out.printf("Hello. My name is %s %s/n", firstName, lastName);
}


icon_up.gif
Go to the top of the page
+Quote Post

dreamerGon
*



post 26 May, 2008 - 02:18 AM
Post #7
QUOTE
public String toString()
{
System.out.printf("Hello. My name is %s %s/n", firstName, lastName);
}


I don't think that toString method will work since it has a return type "String" and is not returning anything. However, that's pretty irrelevant to the main point.

This post has been edited by dreamerGon: 26 May, 2008 - 02:19 AM
Go to the top of the page
+Quote Post

1lacca
Group Icon



post 26 May, 2008 - 03:15 AM
Post #8
That will probably result in a compilation error (missing return statement).
Go to the top of the page
+Quote Post

herefishyfishy
Group Icon



post 29 May, 2008 - 04:22 PM
Post #9
Oh, I didn't notice that.
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/2/08 12:10AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month