Languages

Java - how to print objects?

0 points
Asked by:
Jax-Cano
328

What is the easiest way to print objects in Java?

I tried to print object like an array using Arrays.toString() but I got output like this:

[User@7c75222b, User@4c203ea1]

My code example

User class:

public class User {
    private final String name;
    private final int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Example class with array of users:

import java.util.Arrays;

public class Example {

    private static int[] myArray = {1, 2, 3};

    public static void main(String[] args) {
        User[] users = {new User("Tom", 19), new User("Kate", 21)};

        System.out.println(Arrays.toString(users));  // <------ this doesn't work
    }
}
1 answer
0 points
Answered by:
Jax-Cano
328

You have to override the toString() method in User class so you can use this method to print an array of objects.

Practical example

User class:

public class User {
    private final String name;
    private final int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "User{ " +
                "name='" + name + '\'' +
                ", age=" + age +
                " }";
    }
}

Example class:

import java.util.Arrays;

public class Example {

    private static int[] myArray = {1, 2, 3};

    public static void main(String[] args) {
        User[] users = {new User("Tom", 19), new User("Kate", 21)};

        System.out.println(Arrays.toString(users));
    }
}

output:

[User{ name='Tom', age=19 }, User{ name='Kate', age=21 }]
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join