A2oz

How to Print Two Outputs in the Same Line in Java?

Published in Java Programming 1 min read

You can print two outputs in the same line in Java using the System.out.print() method instead of System.out.println(). The println() method automatically adds a newline character after each output, while print() does not.

Here's how:

public class PrintSameLine {
    public static void main(String[] args) {
        System.out.print("Hello ");
        System.out.print("World!");
    }
}

This code will output:

Hello World!

Here are some additional points to keep in mind:

  • Multiple outputs: You can print multiple outputs in the same line by calling System.out.print() multiple times.
  • Concatenation: You can also concatenate strings using the + operator and print the result using System.out.print().

Example:

System.out.print("The sum of 2 and 3 is " + (2 + 3));

This will output:

The sum of 2 and 3 is 5

Important Note:

  • Formatting: If you need to control the spacing between the outputs, you can add spaces within the strings or use System.out.printf() for formatted output.

Related Articles