This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is “String args[]”? in Java
So I recently (well, three days ago) started teaching myself Java, with absolutely zero previous programming experience unless you count HTML/CSS.
Now I've been looking through both books and online tutorials, including the Sun tutorials. I don't quite understand what the purpose of (string args[]) in a method is.
What I've got from looking online is that when using the console to run a program, it substitutes whatever comes after ">Java myprogram" in place of the "args".
Firstly, is that correct? If so, why would you do that?
Cheers!
The String[] args which can be written as String args[] or String ... args is an array of the arguments you gave the program.
why would you do that?
So you can give your program inputs on the command line. It isn't used in Java programs so often but it is quite commong for command line utilities to take arguments e.g.
In this case the MyClass.java is an argument.
javac MyClass.java
Or like the following has three arguments.
java -cp . MyClass
This is, more or less, correct. Every whitespace-separated word that comes after java Program is stored into an array of Strings, which happens to be called args.
An example on how to use this for your benefit:
public class Test {
public static void main(String[] args)
{
if(args.length > 0)
{
System.out.println(args[0] + "\n");
}
}
}
Compile this with:
> javac Test.java
And then run it:
> java Test Yes
"Yes" is then printed to your screen.
Related
I wondered whether there was any connection between the main method's parameter String[] args and the possibility of opening files with a specified program.
Considering that I wrote a simple program that writes down every String of args, then opened some files with this program (I am using windows).
This is what happened:
No matter what kind of file I opened with my program (right click -> open with...), argscontained only one String which was the file's complete path.
When I ran the program on itself, args was of length 0.
Now my question is: are there any other Strings that might be contained in args or would the following code always work without doubt?
(I want to use this on windows, not play around with it like java MyProgram 1 2 3 "test"
public static void main(String[] args) {
initProgram();
if (args.length != 0) { //file opened with program
loadFile(new File(args[0]));
}
}
Thank you for your answers and please be patient with my english.
Just like Marcos Vasconcelos assumed: by opening multiple files at once args will contain all the files' paths tried to open, so args can be larger than just one String. Its length depends on the amount of files that want to be opened with the program.
I have a java jar that need to accept about 3 arguments but I want to pass them as a Q&A type like the following:
1st step run java jar
java -jar myTest.java
2nd step ask questions and wait for answers:
Hi, how old are you?
I type my answer that accepts it and then ask the 2nd question:
nice! what is your name?
type my second answer and the get a third question and so on. how do I achieve this? I know that I can pass arguments to main but what I found is that I have to pass them all when I first run the jar not like what I'm looking for.
Any ideas?
Thanks!
the way to interact with an application depends of the logic in the application itself...
if you need to give parameters that the application needs from the start point then you give those as soon as you run the application
java -jar myTest.java
all those parameters are getting passed to the string[] parameter in the public static void main method...
in your case, (and if I got the question right) you will need more information from the user, and this is given at runtime... so you need another way to do that like Scanner class allowing you to read input from the terminal too...
Use the Scanner class and read the user input from the console..
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
String input = sc.nextLine();
System.out.println("Hi, " + input + ", where are you from");
input = sc.nextLine();
System.out.println("Ohh, " + input + " is nice place I guess!");
System.out.println("and how old are you??");
...
}
It seems that you are mixing up concepts.
Command line arguments are those strings that you see as String[] args parameter to your main method!
But you want the user to provide "more" input to your application, the typical way is to read them from "stdin" (see here to learn how to do that).
Those two are fundamentally different things; and you should first clarify which one you really intend to use (given your example ... probably the "stdin" option).
Try reading the Java IO tutorial here:
https://docs.oracle.com/javase/tutorial/essential/io/cl.html
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I was recently asked in an exam why we use main (String args[ ]) only in java? Why don't we use main (String args[ ]) in any other programming languages?
main() and other ways to shape the entry point into the application is a part of the language. The reason it is done the particular way in particular language is because the author of the language has seen the protocol between the language runtime system (an OS abstraction layer if that language needs to have an OS underneath to run) and the programmer that way.
I can assume that in Java it was made main(String[] args) because the language was inspired by C++ in a way (thus main() was preserved) and String[] args this is the Java way to pass an array of strings into the function.
Regarding…
“Why don't we use main (String ars[]) in any other programming languages?”
That’s a flawed assumption in the question.
C# example from MSDN:
// Hello3.cs
// arguments: A B C D
using System;
public class Hello3
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}
Why don't we use main (String ars[ ]) in any other programming languages?
Because you like to do it probably. If you're asking if you can do that in other languages (like C++, with which you marked the topic), the answer is: yes, you can.
They syntax for C++ would be:
int main(int argc, char *argv[])
Or - if you would want to also include environment variables:
int main(int argc, char *argv[], char *envp[])
Java has a built in String class so arguments to the class's main method are represented by String args[] or a String array.
Whereas in C++, there is not built in String class, so arguments are represented by char* argv whereas their count is represented by int argc.
The UNIX interface for invoking an application is to collect the individual command line tokens into an array of strings and pass that array to the entry point of the application. UNIX defined that this entry point is named "main", and that the command line tokens would be expressed as an array of pointers to C-style null-terminated strings. Since there's no other way to know the size of the array, the array size was passed as a separate parameter:
main(int argc, char* argv[])
MSDOS and Windows copied this scheme, so it has become quite standard.
Even though Java programs aren't invoked directly from the operating system, the designers of Java choose to use a similar (familiar) paradigm, where the command line tokens would be passed into a method named "main" as an array of Java String objects.
This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 9 years ago.
I am a new programer and I'm just starting to learn the basics of Java and I'm trying to understand what exactly "args" stands for in "public static void main(String[] args)".
I found that's it's connected to command line arguments, which I don't understand. I would like to know what "args" means.
Thank you.
When you run a Java program, it usually looks like this:
java MyProgram
However, you also have the option of including command-line arguments. For example, if your program adds two numbers, you could set it up to take input like this:
java MyProgram 12 47
In this case, arr would equal ["12", "47"]. Having input work in this way is useful because it makes it easier to automate the running of your program through batch files or the like.
args is an arbitrary name for command line arguments. Running a java class file from the command line will pass an array of Strings to the main() function. If you want to handle extra arguments, you can check for keywords at certain indices of args and perform extra functions based on them.
As you can probably understand from the question itself, I'm new to Java.
I was given an exercise to write a Java program which receives a character, prints it and the next character in the Unicode table.
Now, I have the solution to this exercise:
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
I understand basic idea of this code, but I'm trying to run this code in Eclipse I get an annoying error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at MainClass.main(MainClass.java:9)
Note: I have yet to run a Java program that actually receives something as a parameter so I guess it's a stupid beginners' mistake... Here is the full code that I tried to compile in Eclipse:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args){
char c = args[0].charAt(0);
char c1 = (char)(c + 1);
System.out.println(c + "\t" + c1);
}
}
Thanks in advance
Select "Run -> Run Configurations" from the menu.
Search for you project in the list on the left and select it.
Select the "Arguments" tab on the right.
Write the argument you want to pass to the programm in "Programm arguments".
Click "Run"
Right click on your java file in project explorer of your eclipse. Then Run As> Run Configuration
Then you will get a window. Like-
Click on Arguments Tabs, and then write some text there, may be a character.
And then Click on Apply button and Run Button.
The default run configuration in Eclipse runs a Java program without any arguments, hence the ArrayIndexOutOfBoundsException. Your code is trying to get first element of the args array when there aren't any!
You can edit the run configuration to provide the arguments to run your program with. Then it should not throw this exception.
However, a good practice is to check the size of array before accessing it's elements, more so when the array is coming as an argument from outside of your code.
This is a great question with some very good answers. I would like to add some pointers about how to debug your own program. Debugging is as important (if not more important) than writing code.
For one thing, Eclipse has some great debugging features. You can use this debugger to find problems in your code. I suggest that you learn how to use it. In particular, you can set watches for variables to see what value they have as you step through the execution of your code.
Alternatively, you can add calls to System.out.println() to print out the values of any variables. For example, adding the following line at the beginning of your code might help you narrow down the problem:
System.out.println(args[0]);
This would also give an ArrayIndexOutOfBoundsException if no command-line arguments are given. Then you could do something like
System.out.println(args.length);
which would print out 0. This then gives you a clue as to where the problem is.
Of course, even when you get to this point, you still might not know how to solve the problem. This is where sites like StackOverflow come in handy.
Good luck with your Java experience. Please come back when you need more help.
If your Run Configurations are in place (as already shown in above answers):
Shortcut to Run a class is:
Ctrl + F11