Java Command line arguments - java

I am trying to detect whether the 'a' was entered as the first string argument.

Use the apache commons cli if you plan on extending that past a single arg.
"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."
Commons CLI supports different types of options:
POSIX like options (ie. tar -zxvf foo.tar.gz)
GNU like long options (ie. du --human-readable --max-depth=1)
Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
Short options with value attached (ie. gcc -O2 foo.c)
long options with single hyphen (ie. ant -projecthelp)

public class YourClass {
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("a")){
//...
}
}
}

Every Java program starts with
public static void main(String[] args) {
That array of type String that main() takes as a parameter holds the command line arguments to your program. If the user runs your program as
$ java myProgram a
then args[0] will hold the String "a".

Command-line arguments are passed in the first String[] parameter to main(), e.g.
public static void main( String[] args ) {
}
In the example above, args contains all the command-line arguments.
The short, sweet answer to the question posed is:
public static void main( String[] args ) {
if( args.length > 0 && args[0].equals( "a" ) ) {
// first argument is "a"
} else {
// oh noes!?
}
}

Command line arguments are accessible via String[] args parameter of main method.
For first argument you can check args[0]
entire code would look like
public static void main(String[] args) {
if ("a".equals(args[0])) {
// do something
}
}

Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).

Try to pass value a and compare using the equals method like this:
public static void main(String str[]) {
boolean b = str[0].equals("a");
System.out.println(b);
}
Follow this link to know more about Command line argument in Java

As everyone else has said... the .equals method is what you need.
In the off chance you used something like:
if(argv[0] == "a")
then it does not work because == compares the location of the two objects (physical equality) rather than the contents (logical equality).
Since "a" from the command line and "a" in the source for your program are allocated in two different places the == cannot be used. You have to use the equals method which will check to see that both strings have the same characters.
Another note... "a" == "a" will work in many cases, because Strings are special in Java, but 99.99999999999999% of the time you want to use .equals.

