Sending varargs via command line arguments to main()

When I put A B C D in the command line arguments textbox in my compiler, the output is as expected: A B C D. However, when I put *new String[]{A, B, C, D}*, the output is *new String[]{A, B, C, D}*, not A B C D as I had expected. My code is below. Any suggestions?
package varargs;
public class Varargs {
    static void printArray(Object...args){
        for (Object obj : args)
            System.out.print(obj + " ");
        System.out.println();
    public static void main(String...args) {
        printArray((Object[])args);
}

The argument(s) that is/are supplied to your main method will be rendered as literal String constants. It looks like you are attempting to use java code as one of your arguments with the expectation that the program will interpret this code. It won't. Your program will simply display whatever it is given even if what you offer as an argument happens to be a construct of the Java language.

Similar Messages

  • Changing the override file via command line arguments

    Is there a way to change name of the file Coherence uses to override coherence-config.xml via a command line argument? I'd like to specify different override filenames in different environments.

    I get the message that:
    2006-02-13 16:53:27.699 Tangosol Coherence 3.0.1/317 <D5> (thread=main, member=n/a): Optional configuration file "/home/noah/tools/tangosol-config/tangosol-coherence-override-dev.xml" is not specified
    I specified the following as the startup:
    java -Dtangosol.coherence.override=/home/noah/tools/tangosol-config/tangosol-coherence-override-dev.xml -Dtangosol.coherence.log.level=5 -classpath /home/ncohen/tools/tangosol-config:/home/noah/tools/tangosol/lib/coherence.jar com.tangosol.net.CacheFactory
    Where the tangosol-config directory contains my override file tangosol-coherence-override-dev.xml
    If I change the name of the override file solely in the cmd prompt, it doesn't find any of them. It just gives me the optional configuration file ..... is not specified. How does one go about fixing this? Thx.
    Message was edited by:
    noah

  • Sending Command Line Arguments to Jar Executable

    Hi All
    I wish to send Command Line Arguments to Jar Executable.
    i.e. before I Jar'd my program, I would do the following
    public class CmdLnArgmntExp {
    public static void main(String[] args) {
    System.out.println("d");
    for (int i = 0; i < args.length; i++)
    System.out.println(args);
    Running the program in Console.
    Java CmdLnArgmntExp arg1 arg2 arg3 arg4Output:
    arg1
    arg2
    arg3
    arg4
    How would I do this to a Jar executable, hope that made sense
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    java -jar executable-jar-file-containing-class-CmdLnArgmntExp.jar arg1 arg2 arg3 arg4

  • How to hide the command line arguments from solaris process

    Hi All,
    When I execute a JAR application from a java file using the Runtime.getRuntime, the command line arguments (user ID and Password details) which I passed for executing the application displayed on Solaris process (ps -ef).
    Could anybody please help me, how can I hide either the process or the command line arguments from the Solaris process?
    I cannot pass any asterix or any special character in place of password, because the executing application doesn't have any functionality to retreive the password which send as asterix characters.
    Please help me
    SumodeV

    Thanks for all the response.
    I have created a design and implement the functionality which executes the JAR application in Solaris environment without showing any details in the process details.
    I have used the Java Reflection method, which invokes the JAR application. I am sharing the details here for all those who looking for it.
    1, Inside the Customer application [Jar File is running for it], collect the necessary session details [Using System.get property method]
    2, Create an independent Java file, which should be used to invoke the JAR application
    3, Create the ProcessBuilder object and use a command - execute the Java file [a wrapper code] using normal Java command
    4, Pass the necessary session details to the ProcessBuilder using the environment() function.
    5. Collect the environment values in the independent Java file (Which was invoked by ProcessBuilder) and set details for its environment using System.setProperty.
    6, Use reflection technique to invoke the JAR plugin [which you want to run]. You can use the standard Java functionality to read the MANIFEST file of JAR and load the main class using URLClassLoader.
    7, Invoke the main method of the JAR file, which run the JAR application in Solaris window
    This solution will make sure that the process cannot display any session details in the Solaris Environment.
    Note: Use String[] array while create the command. Otherwise the JAR application cannot pop-up.
    Regards
    Sumode

  • Command Line argument is not valid please verify the switch.......???

    hello frends
    We are currently getting this error.
    Command Line argument is not valid please verify the switch.
    The code used to send the mail is
    mail ="mailto:?subject="+escape(subject)+"&body="+escape(email);
    document.location = mail;
    return ;
    this is a javascript code to open outlook mail to send emails.
    the main problem is,when we write
    mailto:?subject=abc&body=uvwxyz......
    then we should be getting abc as subj and uvwxyz as the body..,and we r getting it....
    but when we include ""(double quotes ) in either the subject or the body..,it is showing the error line mentioned above.
    and if em using the html tags in the body part..,it's giving everything including the tags,which z not desired.
    kindly help me .....

    shikha6g wrote:
    i've thought..,you people are brainy enough to help me out in the javascript too...!!so..,i relied on this forum and have posted my problem,coz solving this thing was really imp for me.
    i din't knew,dat i'll get such circastic replys here.sorryTo me, being brainy implies that you are a smart thinker and good at problem solving. It doesn't mean that you know a language that you never learned.

  • Prevent Startup Form from Loading using Command Line Arguments

    Hi there
    I'm developing a VB.NET windows forms application in VS2013.
    The application will have 2 ways of being executed, one being by the user manually and the other being automated by the task scheduler.
    When executed by the task scheduler, command line arguments will be used so that the application is aware that it is being run automatically and not by a user.
    My problem is that I want the startup form to load when run by a user but I don't want it to load when it is run automatically, I just want to execute code.
    Is it possible to prevent the startup form from loading by using the commandline arguments from the MyApplication_Startup event?
    Cheers

    Hi Aureuz,
    >>Is it possible to prevent the startup form from loading by using the commandline arguments from the MyApplication_Startup event
    It is impossible to accomplish it in the MyApplication_Startup event, we can use Form.Shown event:
    #Form.Shown Event
    http://msdn.microsoft.com/en-us/library/system.windows.forms.form.shown(v=vs.110).aspx
    If we start a form by using the commandline arguments, the count of CommandLineArgs will be above one, if so, use Me.Hide() method to hide this form.
    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
    Dim args As String() = Environment.GetCommandLineArgs()
    If args.Count > 1 Then
    Me.Hide()
    Else
    Me.Show()
    End If
    End Sub
    You can also uncheck "Enable application framework" on the project properties application tab and select your startup object to a module object:
    Module Module1
    Sub Main()
    Dim args As String() = Environment.GetCommandLineArgs()
    If args.Count > 1 Then
    'Run your background code
    Else
    Dim f As New Form1
    f.ShowDialog()
    End If
    End Sub
    End Module
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Help with char and command line arguments

    I am writing a program that takes 2 command line arguments (such as 4 b, or 3 4, etc.). It uses the first argument to determine the height of a triangle (how many rows high), and the second is the character with which the triangle is drawn.
    My problem is I tend to code backwards - go for the bigger part and then figure out the smaller things. So, I've written a program that prints out this triangle, BUT I can't figure out how to get the command line arguments into it properly. A number works fine because I can:
    size = Integer.parseInt(args[0]);
    but what do I do if the second argument is a character? Args is a String array (I've been fighting with it for the past 4 hours, so I KNOW its a String array) - so how can I get a char to be read as args[1]?
    Here is my code before adding in the second argument (the char):
    public class Triangle
    public static final void main(String[] args)
    int size;
    if (args.length > 0)
    try
    size = Integer.parseInt(args[0]);
    catch(NumberFormatException e)
    System.out.println("Input Error");
    createFilledTriangle(size);
    System.out.println();
    public static void createFilledTriangle(int size)
    int i = 0;
    int j = 0;
    for(i = size, j = 1; i > 0; i--, j +=2)
    printChar(" ", i);
    printChar("*", j); <-----Instead of using * I want to use the second command line arg
    System.out.println();
    private static void printChar(String str, int total)
    for(int i = 0, i < total; i++)
    if(i%2 == 1)
    System.out.print(str);
    else
    System.out.print(" ");
    Thank you for any help in advance!

    I was sure i send it the other day, i probably send it to the wron guy.
    This will give you more idea about drawing.
    import java.awt.*;
    import java.awt.event.*;
    public class Args extends Frame
         Panel panel = new Tpan();
         int   arg1;
         char  arg2;
    public Args(int a1, char a2) 
         super();
         arg1 = a1;
         arg2 = a2;
         setBounds(1,1,600,400);     
         setLayout(new BorderLayout());
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         add("Center",panel);
         setVisible(true);     
    public class Tpan extends Panel
    public Tpan()
    public void paint(Graphics g)
         super.paint(g);
         g.setColor(Color.blue);
         g.drawLine(120,110-arg1,80,110);
         g.drawLine(120,110-arg1,160,110);
         g.drawLine(80,110,160,110);
         g.setColor(Color.red);
         g.drawLine(120,110-arg1,120,110);
         g.setColor(Color.black);
         g.drawString(""+arg2,116,110-arg1/2+10);
    public static void main (String[] args) throws InterruptedException
    // get the 2 arguments from the args insread of a1= , a2=
         int  a1  = 60;
         char a2 = 'a';
         new Args(a1,a2);
    Noah
    import java.awt.*;
    import java.awt.event.*;
    public class Args extends Frame
         Panel panel = new Tpan();
         int arg1;
         char arg2;
    public Args(int a1, char a2)
         super();
         arg1 = a1;
         arg2 = a2;
         setBounds(1,1,600,400);     
         setLayout(new BorderLayout());
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         add("Center",panel);
         setVisible(true);     
    public class Tpan extends Panel
    public Tpan()
    public void paint(Graphics g)
         super.paint(g);
         g.setColor(Color.blue);
         g.drawLine(120,110-arg1,80,110);
         g.drawLine(120,110-arg1,160,110);
         g.drawLine(80,110,160,110);
         g.setColor(Color.red);
         g.drawLine(120,110-arg1,120,110);
         g.setColor(Color.black);
         g.drawString(""+arg2,116,110-arg1/2+10);
    public static void main (String[] args) throws InterruptedException
    // get the 2 arguments from the args insread of a1= , a2=
         int a1 = 60;
         char a2 = 'a';
         new Args(a1,a2);

  • Using Command Line Arguments with JAVA

    Hi,
    we are using an app called ImageMagick to scale and modify images before they are uploaded to a webserver.
    ImageMagick is called from our Objectiv-C app via
    command line.
    is there a way to this in Java?
    Regards
    Eckbert

    So, ur question is not developing a Java application that
    will do the 'image conversion'; but, your message
    conveys that u want to know how to invoke a Java program built by 'imagemagick' that takes command line arguments?
    Am I right?
    If that's the case, u must look into the documentation
    given along with the download'ed piece of software
    for identifying the 'starting point of the program'. i.e., the
    class that contains the 'main' method! And after you
    identify that class [Eg. ImageMagickStart] then you'll
    have to invoke as follows:
    [you must have Java installed in ur system!]
    c:>java ImageMagickStart
    If the program was written intelligently it must print all
    the command-line arguments required by the above
    program by executing the above command, and from that
    you can identify!
    -RK

  • Need Help with command line arguments for a class method

    Hey guys,
    I'm fairly new to programming in java.
    I want to a write a class method that adds up its command line arguments which are numbers. For example, if the input was .... 5 2 3....then the output would be 10.
    I have been told to use the Convert to convert a string to a double. I'm ok for writing the class method but I have no idea how to use Convert and why I need it in the method.
    Can anybody help please?

    Hey guys,
    I'm fairly new to programming in java.
    I want to a write a class method that adds up its
    command line arguments which are numbers. For
    example, if the input was .... 5 2 3....then the
    output would be 10.Okay. So you would receive the numbers to add as the String[] argument to a main method. The steps are simple:
    1) declare a variable for the count
    2) for each String in the array:
    2.1) extract the value as a double
    2.2) add this to the count
    3) output the resulting count
    I have been told to use the Convert to convert a
    string to a double.
    I'm ok for writing the class
    method but I have no idea how to use ConvertThere is no class Convert in the Java API.
    and why
    I need it in the method. Do you understand you need to somehow convert each String to a double (step 2.1)? Since Convert is unknown to me, maybe you should just take a look at class Double. It can help you do step 2.1, the rest should be trivial enough.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html
    Give it a go and feel free to post back with a specific problem you are having, accurately described if you please :-)

  • How to run command line argument programe

    Hi guys, I am doing pass command line argument programe in java but I don't know how to run this programe. Path for this programe in my my computer is C:\Users\Desktop\Mainjava\mycode\CommandProgjava*
    {code/}
    public class CommandProg
    public static void main(String[] args)
    System.out.println("d");
    for (int i = 0; i < args.length; i++)
    System.out.println(args);
    {code/}
    Where i need to go and what command i need to give so i can execute this programe(I am using window vista). I only know i have to give
    this command some where CommandProg arg1 arg2 arg3 arg4. Output should be
    Output:
    arg1
    arg2
    arg3
    arg4
    Please help me, Thanks in advance.
    Edited by: JayVirk on Dec 30, 2007 11:33 AM

    Jay,
    Your question isn't very clear, hence Joerg's well meaning but irrelevant advise.
    Do you mean:
    I've written a simple program in java which echos
    it's command-line arguments to back to the console.
    Here's my code:
    package forums;
    public class ArgsEchoer
      public static void main(String[] args) {
        for (String arg : args) {
          System.out.println(arg);
    But can't figure out how to compile and run the program.
    I'm using winblows shista, and it's cr@p.
    Please help me, Thanks in advance.So... where are you at? Have you installed the JDK (java development kit)? Which version? Is your path set? Is your classpath set?
    Start here: http://java.sun.com/developer/onlineTraining/new2java/

  • Read in file name + path using command line arguments

    Hi guys,
    I am trying to use command line arguments to read in the name of two files. The code below works as long as the files are on the class path.
    public class cmdLineArguments {
         public static void main(String[] args) {
              String xmlFile1 = args[0];
                    String xmlFile2 = args[1];
              System.out.println ("\nXmlFile1: " + args[0] + "\nXmlFile2: " + args[1]);
    }I would like to be able to read files that are not on the class path as well by entering their full path along with their names.
    In other words, It works if I type:
    C:\Documents and Settings\user\workspace\CmdLineArgs\src>java cmdLineArgs file1.xml file2.xmlbut not if I type:
    C:\Documents and Settings\user\workspace\CmdLineArgs\src>java cmdLineArgs c:\Documents and Settings\user\desktop\file1.xml c:\Documents and Settings\user\desktop\file2.xmlWould anyone please explain how I can edit the code to make it work? I guess I could take them both as a String, modify them manually (add a \ to it etc) but is there an easier way to do it? Even a reference to a tutorial, article etc about this would be very much appreciated.
    Also, any idea why a code would compile and run fine in Eclipse but would create an error from command line?
    Thanks a lot.

    You need to learn about cmd.exe which is used to process the command line. The arguments passed to any program is the command line split at white space so your command line arguments of
    c:\Documents and Settings\user\desktop\file1.xml c:\Documents and Settings\user\desktop\file2.xmlis turned into an array of
    "c:\Documents", "and", "Settings\user\desktop\file1.xml", "c:\Documents", "and", "Settings\user\desktop\file2.xml"In other words instead of 2 arguments you actually have 6.
    To get round this the file names need to be quoted
    java cmdLineArgs "c:\Documents and Settings\user\desktop\file1.xml" "c:\Documents and Settings\user\desktop\file2.xml"

  • Filenames as Command Line Arguments: How?

    i need to create a program that involves taking in a file name as command line argument, reads the file and then displays its contents on the screen. it needs to work with any file with a .txt extension.
    The only thing i dont fully understand is how to read the file name as a command line argument e.g.
    "java FileReaderApp myfile.txt
    ----contents of file--------
    Thanks in advance
    Carl
    P.S. I have lready read the various helps, utils etc for java and still dont really understand

    Okay, first, it will help if you don't think of "filenames as command line args." The two concepts are totally independent.
    Command line args are Strings. What you do with those Strings is up to you. Processing the command line args is the same, regardless of whether they represent file names or the turnons of the last 50 playmates.
    The args array below contains the command line args.
    public static void main(String[] args) {
    // do stuff
    } Files are generally referred to using the java.io.File. It takes a String for the file name. It doesn't matter where the String comes from.
    Look at FileReader and BufferedReader to actually read the contents of the file.
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileReader.html
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/BufferedReader.html
    For the basic command line arg stuff, one of the following should have some info and examples
    http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • Reading character * at command line argument?

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class FindDemo {
    public static void main(String[] args) {
    Matcher m =
    Pattern.compile("[aeiouAEIOU]*(\*)[atcgAGCT]*").matcher(
    "agctaEvening is full of the linnet's wings");
    if (m.find())
    System.out.println(m.group());
    Help?
    (\*) - How can I read the * symbol from command line argument?

    If anyone can advise me, I would be very grateful.
    I have a program that takes arguments from command line:
    one a text file and the other a sequence to search against the file.
    The sequence can contain a * which represents more than one letter of the alphabet. e.g AM*N which should yield Amen, Amoran, american
    import java.io.*;
    public class FindTextInFileNine {
        public static void main(String[] args) {
            if(args.length != 2) {
                System.out.println("Usage: java FindTextInFile [file-name] [search-string]");
            else {
                String file = args[0];
                String search = args[1];
             String parameter = search.replaceAll(" ", "");
                String result = parameter(file, parameter);
                System.out.println(result);
        public static String parameter(String file, String parameter) {
            StringBuffer strb = new StringBuffer();
            parameter = parameter.toLowerCase();
    if (parameter.matches("[actgACTG]*") != false){
                      System.out.print("Correct parameters for sequence entered.");
    if (parameter.matches("[aeiouAEIOU]*") != true){
                      System.out.print("ERROR1: Incorrect parameters for sequence entered.");
            try {
                FileReader fr = new FileReader(file);
                BufferedReader input = new BufferedReader(fr);
                int lineNumber = 0;
                String line;
                     while((line = input.readLine()) != null) {
                         line = line.toLowerCase();
                         lineNumber++;
                      System.out.println(parameter.matches("[aeiouAEIOU]*"));
                         if(line.indexOf(parameter) != -1) {
                             strb.append("Found \""+parameter+"\" at line "+lineNumber+
                                         ", starting-index "+line.indexOf(parameter));
                             strb.append('\n');
                   else {
                   System.out.println("Sequence not found in file. Please check and try again");
                input.close();
            catch(IOException e) {
              System.out.println();
                 System.out.println("ERROR2: File not found. Please check file name, file extension and file location.");
            return strb.toString();
    }Any help appreciated.

  • Pass dynamic Command line arguments

    Hi,
    I tried to pass dynamic command line argument to Web start using the method :
    "javaws URL -D foo -D bar"
    as explained in the "Unofficial JWS/JNLP FAQ" that " You can pass your own system properties to your app using -D switch ....", but I got the following error at the start;
    error occurred while launching/running the application.
    Category: Invalid Argument error
    Too many arguments supplied: {http://...URL/my.jnlp, -Did=123 }
    p.s. I already added the"<property name='' value=''/> in the <resourse>, and modified the main class to get the parameter using System. getProperty();
    Did anyone try to this method before? What's wrong of this?
    Thanks in advance for your help.

    Thanks.
    here below is the jnlp file:
    <jnlp spec="1.0+" href="$$name" codebase="$$codebase">
    <information>
    <title>GUI Application</title>
    <vendor>PS</vendor>
    <description>PS GUI WebStart Version</description>
    <icon href="logo.jpg" />
    <offline-allowed />
    </information>
    <resources>
    <j2se version="1.3" />
    <jar href="lib/gui.jar" />
    <property name="id" value="zbc" />
    <jar href="lib/classes12.zip" />
    <jar href="lib/j2ee.jar" />
    <jar href="lib/jaas.jar" />
    <jar href="lib/jce1_2_1.jar" />
    <jar href="lib/jdom.jar" />
    <jar href="lib/xerces.jar" />
    <jar href="lib/local_policy.jar" />
    <jar href="lib/log4j.jar" />
    <jar href="lib/orion.jar" />
    <jar href="lib/sunjce_provider.jar" />
    <jar href="lib/US_export_policy.jar" />
    </resources>
    <security>
    <all-permissions />
    </security>
    <application-desc main-class="GUIFrame">
    </application-desc>
    and in the main class "GUIFrame", i use System.getProperty("id") t get the parameter, if I hardcode the value of the "id" in this jnlp file and use javaws URL, everything's fine, but not the "javaws URL -Did=value" which will return the error as mentioned.
    Thanks again for your help.

  • Documenting command line arguments

    I'm very new to javadoc, and I'm trying to put together a set of guidelines for our developers to follow. One thing I came accross was command line arguments. If a main function is expecting command line arguments, how would this be documented, should @param be used? I didn't see anything about this in the guidelines sun has posted. Any help is greatly appreciated.

    This is my own personal opinion, so don't treat it as a "fact", but I don't think Javadoc is best suited for specifying command line arguments. You could do the following:
    *  Description of main() here...
    * @param args First parameter = xxx, Second parameter = yyy;
    public static void main(String[] args)
    }In this way you can specify all command-line parameters that are required in order to make the appliction run.
    BUT...
    Javadoc is meant more to be a programmatic guide to how to allow Java classes to interoperate. Java classes (mostly) will not care at all what the command-line parameters to the main invocation are. That is information that is only really needed to be known by the application executor at runtime.
    Therefore, for all my apps, I do the following to comment what types of parameters should be passed to the invocation of the application:
    * My App comments...
    * @param args Run application without any parameters to see list of all necessary command-line parameters.
    public static void main(String[] args)
       if (args.length < 1)
          System.out.println("This application allows the following parameters:");
          System.out.println("   Param#1 = xxx, <description>");
          System.out.println("   Param#2 = yyy, <description>");
          System.exit(0);
    }In this way, you do not clutter up the Javadoc APIs (used for classwise interaction) with command-line parameters, but the command-line parameters are still specified by "documentation" (running the application without any parameters).
    If parameters are optional, instead of mandatory, you could do something similar...
    * Documentation...
    * @param args Run -h as first flag for list of all optional parameters.
    public static void main(String[] args)
       if ((args.length > 0) && (args[0].equals("-h"))
          // Print out all possible parameters.
    }Anyway, this system has held me in good stead for the last couple of years.

Maybe you are looking for

  • How do I share files between users on the same machine?

    I tried using /Users/shared to share files between myself (Admin user) and another user on the machine (Standard user). Whenever I put a file or a folder into said directory permissions are 755 for directories and 644 for files, my umask is 0022. The

  • 1 long beep and 2 short beeps

    hello this is my second post....before i had problems with me8 bios, then downgraded using this forum tool..thx for that. now i can boot my PH67A-C43 (B3) board and use it normally, but my problem is that when ever i try to restart or boot it again w

  • Receive emails with new posted questions

    Dear users, Do you know if there is any way to receive emails every time that someone posts a new question in Business Intelligence forum? Regards, Jordi

  • Difficulty seeing pictures to import

    Using Aperture with Yosemite I cannot see all the pictures on the SD card when attempting to import.  I have many pictures on my SD card (I "Keep" them after Import), but when I insert the SD card into my card-reader and select Import in Aperture it

  • Computer Name Changed

    Hello. Recently I noticed that the computer name of my macbook pro changed from Erugalatha's Computer to Erugalatha's Computer (2). I didn't update/install/change anything lately so why would this happen? I've also noticed that the Applications folde