Java Program to Print a New Line in String
Last Updated :
06 Jun, 2021
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, that is how to print a new line in a string using Java.
Methods:
There are many ways to print new line in string been illustrated as below:
- Using System.lineSeparator() method
- Using platform-dependent newline character
- Using System.getProperty() method
- Using %n newline character
- Using System.out.println() method
Let us discuss them individually in detail.
Method 1: Using System.lineSeparator() method
Example
Java
class GFG {
public static void main(String[] args)
{
String newline = System.lineSeparator();
System.out.println( "GFG" + newline + "gfg" );
}
}
|
Method 2: Using platform-dependent newline character.
Note: Here the new line character is “\n” for Unix and “\r\n” for Windows OS.
Example
Java
class GFG {
public static void main(String[] args)
{
System.out.println( "GFG" + '\n' + "gfg" );
}
}
|
Method 3: Using System.getProperty() method. Here this function uses the value of the system property “line.separator”, which returns the system-dependent line separator string.
Example
Java
class GFG
{
public static void main(String[] args)
{
String newline = System.getProperty( "line.separator" );
System.out.println( "GFG" + newline + "gfg" );
}
}
|
Output:
GFG
gfg
Method 4: Using %n newline character
Note: Here this newline character is used along with the printf() function.
Example
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
System.out.printf( "GFG%ngfg" );
}
}
|
Method-5: Using System.out.println() method.
Example
Java
class GFG {
public static void main(String[] args)
{
System.out.println( "GFG" );
System.out.println( "gfg" );
}
}
|
Share your thoughts in the comments
Please Login to comment...