Showing posts with label tostring. Show all posts
Showing posts with label tostring. Show all posts

Tuesday, 12 July 2022

Is Arrays override toString method in Java?

In Java, object.toString() method return the string representation of an object. toString() method is defined in ‘java.lang.Object’ class, subclasses can override this method and provide custom implementation.

 

What is the default implementation of toString method?

‘java.lang.Object’ class implement toString method like below.

public String toString() {
	return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

 

Is Arrays override toString method?

Arrays don't override toString() method, so when you call toString() method on array variables, you will get the default behaviour of Object.toString().

 


ArrayToString.java
package com.sample.app;

public class ArrayToString {

	// default implementation from java.lang.Object class.
	private static String toString(Object obj) {
		return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
	}

	public static void main(String[] args) {
		int[] arr1 = { 2, 3, 5, 7 };
		String[] arr2 = { "Hi", "there" };

		System.out.println(arr1.toString() + "\t" + toString(arr1));
		System.out.println(arr2.toString() + "\t" + toString(arr2));
	}

}

 

Output

[I@15db9742	[I@15db9742
[Ljava.lang.String;@6d06d69c	[Ljava.lang.String;@6d06d69c

 

 

Previous                                                 Next                                                 Home

Monday, 24 March 2014

toString : Return String representation of the object

public String toString()
Returns a string representation of the object. The default implementatin looks like below.

   public String toString() {
      return getClass().getName() + "@" + Integer.toHexString(hashCode());
   }

By default, toString method returns a string consisting of the name of the class of which the object is an instance, the at-sign character @, and the unsigned hexadecimal representation of the hash code of the object.

class Box{
 int width, height;

 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
 public static void main(String args[]){
  Box b1 = new Box(10, 20);
  System.out.println(b1);
 } 
}

Output
Box@5c09036e

When you call an object in println method, by default it calls the toString method of the particular object.

You can override the toString method to print custom message for an object. It is recommended that all subclasses override this method.

class Box{
 int width, height;

 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
 public String toString(){
  return "Box has width = " + width + " and height = " + height; 
 }
 
 public static void main(String args[]){
  Box b1 = new Box(10, 20);
  System.out.println(b1);
 } 
}

Output
Box has width = 10 and height = 20

Prevoius                                                 Next                                                 Home