Command line arguments are stored as strings in the String array String[] args that is passed tomain()`.
java [program name] [arg1,arg2 ,..]
Command line arguments are the inputs that accept from the command prompt while running the program. The arguments passed can be anything. Which is stored in the args[] array.
//Display all command line information
class ArgDemo{
public static void main(String args[]){
System.out.println("there are "+args.length+"command-line arguments.");
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]:"+args[i]);
}
}
Example:
java Argdemo one two
The output will be:
there are 2 command line arguments:
they are:
arg[0]:one
arg[1]:two

Related

Passing a parameter using String[] args

I have a strong suspicion I'm being stupid here but I have never seen anyone d this before. In this piece of coursework instead of declaring a variable they are using the string array arguments declared in the main.
static public void main(String[] args) {
RandomAccessFile admin;
byte init[] = {0};
if (args.length != 1)
System.err.println("usage: java {gate_bottom,gate_top}");
My Instructions are
"To do this you will need to specify a parameter. The parameter should be either gate_bottom or gate_top"
Where should I specify the parameter so that args contains something?
if(args[0].equals("gate_bottom"))
else if(args[0].equals("gate_top"))
So when you invoke the program like myprogram.exe gate_bottom or myprogram.exe gate_top the conditions will be triggered

ArrayOutOfBoundsExcetpion in command line arguments

in command line arguments i got Exception in the thread main java.lang.ArryINdexOutOfBoundsException. How can i overcome this?
class p
{
public static void main(String a[])throws Exception
{
int n= Integer.parseInt(a[1]);
System.out.println(n);
}
}
If you call the program with only one parameter, you have to use Integer.parseInt(a[0]);, because arrays in java are zero bases.
Also you should check the length of a before accessing an entry.
You can give the two parameters from command prompt then your code will be successfully run like java className parameter1 parameter2 then you can access second parameter by using a[1].
other wise change a[1] to a[0] for first parameter.

How to pass array of strings to a Java program?

In:
public static void main (String [ ] args)
How to set the value parameter variable args of the main method as an array of String?
The args are optional command line values.
java MyProgram --arg1 --arg2
could be accessed as
args[0] == "--arg1"
args[1] == "--arg2"
Value is passed as command line arguments.
For ex, you have this program(Cmd.java):
public class Cmd
{
public static void main(String agrs[])
{
System.out.println("Values are:"+args[0]+" and "+args[1]);
args[0]="New1";
args[1]="New2";
System.out.println("Modified values are:"+args[0]+" and "+args[1]);
}
}
Compile it like:
javac Cmd.java
Execute it like:
java Cmd Value1 Value2
Output will be:
Values are Vaue1 and Value2
Modified values are New1 and New1
Hope you got the point!
BONUS:
If you don't pass any values during execution the program will throw an ArrayIndexOutOfBoundsException.
You may want to handle that!
Read more about Command Line arguments at The Java tutorials (Oracle docs)!
When you execute your java program in command line you can provide arguments to the executable:
java MyClass arg0 arg1 arg2
In Java the word args contains the command-line arguments that are given in input to your program as an array of String Objects.
That is, if you run java AnExample a b, args will contain ["a", "b"].
So, if you want just to print out the contents of args, you can simply loop through them:
public class HelloWorld {
public static void main( String[] args ) {
for( int i=1; i < args.length; i++ ) {
System.out.println( args[i] );
}
}
}
For a deep explication of the Java args you can read this interesting presentation from Emory university.
You can set an array of Strings when you call the program.
java MyClass args0 args1 etc
If you are using Eclipse then this is done under Project->Run Configurations/Debug Configurations. Click the Arguments tab and enter your arguments in the Program arguments box.
The String args[] contains all the arguments you pass to a Java program when you start it with a command line.
Example command to launch a Java application:
java MyApp arg1 arg2
What we have done in the example above is we passed 2 arguments to our MyApp java application ("arg1" and "arg2").
You can now use them however you want.
yup..
just compile your code by
javac <class name> args0 args1 ..

Basic beginners in Java: what does 'arguments' mean in Java

iv'e been trying to learn basic java programming for the last 2 days, and I encountered an issue i can't figgure while viewing the following code:
class DayCounter {
public static void main(String[] arguments) {
int yearIn = 2008;
int monthIn = 1;
if (arguments.length > 0)
monthIn = Integer.parseInt(arguments[0]);
if (arguments.length > 1)
yearIn = Integer.parseInt(arguments[1]);
System.out.println(monthIn + "/" + yearIn + " has "
+ countDays(monthIn, yearIn) + " days.");
}
}
I can't understand the line if (arguments.length > 0)
what does arguments mean? Where did the value come from?
I can't understand the line "if (arguments.length > 0) what does "arguments" mean? where did it value came from?
It came from the method declaration:
public static void main(String[] arguments) {
That declares a parameter called arguments. For a normal method call, the caller specifies the argument, and that becomes the initial value of the parameter. For example:
int foo(int x) {
System.out.println(x);
}
...
foo(10);
Here, 10 is the argument to the method, so it's the initial value for the x parameter.
Now a public static void method called main in Java is an entry point - so when you run:
java MyClass x y z
the JVM calls your main method with an array containing the command line arguments - here, it would be an array of length 3, with values "x", "y" and "z".
For more details, see the relevant bits of the Java tutorial:
Passing information to a method or constructor
Command-line arguments
arguments are the command line options given to your java program when it runs. They are stored in an array so calling arguments.length gives the number of command line inputs to your program.
They are passed in like this on execution
java program argument1, argument2, argument3
In this case arguments.length would return 3 as there are 3 command line arguments.
In this case arguments is the variable name used for array of Strings you provide as input on execution,
i.e.
java DayCounter 1 2010
In the following code excerpt:
public static void main(String[] arguments)
String[] means an array of Strings with a variable name of arguments. Java uses this function prototype for main as default. See here for a tutorial: http://docs.oracle.com/javase/tutorial/getStarted/application/index.html
So when you reference length in arguments (arguments.length), you are looking "inside" the array of Strings finding the length of the array (using a built-in function of Java Strings to do so)
They come from the command prompt. When you start to run a program, you can say:
java program arg1 arg2 ...argN
The args go immediately after the program name.
- Usually parameters and arguments are used interchangeably, but they are different.
I will take an example to explain this:
public class Test{
public void go(String s){
}
public static void main(String[] args){
Test t = new Test();
t.go("Hello");
}
}
- In the above code variable s which is of type String in the line public void go(String s) is the Parameter.
- Where as "Hello" which is of type String in the line t.go("Hello") is an Argument.
- The elements in method definition or declaration are Parameters, where as the elements passed in the method call are Arguments.
Arguments is a list of Parameters that can be passed to your Java Programm at start up.
if (arguments.length > 0) checks if any arguments have been provided.
As otherwise you will be trying to access an empty array and get and index out of bounds exception.
Also there are pleanty of tutorials out there, that can help you.
Have a look at Oracle's essentials guide, here about CMD Line Arguments.
arguments is passed in to the main method
public static void main(String[] arguments)
in this case it means an array of values that can be passed to this method. Usually this is the arguments that you pass to a program from command line or from a shortcut and then you can use them in the program to change the logic flow.
First Understand the meaning of code at hand.
It tells you the number of days in a given month of a year. So obviously when you run the code you need to have a year value and the month value as given values.
In this case month value and year value as provided during code execution time become the argument. In this case the word "argument" is used as such but you can use x or y or xyz to name a variable, as you know.
Java accepts the arguments as the String array. So prior to using them as Integer you need to parse them, that's what has been done in the above code.
Eg
class WelcomeYouself{
public static void main(String[] args){ //Here insted of arguments,the word args is used.
System.out.println("Hello " + args[0]);
}
}
Now when you run this you pass your own name as argument.
java WelcomeYourself Feynman;
// This how you run or execute the java code passing your name as the "argument". Of course it is presumed you are Feynman.

What does "String[] args" contain in java?

When I run the following program:
public class Test
{
public static void main(String[] args)
{
System.out.println(args);
}
{
It prints: [Ljava.lang.String;#153c375
and when I run it again, it prints: [Ljava.lang.String;#1d1e730
it gives me different output each time
So, what does "[Ljava.lang.String;#153c375" mean?
Update: I just realized I never answered the question "What does “String[] args” contain in java?" :-) It's an array of the command-line arguments provided to the program, each argument being a String in the array.
And we now resume with our regularly-scheduled answer...
args is an array. To see individual command-line arguments, index into the array — args[0], args[1], etc.:
You can loop through the args like this:
public class Test
{
public static void main(String[] args)
{
int index;
for (index = 0; index < args.length; ++index)
{
System.out.println("args[" + index + "]: " + args[index]);
}
}
}
For java Test one two three, that will output:
args[0]: one
args[1]: two
args[2]: three
Or loop like this if you don't need the index:
public class Test
{
public static void main(String[] args)
{
for (String s : args)
{
System.out.println(s);
}
}
}
So, what does "[Ljava.lang.String;#153c375" mean?
That's Java's default toString return value for String[] (an array of String). See Object#toString. The [ means "array", the L means "class or interface", and java.lang.String is self-explanatory. That part comes from Class#getName(). The ;#153c375 is ;# followed by the hashCode of the array as a hex string. (I think the default implementation of hashCode for Object indicates where in memory the array is located, which is why it's different for different invocations of your program, but that's unspecified behavior and wouldn't be any use to you anyway.)
String[] args in main method is the String array of the command line arguments.
[Ljava.lang.String;#1d1e730 are the class name ([Ljava.lang.String is String[]) and the object's hashcode (#1d1e730);
if you want to print the actual values of the Strings in the array, you can use a simple for-each loop:
for(String arg:args)
System.out.println(arg);
It's a form of name mangling used for disambiguating method overloads. The method name is appended by a series of characters describing the parameters and return type: the parameters appear sequentially inside parentheses, and the return type follows the closing parenthesis. The codes are as follows:
Z: boolean
B: byte
C: char
S: short
I: int
J: long
F: float
D: double
L fully-qualified-class-name ; : fully qualified class
[ type : array of type
V: void
So according to above codes [Ljava.lang.String;#153c375
Array of string (java.lang.String fully qualified class name) followed by hascode.
String[] args is an Array of Strings and contains the arguments that were given when the application was started. Java does not require you to use the name args, you could just as well specify String[] foo but that will make things unclear if you later read your code again.
Default implementation of toString method for Object is classname;#identityHashCode.
I think, this is what you expect:
System.out.println(java.util.Arrays.toString(args));
It's a string array.
Modify your code to this:
public class Test{
public static void main(String[] args){
System.out.println(args[0]);
}
}
Now compile this code:
$>javac Test.java
Now run:
$>java Test hello
This will print: "hello"
Because "hello" is the argument you are passing to your class.
If you try: args[x], where x=0..n and run your class via command line: java Test your arguments, then you will see any contents which you pass..
The main method has a parameter that is an array of String references.
So each time you try to print args, it gives you memory location of array 'args' because this String array args located a place in memory for array elements.
That say you have an simple program called 'HelloWorld.java' like this:
public class HelloWorld
{
public static void main(String [] args)
{
for(int i =0; i<args.length; i++)
System.out.println(""+args[i]);
}
}
Ready to test this program with command line interface:
java HelloWorld a b c
We can see that this program prints thouse arguments after 'java Helloworld'
a
b
c
Lets make it simple
1: Write a simple class named "test"
public class test {
public static void main(String[] args) {
System.out.println("Passed argument is: " + args[0]);
}
}
2: Now compile it in the following way
javac test.java
3: Now run this by passing an argument
java test Ayoub
** the output will be**
Passed argument is: Ayoub

Categories