PrintStream println(Object) method in Java with Examples


The println(Object) method in Java is a method of the PrintStream class that is used to print an object to the standard output stream and then terminate the line. The method takes an object as an argument and converts it into a string representation using the toString() method of the object. The resulting string is then printed to the standard output stream followed by a newline character.

Syntax:

public void println(Object obj)

Parameters: - obj: The object to be printed.

Return Value: - This method does not return any value.

Example 1: Printing a String using println(Object) method

String message = "Hello, World!";
System.out.println(message);

Output:

Hello, World!

Example 2: Printing an Integer using println(Object) method

int number = 42;
System.out.println(number);

Output:

42

Example 3: Printing a Custom Object using println(Object) method

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return "Name: " + name + ", Age: " + age;
    }
}

Person person = new Person("John Doe", 30);
System.out.println(person);

Output:

Name: John Doe, Age: 30


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.