Hi, I'm wondering how I can accomplish this.

Suppose I have the following array

String[] randomText = {"hi", "hello", "hey there"}

;

If I want to print the array I only know how to do so line by line.

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

Can someone point me in the right direction?

Dani AI

Generated

Short answer: was right that using System.out.print keeps output on one line, and ’s loop shows the manual way to avoid a trailing delimiter. If you prefer less boilerplate, use the standard library to build a single-line representation instead of hand-writing the loop.

A quick debug-friendly option (prints brackets and comma/space separators):

import java.util.Arrays;

System.out.println(Arrays.toString(randomText));

This prints the array as a single line like [hi, hello, hey there] (and returns "null" if the array reference itself is null). (docs.oracle.com)

If you want a plain joined string with your own delimiter (no brackets), use String.join:

System.out.println(String.join(" ", randomText)); // uses a space between elements

String.join concatenates elements with the delimiter (no brackets). Note: if the delimiter or the elements argument is null it throws NullPointerException; individual null elements are rendered as the four characters null. String.join is available since Java 1.8. (docs.oracle.com)

For more control (filtering nulls, mapping, or using streams) use Streams + Collectors.joining:

System.out.println(
  Arrays.stream(randomText)
        .filter(Objects::nonNull)                 // optional: skip nulls
        .collect(Collectors.joining(", "))        // custom delimiter
);

Collectors.joining is handy inside a stream pipeline when you need to transform or filter elements before concatenation. (docs.oracle.com)

Recommendation: for quick console output use Arrays.toString; for clean, delimiter-controlled output use String.join; for transformation/filtering before combining use streams + Collectors.joining. These approaches avoid the trailing-delimiter logic your manual loop must handle.

Recommended Answers

All 3 Replies

System.out.print("I will print on same line");

Yeah, what exactly do you mean? System.out.println() will print out each element on a new line.. if you use System.out.print(), then you can print each element on the same line..

for (int i = 0; i < randomText.length - 1; i++)
	System.out.print(randomText[i] + " ");
System.out.print(randomText[randomText.length - 1]);
//Prints out randomText[] on one line, delimited by spaces.

It was the System.out.print statement I guess, I missed that hehe.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.