Why should i write main(String[] args)?

Hello,
I don't know why i am obliged in the main function of the class to send an array of string as parameters?
Thanks

Actually I think this is a great question!
main()
Any java application has to have a main method to do anything, but as you gain further into java and object orientated practices you will start writing lots of stuff that do NOT have a main method but are *.java and *.class files, neither will they do anything unless they are attached to a program with a main. Andthen as you get DEEPER still you might even have 'private synchronised void main(String[] args)' - though not too often.
Why an array of strings? Hmmm ...pauses ...thinks, there is no obvious reason, other than the fact that if you're going to pass parameters from 'java ...' command line to the application. This is, logically, the most potentially useful data type to have. There may well be other reasons for this, so the answer to the second part of your question is a logical deduction - it may not be right.

Similar Messages

  • Why can't created an object in the "public static void main(String args[])"

    Example:
    public Class Exp {
    public static void main(String args[])
    new Exp2();-------------> To Occur Error
    Class Exp2 {
    public Exp2()

    You can't create an inner class within main, because
    it is a static method. Inner classes can only be
    created by true class methods.This is not correct. You can create an inner class object in a static method. You just have to specify an outer class object that the inner class object should be created within:
    Exp2 exp2 = new Exp().new Exp2();

  • How to call java with public static void main(String[] args) throws by jsp?

    how do i call this from jsp? <%spServicelnd temp = new spServicelnd();%> does not work because the program has a main. can i make another 2nd.java to call this spServiceInd.java then call 2nd.java by jsp? if yes, how??? The code is found below...
    import java.net.MalformedURLException;
    import java.io.IOException;
    import com.openwave.wappush.*;
    public class spServiceInd
         private final static String ppgAddress = "http://devgate2.openwave.com:9002/pap";
         private final static String[] clientAddress = {"1089478279-49372_devgate2.openwave.com/[email protected]"};
    //     private final static String[] clientAddress = {"+639209063665/[email protected]"};
         private final static String SvcIndURI = "http://devgate2.openwave.com/cgi-bin/mailbox.cgi";
         private static void printResults(PushResponse pushResponse) throws WapPushException, MalformedURLException, IOException
              System.out.println("hello cze, I'm inside printResult");
              //Read the response to find out if the Push Submission succeded.
              //1001 = "Accepted for processing"
              if (pushResponse.getResultCode() == 1001)
                   try
                        String pushID = pushResponse.getPushID();
                        SimplePush sp = new SimplePush(new java.net.URL(ppgAddress), "SampleApp", "/sampleapp");
                        StatusQueryResponse queryResponse = sp.queryStatus(pushID, null);
                        StatusQueryResult queryResult = queryResponse.getResult(0);
                        System.out.println("Message status: " + queryResult.getMessageState());
                   catch (WapPushException exception)
                        System.out.println("*** ERROR - WapPushException (" + exception.getMessage() + ")");
                   catch (MalformedURLException exception)
                        System.out.println("*** ERROR - MalformedURLException (" + exception.getMessage() + ")");
                   catch (IOException exception)
                        System.out.println("*** ERROR - IOException (" + exception.getMessage() + ")");
              else
                   System.out.println("Message failed");
                   System.out.println(pushResponse.getResultCode());
         }//printResults
         public void SubmitMsg() throws WapPushException, IOException
              System.out.println("hello cze, I'm inside SubmitMsg");          
              try
                   System.out.println("hello cze, I'm inside SubmitMsg (inside Try)");                         
                   //Instantiate a SimplePush object passing in the PPG URL,
                   //product name, and PushID suffix, which ensures that the
                   //PushID is unique.
                   SimplePush sp = new SimplePush(new java.net.URL(ppgAddress), "SampleApp", "/sampleapp");
                   //Send the Service Indication.
                   PushResponse response = sp.pushServiceIndication(clientAddress, "You have a pending Report/Request. Please logIn to IRMS", SvcIndURI, ServiceIndicationAction.signalHigh);
                   //Print the response from the PPG.
                   printResults(response);
              }//try
              catch (WapPushException exception)
                   System.out.println("*** ERROR - WapPushException (" + exception.getMessage() + ")");
              catch (IOException exception)
                   System.out.println("*** ERROR - IOException (" + exception.getMessage() + ")");
         }//SubmitMsg()
         public static void main(String[] args) throws WapPushException, IOException
              System.out.println("hello cze, I'm inside main");
              spServiceInd spsi = new spServiceInd();
              spsi.SubmitMsg();
         }//main
    }//class spServiceInd

    In general, classes with main method should be called from command prompt (that's the reason for main method). Remove the main method, put the class in a package and import the apckage in your jsp (java classes should not be in the location as jsps).
    When you import the package in jsp, then you can instantiate the class and use any of it's methods or call the statis methods directly:
    <%
    spServiceInd spsi = new spServiceInd();
    spsi.SubmitMsg();
    %>

  • What happens when main(String[] args)

    Hi techies,
    I am trying to understand, "how the JVM invokes public static void main(String[] args)".
    I had gone through JVM tutorial, and found that there are 2 different types of classloaders 1. bootstrap loader 2. user defined class loader.
    I had gone through java api for class loader class. i did not find the method main(String[] args).
    I am having confusion whether bootstrap loader calls main(String[] args)(or) userdefined classloader calles main(String[] args).
    Why do we have to give String[] args as argument to main??
    can you guys guide to understand this .
    regards,
    Krishna

    Hi techies,
    I am trying to understand, "how the JVM
    invokes public static void main(String[] args)".
    I had gone through JVM tutorial, and
    found that there are 2 different types of
    classloaders 1. bootstrap loader 2. user defined
    class loader.
    I had gone through java api for class
    loader class. i did not find the method
    main(String[] args).
    I am having confusion whether bootstrap
    loader calls main(String[] args)(or) userdefined
    classloader calles main(String[] args).
    Why do we have to give String[] args as
    argument to main??
    can you guys guide to understand this
    regards,
    Krishnawell, you won't find main(String[] args) in the docs for ClassLoader, since it's not a method on ClassLoader!
    the bootstrap loader loads, verifies, prepares and initializes the class for which you pass the fully.qualified.name into the JVM, and looks for the static method on that class called 'main' which has a single argument, an array of Strings, and no return type ( I'm not 100% sure of that last part actually - I'll try it ) and begins a thread of execution on that method. from there, your program is run
    we have to give an array of Strings in order to pass arguments into the program
    it can't be a user-defined classloader that does this, because most of the time there won't be a user-defined classloader!

  • Why should still we use String though we have StringBuffer?

    I hope StringBuffer is best instead of String. Since StringBuffer grows itselfs when the content increases with out creating new object .
    So now I have a question, Why should still we use String though we have StringBuffer? whether do you any proper reason or situation to go for String ?

    I hope StringBuffer is best instead of String.StrngBuilder is better than StringBuffer in Java 5.0. Both are different from Strings.
    Since
    StringBuffer grows itselfs when the content increases
    with out creating new object .Which is not necessarily a good thing. Strings can be relied upon not to change
    So now I have a question, Why should still we use
    String though we have StringBuffer? whether do you
    any proper reason or situation to go for String ?One reason: you can't intern StringBuffers and thus save on instantiation effort and emory space. You can do that with Strings because they cannot be modified.

  • Can't find file when use the main(String[] args) method

    I put a file under the DefaultDomain directory of Weblogic 11.1.1.5 on my local machine. Below is how I look up this file
    FileInputStream fis = new FileInputStream("input.xml");
    I started up the IntegratedWeblogicServer instance and I tested using the below 2 approaches.
    1) When I test a web service program using the below approach, it CAN'T find the input.xml file
    public static void main(String[] args)
    2) When I package it into an EAR file and deploy it onto the server then log into the admin console and use the test client approach then it's able to find the file
    How do I make it so it can find the file using #1 approach?
    Thanks

    That's how relative paths work, and it's nothing particular to Java.
    When you type ls input.xml or dir input.xml does it list the file, or give an error? If it lists the file, then it's in your current directory, and it will work if you run Java from that directory. If it gives an error, then that file is not in your current working directory, and Java won't be able to find it either.

  • When does the Java main(String args[]) method exit?

    Hi all,
    I and my colleagues want to know, when does the main() method exit?
    we wrote a small code as follows:
    import java.awt.*;
    public class Test {
    public static void main(String[] args) {
    Frame f = new Frame("hi");
    f.show();
    System.out.println("after show");
    and ran the program, in which case I could see the printed message "after show", but although there is no code after the System.out.println(), the Java virtual machine does not exit and waits for the Frame to close.
    My question is has the main method exited in this case? since it clearly shows that it does not have any more code to execute. Does java create the main method as a thread or as a process?
    regards,
    Harshad

    To make your application terminate you need to add code to cause the AWT thread to handle the termination. In your code, before f.show(), try:
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        dispose();
      public void windowClosed(WindowEvent e) {
        System.exit(0);
    });Now, at least you can click on the little "X" on the upper right-hand corner of the Frame (at least in Win95/98/NT) environments) to cause your application to receive a window closing event. It is also possible to add a menu with an option to exit; in that case I'd use an EventQueue to cause a window closing event to be sent.

  • Static main(String args[]) access modifiers possible

    main(String args[]) can have private as access modifier?

    hi,
    yes of course this is possible, because main is at the end only a method like each other. But you have to know, that you cannot use this method from outside. so no application will start, if the main() of the Main-class has a private as modifier.
    You can use this class as an applet.
    So be carefull doing this
    regards

  • Standard input - main(String[] args) -- how?

    In eclipse, how do I feed the main with values?
    public static void main(String[] args) {
           System.out.println("Enter value: ");
           args =
        if (args.length != 1) {
    ...Thanks,
    george

    You mean basically command line arguments?
    Look in the run menu. For every run event there's a form that specifies how to invoke the program. Somewhere in there you can specifiy the command line arguments. I can't recall right now but I can look it up if you can't find it.
    Standard input is a completely different thing from command line arguments. Standard input, from the java point of view, is what comes in on System.in.

  • Main(String args[]) cannot be overload ? True or False

    main(String args[]) cannot be overload ? True or False

    Although you can do this....
    public class a
        public static void main(String[] args)
            System.out.println("Hello World - a!");
    public class b extends a
        public static void main(String[] args)
            System.out.println("Hello World - b!");
    }(I'm not sure if that is relevant to your actual question.... but then again your question isn't spot on either! ;-)

  • Private static void main(String args[]) ... ?????

    even if the main method is declared
    private static void main(String args[])
    //Code Here
    it works fine..can somebody explain the reason behind?

    hi rkippen
    so u mean, since the JVM is calling the main it can
    break all kinds of access specifiers to any class..am
    i right?
    This could be the case.
    However, I tried using 1.4.1 with no development environment (just java.exe) and it gave the following error:
    C:\>java MainTest
    Main method not public.
    So, your development environment might be the cause (e.g. what you use to program your code (e.x. JBuilder)), or the Java version.
    Your development environment might be using reflection to get around Java accessibility checks. For debugging purposes, it is possible to use reflection to obtain refereneces to private methods/fields and invoke those methods and access those fields.
    E.g.
    Vector v = new Vector();
    Field f = v.getClass().getDeclaredField("elementCount");
    f.setAccessible(true); // this is the trick
    f.set(v, new Integer(100));In the presence of a security manager, the setAccessible method will fire a "suppressAccessChecks" permission check.

  • Main(String[] args) ...

    I understand that args are passed when executing the program, but how exactly does it separate arguments?
    Say I type: (for WinXP)
    start myprogram.jar 123 -n -k
    does it separate the "arguments" according to spaces? or does every character get its own String in the args array?

    I am not at my computer, and this one does not have the JDK installed on it so I couldnt test it myself and I didnt feel like waiting until I got back to my house, im impatient =)
    But thank you for your response!

  • Detect shift key in main(String[] args)

    Hello all,
    I am trying to detect if the user is pressing the shift key while my application is starting.
    I tried
    Toolkit.getDefaultToolkit().addAWTEventListener(globalEventListener, AWTEvent.KEY_EVENT_MASK);
    But it doesn't seem to detect the shift key.
    Any help on this?

    I don't think you can do it Java; the problem is that GUI never gets an event
    from which it can check the modifiers. I thought maybe you could get around
    this with a Robot creating an event, but with the Shift key down, it never gets
    delivered (though with no keys pressed, it does). You might be able to do this
    using some JNI, though, but of course, that will be platform specific.
    Why not just make the admin functionality available off a menu item or
    something like that?

  • Why is the problem? String Manipulation. Help Please.

    Ok I have two while loops that run with two different String arrays. The problem that I have is that I have a String LeadPI that looks like this: "Dr. Ayusman Sen, Pennsylvania State University".
    I would like to separate the String where the first half "Dr. Ayusman Sen" = String investigator; and "Pennsylvania State University" = String institution;
    basically separate the string into two separate String variables.
    can I do this in 1 while loop, and why is my output not functioning correctly?
    Lead PI: Dr. Ayusman Sen, Pennsylvania State University //*** String to manipulate***//
    // what the output should look like.
    Institution: Pennsylvania State University //*** this should be institution ***//
    Investigator: Dr. Ayusman Sen //*** this should be investigator ***//
    // This is the current output!
    Institution: Dr. Ayusman Sen
    Institution: Pennsylvania State University //*** this should be institution ***//
    Investigator: Dr. Ayusman Sen //*** this should be investigator. ***//
    Investigator: Pennsylvania State University
    Investigator: Dr. Ayusman Sen
    Investigator: Pennsylvania State University            
                 //********************** institution **************************//
                int count= 0;
                char separator =',';
                int index =0;
                do
                   ++count;
                   ++index;
                   index = LeadPI.indexOf(separator, index);
                while (index != -1);                       
                String[] insti = new String[count];
                index=0;
                int endIndex = 0;
                for(int i = 0; i < count; i++)
                    endIndex = LeadPI.indexOf(separator, index);
                    if(endIndex == -1)
                        insti= LeadPI.substring(index);
    else
    insti[i] = LeadPI.substring(index, endIndex);
    index = endIndex + 1;
    for(int i = 0; i < insti.length; i++)
    System.out.println("\tInvestigator: "+insti[i]);
    //********************** investigator **************************//
    index =0;
    do
    ++count;
    ++index;
    index = LeadPI.indexOf(separator, index);
    while (index != -1);
    String[] investi = new String[count];
    index=0;
    endIndex = 0;
    for(int i = 0; i < count; i++)
    endIndex = LeadPI.indexOf(separator, index);
    if(endIndex == -1)
    investi[i]= LeadPI.substring(index);
    else
    investi[i] = LeadPI.substring(index, endIndex);
    index = endIndex + 1;
    for(int i = 0; i < investi.length; i++)
    System.out.println("\tInstitution: "+investi[i]);

    Cheers!
    One of the problems with the String's split method is that it will nto handle the spaces properly. You will still need to trim it.
    In the class, below, I have coded for you two methods that will do what you are asking for.
    The first method (split) uses the String's split method, but then has to go through and trim down the strings to remove the space after the comma.
    The second method, tokenize, does the same thing, but uses a string tokenizer.
    Both work - I was just trying to illustrate both methods. The tokenizer method is about three times faster than the split method (in my tests) - but the split method is a little cleaner (IMHO) - but we're talking sub-millisecond differences in one execution.
    You would get the name from the [0] index of the returned String array and the institution from the [1] index, like so:
    System.out.println( "Name: " + info[ 0 ] );
    System.out.println( "Institution: " + info[ 1 ] );There are some issues with this code... if there is a comma in the institution name or the person's name, if messes things up - if, for example, the persons' name is "Paul Leska, Jr." - the routine splits the string in between Leska and Jr.
    The same thing happens in the institution name - if, for example, the name of the place is "University of Minnesota, Duluth" - we tokenize or split between Minnesota and Duluth.
    You'll either need to (1) watch your data, (2) make these routines smarter or (3) Change your input to already be split (from the source, perhaps).
    Here's the code:
    import java.util.StringTokenizer;
    public class Splitter {
      public static String[] split( String s, char c ) {
        String[] chopped = s.split(String.valueOf( c ));
        for( int idx = 0; idx < chopped.length; idx++ ) {
          chopped[ idx ] = chopped[ idx ].trim();
        return chopped;
      public static String[] tokenize( String s, char c ) {
        StringTokenizer st = new StringTokenizer( s, String.valueOf( c ) );
        int count = st.countTokens();
        String[] chopped = new String[ count ];
        for( int idx = 0; idx < count; idx++ ) {
          chopped[ idx ] = st.nextToken().trim();
        return chopped;
      public static void main( String[] args ) {
        String[] info = tokenize( "Michael A. Riecken, Jumping Mouse Software", ',' );
        for( int idx = 0; idx < info.length; idx++ ) {
          System.out.println( info[idx] );
        info = split( "Michael A. Riecken, Jumping Mouse Software", ',' );
        for( int idx = 0; idx < info.length; idx++ ) {
          System.out.println( info[idx] );
    }

  • Should we use main method in JCO

    1/
    Should we use main method in JCO.. Connections does not seem to be simple java programes... so why should we use them??? just for the sake of running the programme?
    2/ And the below mentiond programme.. there is nothing called Connect1. Still the that class is created ..
    do not you thik it has to be <b>TutorialConnect1</b> object and constructor,
    import com.sap.mw.jco.*;
    public class TutorialConnect1 extends Object {
       JCO.Client mConnection;
       public Connect1() {
         try {
           // Change the logon information to your own system/user
           mConnection =
              JCO.createClient("001", // SAP client
                "<userid>", // userid
                "****", // password
                null, // language
                "<hostname>", // application server host name
                "00"); // system number
           mConnection.connect();
           System.out.println(mConnection.getAttributes());
           mConnection.disconnect();
        catch (Exception ex) {
          ex.printStackTrace();
          System.exit(1);
      public static void main (String args[]) {
        Connect1 app = new Connect1();

    Hi
    The main method is used in the learning stages to know how the program is executing.In real time scenarios we do not use the main method.If you use a main method it is just like a stand alone program to know the basics.
    In your program the class name and constructor name is different
    Make sure both are same or otherwise create an object with default constructor given by jvm and then call a method
    Thanks
    kalyan

Maybe you are looking for

  • Best way to set-up U Verse, Time Capsule and Express to Extend Network

    I'm trying to extend my WIFI signal with AP Express and TC using an AT&T U Verse router. Neither the Express nor the TC are directly connected to the U Verse router. Both the Express and the TC show they are connected to the network but when I try an

  • Slow SQL Apply on Logical Standby Database in Oracle10g

    Hi, We are using Oracle 10g Logical Standby database in our production farm but whenever there is bulk data load (5-6 GB data) on the primary database, the logical standby seems to be hung. It takes days to apply the 5-6 GB data on the logical standb

  • Number disclosure

    Hello, I would like to register my skype Finland number for disclosure. That if I am going to call my customer then he sees my finland number, which is actually bought from skype and I am calling from estonia trough skype. When I try to confirm my nu

  • Officejet 4500

    I got a new wireless router and set up network with different name and pass phrase.  How do I reconnect the officejet 4500 to the new wireless network?  Under settings network setup up I only can reset network then use automatic or manual.  Nowhere c

  • Reinstalling Aperture 3

    I have been using Aperture 3 for about a week now with no issues. I formatted my drive last night and I reinstall Aperture 3. I then used time machine to restore the pictures folder that contains all my pictures and the Aperture 3 library. When I ope