0

Below is the code.

public static void main(String[] args) {
    for(String e : args) {
        System.out.println(e);
    }
}

when I input one, the output is one I understand this.

But, When input one two the output is not one two but one and two.

Isn't the space a character? if not, is the space separate each inputs in a String array?

azro
  • 53,056
  • 7
  • 34
  • 70
Sage
  • 1

6 Answers6

1

It's actually the calling program (usually the shell) that splits the arguments.

For example, in a bash shell, you can call the program like this and get one two in one line, since it is one argument for your program:

java -jar YourProgram.jar "one two" 
Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
0

The args variable is space-delimited. When you pass arguments into main from the command line, each space will indicate a different argument. E.g. C:\program.exe stuff1 stuff2 will treat stuff1 and stuff2 as two separate array elements.

Abstract
  • 985
  • 2
  • 8
  • 18
0

You're talking about program arguments. These are intended to specify some options at program launch, and they are always split by the space symbol.

If you want to have user input in your program, check out Scanner - it is the simplest way. It provides you with methods like nextInt() to read a number, or nextWord() to read a word (separated by spaces), or nextLine() to read a line without separating by spaces.

DL33
  • 194
  • 8
0

In Java args contains supplied command-line arguments as an array of String objects.
if you run your program as one two then args will contain ["one", "two"].
So What you are basically doing is traversing through the String array printing each of its elements.
This is the reason you are getting "one", "two" instead of "one two"

for(int i=0;i<args.length;i++)
{
     System.out.println(args[i]);
}

The Above is the equivalent code of what you have done in your one.

Debi Prasad
  • 297
  • 1
  • 8
0

You can easily read input from Console using BufferedReader.

Code :

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input1 = br.readLine();
0

The space character is what separates the elements in the args array, which by the way, can be given any valid variable name. See https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

If you want your program to print one two in one line, pass both words as one string and run your program like this:

java -jar yourJarFile.jar "one two"

You can also look at this answer What is "String args[]"? parameter in main method Java

Nexonus
  • 706
  • 6
  • 26
eunelyky
  • 69
  • 7