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 usingSystem.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.