Java object print method

How can println print an object

How can the object «list» be used like it has been in the print statement? Don’t we need to use the object to access a method to print the list?

inside the List class the toString method is being overridden so that it will print all its contents rather than the address of the object.

well what does it mean for the the list object to be initialized to the Arraylist() function I thought nly constructors could be used to initialize an object? so shouldn it be List list= new List() ?

@Quirin no, List ‘s .toString() will print [ , then its element’s .toString() joined by a comma, then ]

new ArrayList IS a constructor that creates a List object. (ArrayList implements List). Read up on polymorphism

11 Answers 11

prinln(someObject) will print out whatever is implemented in someObject ‘s toString() method.

You can use toString() which is (supposed) to be implemented for all objects:

System.out.println(list.toString()) 

Note that you ought not to use the returned string as anything you can actually parse; it’s really for a visual representation. It also doesn’t need to uniquely represent the object.

you are, in fact, using the toString() method implicitly.

Returns a string representation of this collection. The string representation consists of a list of the collection’s elements in the order they are returned by its iterator, enclosed in square brackets («[]»). Adjacent elements are separated by the characters «, » (comma and space). Elements are converted to strings as by String.valueOf(Object).

When we pass any object to println() method, it will implicitly call that object’s toString() method. So, what is actually executed is

System.out.println( list.toString() ); 

ArrayList is inherited from the class java.util.AbstractCollection and that class has toString() method. So, in your case, that toString() should be executed.

That toString() method returns a string representation of this collection. The string representation consists of a list of the collection’s elements in the order they are returned by its iterator, enclosed in square brackets («[]»). Adjacent elements are separated by the characters «, » (comma and space). Elements are converted to strings as by String.valueOf(Object).

Источник

Print Objects in Java

  1. Understanding the Object Output
  2. Print Object in Java
  3. Arrays Objects
  4. How to print objects?
  5. Print Array Object
  6. Print Multi-Dimensional Array Object
  7. Print Collection Objects in Java
  8. Using Apache Commons Library
  9. Summary

This tutorial introduces how to print an object in Java and lists some example codes to understand the topic.

An object is an instance of a class, and we can use it to access the class properties and methods. But if we try to print an object using the System.out.println() method, we may not get the expected output. We often print the object properties to debug and to make sure that everything is working fine. In this tutorial, we will learn how to print object properties in Java.

Читайте также:  Python format default value

Understanding the Object Output

About Objects

  • Let’s try to understand what happens when we print an object. When we call the System.out.print() method, then the toString() method of the Object class is invoked.
  • As we know, all classes in Java extend the Object class. So the toString() method can be applied to any instance of any class.
  • This method returns a string that is composed of the class name and the hashcode of the object. These two are connected by the @ symbol.

Let’s create a new class and try to print its objects.

class Student   private String studentName;  private int regNo;  private Double gpa;  Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  > > public class Demo   public static void main(String[] args)    Student s1 = new Student("Justin", 101, 8.81);  Student s2 = new Student("Jessica", 102, 9.11);  System.out.println(s1);  System.out.println(s2);  > > 
Student@7a81197d Student@5ca881b5 

The first part of the output shows the class name ( Student in this case), and the second part shows a unique hashcode for the object. We will get different hashcode every time we run the above code.

Arrays Objects

An array is also an object in Java, and we don’t get its elements when trying to print an array to the console. Let’s run the following code and view its output.

