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

No comments:

Post a Comment