Passing a parameter using String[] args - java

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

Related

Is there any other parameter in the main method of java other than 'string[] args'?

In java, for a class having
public static void main(String[] args){
}
Is there any further arguments after String[] args
public static void main(String[] args | any_arguments_here? ){
}
All the parameters you pass will be receive only in that string array.
In short, No.
What ever you pass in the command it will be held by args array.
e.g if you write java classname Text1 Text2, args[0] will contain Text1 and args[1] will contain Text2
The answer is no.
This is a trick interview question to trap experienced C/C++ programmers pretending to be Java programmers.
In C/C++ you can declare (and receive from the runtime bootstrap libraries) an 'env' pointer after 'argv', but it is rarely used because it duplicates functionality in the getenv() call.

String[] args in main

Can some one tell , why args in main method are of String type . in
public static void main(String args[]){
}
I mean, why it is not int or float or something else. I was asked the same but could not find appropriate answer.
You might run your java program with parameters through console like this:
java YourClass first second third
In the java program you may use it through String args[].
public static void main(String[] args) {
Arrays.asList(args).forEach(System.out::println);
}
Output:
first
second
third
But it is not necessary to use such name. There are few ways to declare signature of the main method:
public static void main(String... args)
public static void main(String[] strings)
public static void main(String [] args)
Why it is not int or float or something else? At the command prompt the command is considered to be a string.
I will give you my inputs.
Command line arguments are Strings which is why that is the data type.
You can get other datatypes easily from Strings.
Most of Java's syntax is based on C, and since C used String args, maybe the creators did the same for java. (Just a possibility)
when we write java filename.java that means you giving your filename to java compiler whose main method is to be called it is obvious that the file name you are giving will be a string.
on the other end if you want to give any parameter to compiler at the same time it will also be in string not an integer or any other data type.
Because String can be converted to any type easily. If it were int and you want to take double as input, how would this happen? But with String, you can convert to whatever you expect.

String initialization confusion in java

I was trying to call the main function inside the main function i have tried the following code and got successfully compiled code.
class test
{
static int i = 0;
public static void main(String args[])
{
String asda[] = {"!2312"};
if (++i == 1)
main(asda);
}
}
But the error occurs in case of the following code:
class test
{
static int i = 0;
public static void main(String args[])
{
if (++i == 1)
main({"!2312"});
}
}
this made me so confused. the confusion is that String array initialization is done like String A[]={"asdf","Asdf"); then why is it giving an error in the second case?
I'm using java 8u40.
The syntax for what you're looking for is:
main(new String[]{"!2312"});
In your first example, Java is smart enough to know that you're creating a String array, since it's in the String[] declaration part. But since you don't have that in your second example, Java isn't smart enough to know that's a String array, or an array of Objects. So you need to specifically tell Java that it's a String array by including the String[] part.
Edit: I will also note that you could use varargs instead of an array as the argument to your main() method:
public static void main(String... args){
And then you can call your main() method with a String literal instead of an array, just like this:
main("!2312");
Your whole program might look something like this:
public class Main{
static int i = 0;
public static void main(String... args){
if (++i == 1){
main("!2312");
}
}
}
That's slightly outside your question, but it might be useful for you to know.
The problem with literals like {"!2312"} is that they do not have type information. E.g., Java has no way of knowing if you mean a String[] with one value or an Object[] with one value. You need to explicitly specify it, either by initializing a variable:
String asda[]={"!2312"};
if(++i==1)
main(asda);
or by calling the new operator:
if(++i==1)
main(new String[]{"!2312"});
In the previous code when you passed asda to main through
main(asda);
asda was an array but {"!2312"} is not an array and the main method accepts string arrays as specified in the declaration
public static void main(String args[])
where args is an array. So you should pass an array to main.
Create an array then place that string literal in it and then pass it to main.

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.

Java Command line arguments

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

Categories