0

Ok, I want a line of code That will allow me to print all args as one string.

Example of what i need: lets say arg[0] = "Hi"; and lets say arg[1] = "there";

i want it to print "Hi there", not something like [Hi, there] when you use Array.toString()

Thanks - Jay (0-0)/

Jay Parker
  • 3
  • 1
  • 3

4 Answers4

2

You can simply String.join the strings together and print them. Like:

public class Foo {

    public static void main(String [] args) {
        System.out.println(String.join(" ",args));
    }

}

The first argument, the delimiter, is here " " (a string containing one space). Such that there is a space between two arguments.

Note that this program is almost identical to the echo program you see on a lot of operating systems.

Finally note that although this program does not contain a loop, the String.join definitely need some form of looping inside the method.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

Assuming you are using Java 8+, you can use a Stream and a Collector. Like,

String[] arg = { "Hi", "there" };
System.out.println(Stream.of(arg).collect(Collectors.joining(" ")));

which outputs (as I think you wanted)

Hi there
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

In java 8 you can use this

Arrays.asList(args).forEach(x -> System.out.print(x + " "));
-1

Override the Array toString method? You'd have to use a loop in there to get the desired result though.

jared
  • 473
  • 3
  • 16