If you want the printing to continue in the same line, you need to invoke a print()
method instead of a println()
method.
Also, since this resembles the echo
program, if you want it to be perfect, you want to have space between the strings, but not before the first or after the last.
With Java 4 and older:
public class Main {
public static void main(final String[] args) {
for (int i = 0; i < args.length; i++) {
if (i > 0)
System.out.print(" ");
System.out.print(args[i]);
}
System.out.println();
}
}
With Java 5-7 you could use for
each-loops, although in this special case that's not really better, it's just for completeness:
public class Main {
public static void main(final String... args) {
boolean isFirst = true;
for (final String arg : args) {
if (isFirst)
isFirst = false;
else
System.out.print(" ");
System.out.print(arg);
}
System.out.println();
}
}
With Java 8:
public class Main {
public static void main(final String... args) {
System.out.println(String.join(" ", args));
}
}
If you want your program to be fast - which would not be necessary in this case, this again is just for completeness - you would want to first assemble the String and then print it in one go.
With Java 4 and older:
public class Main {
public static void main(final String[] args) {
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++) {
if (i > 0)
sb.append(' ');
sb.append(args[i]);
}
System.out.println(sb);
}
}
With Java 5-7:
public class Main {
public static void main(final String... args) {
final StringBuilder sb = new StringBuilder();
for (final String arg : args)
sb.append(arg);
if (args.length > 0)
sb.setLength(sb.getLength() - 1); // skip last space
System.out.println(sb);
}
}
With Java 8 (no difference):
public class Main {
public static void main(final String... args) {
System.out.println(String.join(" ", args));
}
}
The code which I prefer:
import static java.lang.String.join;
import static java.lang.System.out;
public class Main {
public static void main(final String... args) {
out.println(join(" ", args));
}
}
Hope this helps, have fun with Java!