public class Demo   public static void main(String[] args)    int[] integerArr = ;  double[] doubleArr = ;  char[] charArr = ;  String[] stringArr = ;  int[][] twoDimArray =   ,   >;  System.out.println("Integer Array:" + integerArr);  System.out.println("Double Array:" + doubleArr);  System.out.println("Char Array:" + charArr);  System.out.println("String Array:" + stringArr);  System.out.println("2D Array:" + twoDimArray);  > > 
Integer Array:[I@36baf30c Double Array:[D@7a81197d Char Array:[C@5ca881b5 String Array:[Ljava.lang.String;@24d46ca6 2D Array:[[I@4517d9a3 
  • The square brackets denote the dimension of the array. For 1-D-array, a single opening square bracket will be printed. For the 2-D array, we got two brackets.
  • The next character after the bracket denotes what is stored in the array. For the integer array, an I is printed. For the char array, the letter C is printed.
  • The L for the string array denotes that the array contains objects of a class. In such cases, the name of the class is printed next(java.lang.String in our case).
  • After the @ symbol, the hashcode of the object is printed.

How to print objects?

If we want to print the object and its properties in a different format, then we need to override the toString() method in our class. This method should return a string. Let’s override this method in our Student class and understand the process.

class Student   private String studentName;  private int regNo;  private Double gpa;  Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  >  //overriding the toString() method  @Override  public String toString()    return this.studentName + " " + this.regNo + " " + this.gpa;  > > 

Now, we can view the student’s name, registration number, and GPA when we print an object of this class.

public class Demo   public static void main(String[] args)    Student s1 = new Student("Justin", 101, 8.81);  System.out.print(s1);  > > 

We need to use the Arrays.toString() method to view the elements present in an array. Note that if we have an array of user-defined class objects, then the user-defined class should also have an overridden toString() method. This will make sure that the class properties are printed correctly.

import java.util.Arrays; class Student   private String studentName;  private int regNo;  private Double gpa;  Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  >  //overriding the toString() method  @Override  public String toString()    return this.studentName + " " + this.regNo + " " + this.gpa;  > > public class Demo   public static void main(String[] args)    Student s1 = new Student("Justin", 101, 8.81);  Student s2 = new Student("Jessica", 102, 9.11);  Student s3 = new Student("Simon", 103, 7.02);   //Creating Arrays  Student[] studentArr = s1, s2, s3>;  int[] intArr = 5, 10, 15>;  double[] doubleArr = 5.0, 10.0, 15.0>;  String[] stringArr = "Justin", "Jessica">;   System.out.println("Student Array: " + Arrays.toString(studentArr));  System.out.println("Intger Array: " + Arrays.toString(intArr));  System.out.println("Double Array: " + Arrays.toString(doubleArr));  System.out.println("String Array: " + Arrays.toString(stringArr));  > > 
Student Array: [Justin 101 8.81, Jessica 102 9.11, Simon 103 7.02] Intger Array: [5, 10, 15] Double Array: [5.0, 10.0, 15.0] String Array: [Justin, Jessica] 

For multidimensional array, use the deepToString() method instead of the toString() method and get the desired output to the console.

import java.util.Arrays; class Student   private String studentName;  private int regNo;  private Double gpa;   Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  >  //overriding the toString() method  @Override  public String toString()    return this.studentName + " " + this.regNo + " " + this.gpa;  > > public class Demo   public static void main(String[] args)    Student s1 = new Student("Justin", 101, 8.81);  Student s2 = new Student("Jessica", 102, 9.11);  Student s3 = new Student("Simon", 103, 7.02);  Student s4 = new Student("Harry", 104, 8.0);  Student[][] twoDimStudentArr =   s1, s2>,  s3, s4>  >;  System.out.println("Using toString(): " + Arrays.toString(twoDimStudentArr));  System.out.println("Using deepToString(): " + Arrays.deepToString(twoDimStudentArr));  > > 
Using toString(): [[LStudent;@7a81197d, [LStudent;@5ca881b5] Using deepToString(): [[Justin 101 8.81, Jessica 102 9.11], [Simon 103 7.02, Harry 104 8.0]] 

Collections like Lists , Sets , and Maps do not need any added method like Arrays.toString() . If we have properly overridden the toString() method of our class, then simply printing the collection will give us the desired output.

import java.util.ArrayList; import java.util.HashSet; class Student   private String studentName;  private int regNo;  private Double gpa;  Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  >  //overriding the toString() method  @Override  public String toString()    return this.studentName + " " + this.regNo + " " + this.gpa;  > > public class Demo   public static void main(String[] args)    Student s1 = new Student("Justin", 101, 8.81);  Student s2 = new Student("Jessica", 102, 9.11);  Student s3 = new Student("Simon", 103, 7.02);   //Creating an ArrayList  ArrayListStudent> studentList = new ArrayList<>();  studentList.add(s1);  studentList.add(s2);  studentList.add(s3);  //Creating a Set  HashSetStudent> studentSet = new HashSet<>();  studentSet.add(s1);  studentSet.add(s2);  studentSet.add(s3);  System.out.println("Student List: " + studentList);  System.out.println("Student Set: " + studentSet);  > > 
Student List: [Justin 101 8.81, Jessica 102 9.11, Simon 103 7.02] Student Set: [Simon 103 7.02, Justin 101 8.81, Jessica 102 9.11] 

Using Apache Commons Library

If you are working with the Apache commons library, then use the ToStringBuilder class of the Apache Commons library to format our object in different ways. We can use the reflectionToString() method of this class.

We can simply print the object class and hashcode and the values set for the properties using this method.

import org.apache.commons.lang3.builder.ToStringBuilder; class Student   private String studentName;  private int regNo;  private Double gpa;  Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  >  @Override  public String toString ()   return ToStringBuilder.reflectionToString(this);  > > public class Demo   public static void main(String[] args)    Student s = new Student("Justin", 101, 8.81);  System.out.print(s);  > > 
Student@25f38edc[gpa=8.81,regNo=101,studentName=Justin] 

If we want to omit the hashcode, then we can use the SHORT_PREFIX_STYLE constant. See the example below.

import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle;  class Student   private String studentName;  private int regNo;  private Double gpa;   Student(String s, int i, Double d)    this.studentName = s;  this.regNo = i;  this.gpa = d;  >  @Override  public String toString ()   return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);  > > public class Demo   public static void main(String[] args)    Student s = new Student("Justin", 101, 8.81);  System.out.print(s);  > > 
Student[gpa=8.81,regNo=101,studentName=Justin] 

If our class contains nested objects, we can use the RecursiveToStringStyle() method to print objects.

@Override  public String toString()    return ToStringBuilder.reflectionToString(this, new RecursiveToStringStyle());  > 

Summary

The Object class is the superclass of all classes in Java. The toString() method, which is invoked when printing an object, is implemented in the Object class. But this implementation doesn’t give any information about the user-defined class properties. To properly view these properties, we need to override our class’s toString() method. For arrays, we can directly use the toString() method or the deepToString() .

Related Article — Java Object

Copyright © 2023. All right reserved

Источник

Оцените статью