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.
Related
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.
Description
I have a beginner's-level program. My goal is to pass an argument in at runtime for the first time.
Proposed questions
Describe the error in greater detail?
How are errors like this traced and repaired?
I've used google and StackOverflow. Should I be using a different resource to help with errors like this in my beginner programs?
My code
class sayagain {
public static void sayagain(String s){
System.out.print(s);
}
public static void main(String[] args){
sayagain(arg);
}
}
Compile error
print2.java:11: error: cannot find symbol
print2(arg);
^
symbol: variable arg
location: class print2
1 error
Correct
arg is not defined. Maybe you mean sayagain(args[0]), which will print the first argument in the main method.
Explanation of string array types-and-indexes
args is a string array, so to get the first argument you need to access the first element in the array: [0].
Warning
You will be given an index out of bounds error if you do not include any arguments when you call the main method.
Example input: >java sayagain
Example output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at sayagain.main(sayagain.java:11)
Variable plurality
There's no built-in function to discover arg as the singular of args. Variables may be anything within the specification of the formal language, even asdfsfaeef. It is much better practice to use a descriptive name; therefore, people tend to use plural form when naming arrays.
It looks like typographical error.
you have passed arg :- s is missing from the name as the argument you recieved in main method is args.
sayagain(arg);
However if you pass 'args' to your method it still give an error as args is an array type and your function is looking an String type. So the correct call for that function would be.
sayagain(args[0]);
Check the args length before calling this function otherwise it may throw an ArrayIndexOutOfBoundException if parameter not passed.
My own spin
Correct: System.out.print(args[0]);
Incorrect: System.out.print(args); //wrong type.
Incorrect: System.out.print(args[1]); //wrong index.
Incorrect: System.out.print(arg); //not a variable.
Incorrect: System.out.print(arg[0]); //typo (see above).
In Java, source code is compiled to class files using javac sayagain.java, which in turn creates a sayagain.class which is essentially what the JVM (Java Virtual Machine) can understand and execute.
To run the sayagain.class that the javac command generated, you'll use java sayagain
You can also pass arguments, seperated by spaces, to the class that you are running, like so:
java sayagain Hello World !
These arguments is passed to the args array which you defined in your main class, which is the method that will be called first. (You could have called it listOfArguments, like below, and it would have made no difference)
To access any object contained within an array, you use []. Number starts at 0 and ends and length-1. Here is an altered example of your code:
public class sayAgain {
//Eventhough there is two say methods, one takes a String parameter, and one takes an Integer parameter, thus they are different
public static void say(String s){
System.out.print(s);
}
public static void say(int i) {
System.out.print(i);
}
public static void main(String[] listOfArguments){
//First argument, starting at 0 - Hello
String arg1 = listOfArguments[0];
//Second argument - World
String arg2 = listOfArguments[1];
//Second argument - 3
String arg3 = listOfArguments[2];
//arg3 is a integer but is saved as a String, to use arg3 as a integer, it needs to be parsed
// Integer, is a class, just like your sayAgain class, and parseInt is a method within that class, like your say method
int count = Integer.parseInt(arg3);
//Print each argument
say(arg1);
say(arg2);
say(arg3);
//Use the converted argument to, to repeatedly call say, and pass it the current number
for (int t = 0; t < count; t++) {
//The variable t is created within the for structure and its scope only spans the area between the { }
say(t);
}
}
}
Hope this helps :)
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
public class test
{
public static void main(String[] args)
{
int x = 5;
int y = 10;
multiply(x,y);
}
public static void multiply(int x, int y)
{
int z = x*y;
System.out.println(z);
}
}
I am new to programming and I am confused on a few things.
Why is it correct to use void? I thought void is used in order to specify that nothing will be returned but, the multiply method returns z.
Do all programs require that you have exactly "public static void main(String[] args)"? What exactly is the purpose of the main method and what do the parameters "String[] args" mean? Would the program work if the main method was removed?
Thank You!
First, the multiply method does not return anything; it prints the product, but does not return any value.
public static void multiply(int x, int y)
{
int z = x*y;
System.out.println(z); //may look like a return, but actually is a side-effect of the function.
} //there is no return inside this block
Secondly, public static void main provides an entry point into your program. Without it, you cannot run your program. Refer to the Java documentation for more information on the usage of public static void main.
The String[] args here means that it captures the command line arguments and stores it as an array of strings (refer to the same link posted above, in the same section). This array is called args inside your main method (or whatever else you call it. Oracle cites argv as an alternate name)
System.out.print tells the program to print something to the console, while return is the result of the method. For example, if you added print all over your method to debug (a common practice), you are printing things while the program runs, but this does not affect what the program returns, or the result of the program.
Imagine a math problem - every step of the way you are "print"ing your work out onto the paper, but the result - the "answer" - is what you ultimately return.
When a method does not return anything, you specify its return type as "void". Your multiply method is not returning anything. Its last line is a print statement, which simply prints the value of its arguments on the standard output. If the method ended with the line "return z", then you would not be able to compile the program with the "void" return type. You would need to change the method signature to public static int multiply(int x, int y).
All Java programs do require the public static void main(String[] args) if they are to be executable. It is the starting point of any runnable Java program. Here's what it means:
a. public - the main method is callable from any class. main should always be public because it is the method called by the operating system.
b. static - the main method should be static, which means the operating system need not form an object of the class it belongs to. It can call it without making an object.
c. void - the main method does not return anything (although it may throw an Exception which is caught by the operating system)
d. String[] args - when you run the program, you can pass arguments from the command line. For example, if your program is called Run, you can execute the command java Run 3 4. In that case, the arguments would be passed to the program Run in the form of an array of Strings. You would have "3" in args[0] and "4" in args[1].
That said, you could have a Java program without a main, which will not be runnable.
I hope that helps.
Why is it correct to use void? I thought void is used in order to specify that nothing will be returned but, the multiply method returns z.
No
multiply method does not return z. However, you are correct, void is in fact used to specify that nothing will be returned.
Do all programs require that you have exactly "public static void main(String[] args)"? What exactly is the purpose of the main method and what do the parameters "String[] args" mean? Would the program work if the main method was removed?
yes, all programs must have a main function that looks like public static void main(String[] args).
Like others said, the multiply method does NOT return anything. The other answers explained why that is.
However it would also be helpful to mention that when you use void that method can not return anything. In contrast, if you set your method to return anything (not to void) you are required to return that type of value.
For example:
public static void main(String[] args){
int a;
a = returnInt();
}//End Method
public static int returnInt(){
int z = 5;
return z;
}//End Method
The main method does not return anything, which is why we use void. The returnInt method returns an integer. The integer that the method returns is z. In the main method where a = returnInt(); that sets the value of a to the value returned from returnInt(), in this case, a would equal 5.
Tried to keep it simple, hope it makes sense.
public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.
static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
void means that the method has no return value. If the method returned an int you would write int instead of void.
The combination of all three of these is most commonly seen on the main method which most tutorials will include.
credits to Mark Bayres
The multiply() method in your example does not return the value of z to the calling method, rather it outputs the value of z (e.g., prints it to the screen).
As you said, the void type keyword means that the method will not return a value. Methods like this are intended to "just do something". In the case of main(), the method will not return a value, because there is no calling method to return it to -- that's where your program begins.
OK, technically, that last comment is not accurate; it actually is possible to have your main return a value to the operating system or process that launched the program, but it isn't always necessary to do so -- especially for simpler console-based programs like those you'll write when you're just getting started! :)
Void class is an uninstantiable class that hold a reference to the Class object representing the primitive Java type void.
and The Main method is the method in which execution to any java program begins.
A main method declaration looks like this
public static void main(String args[]){
}
The method is public because it be accessible to the JVM to begin execution of the program.
It is Static because it be available for execution without an object instance. you may know that you need an object instance to invoke any method. So you cannot begin execution of a class without its object if the main method was not static.
It returns only a void because, once the main method execution is over, the program terminates. So there can be no data that can be returned by the Main method
The last parameter is String args[]. This is used to signify that the user may opt to enter parameters to the java program at command line. We can use both String[] args or String args[]. The Java compiler would accept both forms.
Why is it correct to use void? I thought void is used in order to
specify that nothing will be returned but, the multiply method returns
z.
Your multiply method is correct to have void since it is returning nothing, it is just printing to the console.
Returning something means gives out a result to the programm for further computation.
For example your methode with return of the result would look like this:
public static int multiply(int x, int y)
{
int z = x*y; //multipling x and y
System.out.println(z); //printing the restult to the console
return z; //returning the result to the programm
}
this "new" method can be used like this for example:
public static void main(String[] args)
{
int x = 5;
int y = 10;
int result = multiply(x,y); //storing the returnen value of multiply in result
int a = result + 2; //adding 2 to the result and storing it in a
System.out.println(a); //printing a to the console
}
Output:
50
52
Do all programs require that you have exactly "public static void
main(String[] args)"? What exactly is the purpose of the main method
and what do the parameters "String[] args" mean? Would the program
work if the main method was removed?
This mehtod seves a the etry point for your programm. This meas the first thing that is executet of your programm is this mehtod, removing it would make the programm unrunneable.
String[] args stands for the commandline arguments you can give to you programm befor starting over the OS (OS = Windows for example)
The exact purpose of all of the words is very well explained in the other answers here.
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