Solved

Why should be declared as static in main?

Posted on 2002-06-25
9
271 Views
Last Modified: 2010-03-31
In java (standalone) pgm must have one main function.
the line should be
public static void main(String a[]){}
why should pu static in main()? what is the advantage adn what is the reason?
..
thanking you experts
0
Comment
Question by:anmadhu
9 Comments
 
LVL 9

Accepted Solution

by:
Venci75 earned 100 total points
ID: 7106702
because the static methods/variables are global. To execute this method you don't need to have an instance of the class, containing the main() method
0
 
LVL 4

Expert Comment

by:Neutron
ID: 7107664
The designer of the Java-Application concept probably had the following alternatives:

- to have a standard constructor for Java-Application, something like:

class MyClass
{
    public MyClass( String[] args )
    {
    }
}

- or to have a parameterless constructor and some init method:

class MyClass
{
    public MyClass()
    {
    }

    public void init( String[] args )
    {
    }
}

- it seems that the best option is the chosen one, because JVM doesn't need an instance of your 'main' class in order to run it, so you can decide whether you will create an instance or not.

This info is for free :-)

Greetings,
    </ntr> :)
0
 
LVL 3

Expert Comment

by:daitt
ID: 7107831
main method is the starting point of a java program. When you execute a java program, you execute something like this:
java MyClass
JVM will invoke MyClass.main(param)

In order to let JVM do so, main method must be:
1. Public, so that it can be invoked from ourside of the package, for example, if your MyClass is in packet com.myjava.example, JVM still can invoke it.
2. Static, so that JVM doesn't need to create an instance of MyClass. To create an instance, usually JVM must call the constructor of that class, but it doesn't know which parameter to pass to the constructor. So JVM cannot create an instance of MyClass and then call the starting function. So main must be static (can be called alone).
hope this helps
0
 
LVL 3

Expert Comment

by:mjzalewski
ID: 7109372
A good pattern to use when writing a Java application is to have the public static main() method create an instance of the object, then run one or more methods. The main() method just checks the arguments, such as if the correct number of arguments are present.

For example, let's say I make a Java class that copies a file. I decide that the application should take two arguments, one as a source and one as a destination.

public class Copy {
  // This method does the actual work of the application
  public void copy( String source, String destination)
      throws IOException {
    ...
  }
  public static main( String[] args) {
    // First check that the right number of arguments were given
    if( args.length != 2) {
      System.err.println( "Usage: " + class.getName() + " source destination);
      System.exit( 1);
    }

    // Now make an object to perform the copy.
    Copy myCopyApplication = new Copy();
    myCopyApplication.copy( args[ 1], args[ 2]);
  }
}

This code won't quite compile because I didnt put all the exception catching (and because I typed it out of my head without ever compiling it).

But if you do it this way, you now have a reusable copy class that can be used from other classes. Another object which needs to copy things can just do

    Copy myCopyHelper = new Copy();
    myCopyHelper.copy( source, destination);
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Expert Comment

by:rhariss
ID: 7109640
Hi
   we can directly access the object without creating an instance and it contain global variables.
 
 
0
 
LVL 1

Expert Comment

by:saurav17
ID: 7109797


Many of these comments have the answers themselves.
But still i would like to explain u in detail.

Java is designed in a way thatall standalone programs nedd to be started at one point (means to be loaded to the memory).
to run a program we say java <program Name>. we have not created the instance or ur javafile yet. then with what referrence the JVM will load the program to memmory. To Acces a variablw we need its claas object which will be created only if it is instantiated. So, we mark main() as static, saying it can be accessed directly with the program name.
i.e.,  our JVM will locate the main method with the program name supplied by us in this manner:

      <programName>.main();
if no main method is found in ur class, it will throw u no defn found error.

so, all the variables, that u want to access before instantiating the class, can be marked as static and it can be accessed by u with its program name like this:

    <programName>.<variable>;
one good example for static is singleton class.
where u will have static variable holding ur classobject. u will acess it with classname, it will return theclassobject to u, inorder to maintain the single version object of that class throught out ur program.

I'm typing this message in a hurry. So, if there are any mistakes pls., ignore it.

Regards,
K.J.S.
0
 

Expert Comment

by:sudhir_13
ID: 7139629
hia friend ,

   before telling the answer . i would like to teel one thing that java is a pure object oriented language . we call a pure oops if every thing is included in the class .
so we have the main function inside the class . but it should be the only one for all the objects so we be keeping as a static so that only one copy is maintained for all the objects .it made public so that it can accessed out side the class

 hope you got the answer .
bye
sudhir(MSIS)
0
 
LVL 5

Expert Comment

by:vemul
ID: 7888002
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- points to Venci75

All experts have replied with the correct comments, hence I am requesting it to be awarded to the one who answered first

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

vemul
Cleanup Volunteer
0
 
LVL 1

Expert Comment

by:Computer101
ID: 7959667
Comment from expert accepted as answer

Computer101
E-E Admin
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now