Every beginner in the programming world first encounters the println()
function, for example, in the classic “Hello World” program.
The main use of println()
in Java is to print messages to the computer screen (console).
Normally, you access it through System.out
β a standard output stream.
π So when you write:
System.out.println("Hello World");
You’re calling the println()
method on the out
object of the System
class.
System
is a final class in the java.lang
package, and out
is a static variable of the System
class. The type of out
is PrintStream
, and println()
belongs to the PrintStream
class.
This means that both out
and println()
are part of the PrintStream
type, which is why we can access the println()
method through the out
variable.
PrintStream
has many methods for printing messages, and println()
is one of them.
Now, let’s break down the word println()
to understand its meaning:
“ln” means “line” β it adds a new line after printing each message.
“print” means printing the message on the screen.
π check this : Java Main Method Example with Explanation and Output.
Different Variants of println()
You can pass different types of data to the println()
method, such as integers, characters, booleans, strings, and more.
The println()
method automatically converts all types of data into a String
format internally.
You donβt have to worry about the data type β println()
will handle it for you!
Type | Example |
---|---|
String | System.out.println("Hello Aitechray"); |
int | System.out.println(101); |
double | System.out.println(3.14); |
char | System.out.println('Z'); |
boolean | System.out.println(true); |
Object | System.out.println(new Object()); |
Example Code
public class PrintExample {
public static void main(String[] args) {
System.out.println("Learning Java"); // prints a String
System.out.println(42); // prints an int
System.out.println(3.1415); // prints a double
System.out.println('J'); // prints a character
System.out.println(true); // prints a boolean
}
}
Output
Learning Java
42
3.1415
J
true
All these different types will be printed smoothly because println()
is overloaded for different data types.
π Related Article :