Java, end of line with system.out.print

metraon picture metraon · Jan 17, 2013 · Viewed 62.7k times · Source

I have done some research concerning System.out.print() and System.out.println() and I discovered that System.out.println() add the end of line at the end of printed line.

System.out.println("Test");

Output only :

Test

but does not print end of the line.

System.out.print("Test");

Output only:

Test

but does not end the line and leave some place for other words or numbers, etc etc.

A more illustrative way is:

Test_____________________________________________ (All "blank" spots)

Is there a way to, force an end of line with System.out.print() directly after the word Test? Will the usage of % will remove the "blank" spots?

Or a way to code a function that will end the line after I used several System.out.print() to print a sentence?

For exemple :

System.out.print("Test);
System.out.print("Test);

will outpost a pure:

Test Test

like System.out.println("Test Test")

Answer

Fallup picture Fallup · Jan 17, 2013

You can append line separator, Note that it is platform dependant, so :

  • Windows ("\r\n")
  • Unix/Linux/OSX ("\n")
  • pre-OSX Mac ("\r")

If you want to get line separator depending on actual system you can just use :

  • System.getProperty("line.separator"); for pre Java 7
  • System.lineSeparator(); for Java 7

Then you just append your separator to your string in System.out.print, like :

  • System.out.print("Word\n");