Hey guys in this short blogpost, we will discuss about Java println()
and print()
with few easy to understand examples.
Overview
- Both
print()
andprintln()
methods are used to print message on to the console - The key difference here is,
println()
adds\n
at the end of the text, which indicates that move the cursor to the next line. Basically it adds new line after the text - where as,
print()
does not add\n
at the end of the text, meaning it does not move the cursor to the next line, it stays at the end of the text.
Examples
Consider the following example,
public class Test {
public static void main(String[] args) {
System.out.println("My name is Bushan");
System.out.print("I am from India");
}
}
In the above example, the first statement uses println()
method, which adds new line at the end, this is because the next statement which prints the text on to the new line.
Output
My name is Bushan
I am from India
Consider the following example,
public class Test {
public static void main(String[] args) {
System.out.print("My name is Bushan");
System.out.println("I am from India");
}
}
In the above example, the first statement uses print()
method, which does not add new line at the end, so the next statement which prints the text in the same line.
Output
My name is BushanI am from India
Consider the following example,
public class Test {
public static void main(String[] args) {
System.out.println("My name is Bushan");
System.out.print("I am from India");
System.out.println("I am software developer");
}
}
Output
My name is Bushan
I am from IndiaI am software developer
In the above example, the first statement adds \n
at the end of the text, so the next statement will print the text in the new line, whereas second statement uses print()
method, which does not add \n
at the end so the third statement will print in the same line.
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.