English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico de Java

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Tratamento de Exceções Java

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input output (I/O)

Java Reader/Writer

Java other topics

Java program to print the object of a class

Java Examples Comprehensive

In this tutorial, we will learn how to print the object of a class in Java.

To understand this example, you should understand the followingJava programmingSubject:

Example1:Java program to print objects

class Test {
}
class Main {
  public static void main(String[] args) {
    // Create an object of the Test class
    Test obj = new Test();
    //Print Object
    System.out.println(obj);
  }
}

Output Result

Test@512ddf17

No exemplo acima, criamos um objeto da classe Test. Quando imprimimos o objeto, podemos ver que a saída parece diferente.

Isso é porque, ao imprimir um objeto, é chamado o método toString() da classe do objeto. Ele formata o objeto no formato padrão. Veja o exemplo a seguir:

  • Test - Class Name

  • @ - Concatenate Strings

  • 512ddf17 - Object Hash Code

If you want to format the output in your own way, you need to override the toString() method in the class. For example,

class Test {
  @Override
  public String toString() {
    return "object";
  }
}
class Main {
  public static void main(String[] args) {
    //Create an object of the Test class
    Test obj = new Test();
    // Print Object
    System.out.println(obj);
  }
}

Output Result

object

In the above example, the output has changed. This is because here we have overridden the method toString() that returns a string from the object.

To understand the method toString() of the object class, please visitJava Object toString().

Java Examples Comprehensive