What does "String[] args" contain in java? - 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

Related

What does (String[] arguments) mean? [duplicate]

This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Why does main method in Java always need arguments?
(8 answers)
Closed 9 years ago.
I added the following code to a new class I created in Java:
public static void main(String[] arguments) {
I understand what public, static and void mean, but what does (String[] arguments) mean?
Your main() method can take input parameters of type String if your program is run through a console like
java YourClass arg1 arg2
Now, within main() if you iterate the String [] like
for (arg : arguments)
System.out.println(arg);
it should print
arg1
arg2
Demo :
public class AddTwoNumbers {
public static void main(String[] args) {
if(args.length == 2) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("a + b = " + a + " + " + b + " = "+ (a + b));
} catch (NumberFormatException e) {
System.err.println("Invalid Input: Please enter numbers.");
}
} else {
System.err.println("Missing Input: Please enter TWO numbers.");
}
}
}
You can run this on your console as
java AddTwoNumbers 2 3
and it should print
a + b = 2 + 3 = 5
It literally means "an array, where every element inside of it is at least a String, which we will name arguments".
In the context of the rest of the line, the method main takes as input, "an array, where every element inside of it is at least a String, which we will name arguments"
Since this is the public static void main(String[] arguments) method call, there is a special "exception to the rule" of normal parameter passing. Methods that look like this are one of the very few times when your input is not defined in some other part of your program. Instead the Java Virtual Machine constructs the input into this method, from the command line arguments you gave the JVM.
It means that the function expects an array of strings.
String[] arguments is the array for run time argument to your java program. If required you can pass arguemnts to your java program like this:
java yourJavaMainClass args1 args2
In your java code you can use the arguments provided by simply iterating over this array.
arguments[0] // this should give you the args1
It's the array of parameters that you may pass to your program during the execution. Ex:
java YourClass param1 100 X
In your runtime, you'll have this array
System.out.println(args.length); //prints 3
System.out.println(args[0]); //prints param1
System.out.println(args[1]); //prints 100
System.out.println(args[2]); //prints X
These are the parameters that the main function expects.
String [] arguments is a java array of String objects. This means that the main function expects an array of Strings. This array of strings typically holds all command line parameter arguments passed in when the program is run from the command line.
From the command line
java className stringOne stringTwo
In the program
Note : means in .. So read this as for stringObject in arguments
for (stringObject : arguments) {
System.out.println(stringObject);
}
Or if you know the exact amount of Strings that will be in arguments is two then
System.out.println(arguments[0]);
System.out.println(arguments[1]);
Output->
stringOne
stringTwo
Hope this helps! Good luck learning Java
Run the program using command line and the input provided there gets stored in obj array. So if you run the class as java className a1 a2 then object array will have a1 and a2 as elements.
Or if you are using eclipse IDE the go to run/debug config and do as shown

Making main accept object other than string?

Is it possible to have the main method accept an argument other than a string array? For example, can we have a method like main(Animals[]args){/*code*/}? If not, then why?
No - the entry point is always the method with the header public static void main(String[] args) (i.e. the JVM invokes this particular method). You can certainly define a method
public static void main(Animals[] args) {...}
but it would not be executed directly upon running the program.
EDIT: The reason the main method specifically has a string-array argument is because this array will contain the command-line arguments when the program is run. Intuitively, these should be strings (and certainly not Animals, for example).
Because when you input from the command line you are entering strings, not a complex type.
So it makes sense for the argument to be an array of pointers (references) to strings, including or not (depending on the language) the count of the arguments. In Java this isn't needed as you can just use length.
Not sure why you'd want that?..
The spec says it can only handle array of Strings.
There is nothing stopping you from having a public static void main that takes a parameter type other than String. The problem is the that the JVM needs simple rules for identifying and calling the method. It has an array of strings, e.g. from the command line, available to pass to the program. How would the JVM go about turning it into an array of Animal, or some other type, before it has started running your program?
Here's an example of a main that takes a different parameter type, and of the program itself dealing with producing the Animal array from the array of strings that the JVM has. Of course, it would really be better to give the second main method a more meaningful name.
import java.util.Arrays;
public class Bad {
public static void main(String[] args) {
Animal[] animals = new Animal[args.length];
for (int i = 0; i < args.length; i++) {
animals[i] = new Animal(args[i]);
}
main(animals);
}
public static void main(Animal[] args) {
System.out.println(Arrays.asList(args));
}
}
class Animal {
String species;
public Animal(String species) {
this.species = species;
}
public String toString() {
return "Animal: " + species;
}
}

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.

How can I create a Java method that accepts a variable number of arguments?

For example, Java's own String.format() supports a variable number of arguments.
String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!
How can I make my own function that accepts a variable number of arguments?
Follow-up question:
I'm really trying to make a convenience shortcut for this:
System.out.println( String.format("...", a, b, c) );
So that I can call it as something less verbose like this:
print("...", a, b, c);
How can I achieve this?
You could write a convenience method:
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
But as you can see, you've simply just renamed format (or printf).
Here's how you could use it:
private void printScores(Player... players) {
for (int i = 0; i < players.length; ++i) {
Player player = players[i];
String name = player.getName();
int score = player.getScore();
// Print name and score followed by a newline
System.out.format("%s: %d%n", name, score);
}
}
// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);
// Output
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.
Varargs
PrintStream#format(String format, Object... args)
PrintStream#printf(String format, Object... args)
This is known as varargs see the link here for more details
In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:
Object[] arguments = {
new Integer(7),
new Date(),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet "
+ "{0,number,integer}.", arguments);
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:
public static String format(String pattern,
Object... arguments);
Take a look at the Java guide on varargs.
You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(....
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
This is just an extension to above provided answers.
There can be only one variable argument in the method.
Variable argument (varargs) must be the last argument.
Clearly explained here and rules to follow to use Variable Argument.
The following will create a variable length set of arguments of the type of string:
print(String arg1, String... arg2)
You can then refer to arg2 as an array of Strings. This is a new feature in Java 5.
The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.
void print(final String format, final String... arguments) {
System.out.format( format, arguments );
}
You can pass all similar type values in the function while calling it.
In the function definition put a array so that all the passed values can be collected in that array.
e.g.
.
static void demo (String ... stringArray) {
your code goes here where read the array stringArray
}

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