[JAVA] The story of toString () starting with passing an array to System.out.println

I wanted to make an array and display its contents,

Convert the array to println as it is

int[] array = {1,2,3,4,5};

It seems that there are some beginners who pass the array as an argument to the standard output as it is. This output result (example) is


It becomes something that you don't understand. When I see this, I get asked "It doesn't work" ... Why is this happening?

What is System.out.println?

System → java.lang.System class out → Static variable of PrintStream type of System class That is, println is a ** PrintStream class method **. So if you take a look at PrintStream # println, there are some overloads. Most of them are overloads to support various primitive types, so to mention the others,

println(char[] x) println(Object x) println(String x)

These exist. These, including primitive types, output a string of arguments. In the case of char [], the characters of each element are connected and output, and String also outputs the contents as it is.

In the case of Object, the string ** that is the result of passing the ** argument to String.valueOf is output.


Returns a string representation of the Object argument. Parameters: obj - Object。 Return value: A string equal to "null" if the argument is null. Otherwise, the value of obj.toString () is returned.

The reason why it is not set to toString () as it is is because it is null safe. So what about that toString ()?


Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. This result should be concise and informative for human readability. Oracle recommends that you override this method in all subclasses. The toString method of class Object returns a string consisting of the name of the original class in which the object is an instance, the atmark character "@", and an unsigned hexadecimal representation of the object's hash code. That is, this method returns a string equal to the following values:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Return value: A string representation of this object.

It has become. Let's take a look at the first output here.


Do you understand? The string after this @ is the result of ʻInteger.toHexString (hashCode ()) `, that is, ** hexadecimal notation of hash code **. However, this number is meaningless to humans.

As the method description says, "This result should be concise and informative for humans to read. It is recommended that all subclasses override this method." This is the original usage of the method. In the base class Object, it is only decided that "if it is called for the time being, it will be output like this", and ** there is no information about what the contents are **.

String before @-what class of object?

If there is only one useful piece of information, it is the string ** before ** @. In this example, it's [I. What is this ...? If you think so, read the explanation again. The string before the @, which is the result of getClass (). GetName (). So what kind of specifications do you have?

It is difficult to explain or understand the return type Class of getClass () in detail, so for the time being, I would like you to recognize it as "an object that represents an instance of which class".


Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object as a String. If this class object represents a non-array type reference type, as specified in the Java (tm) Language Specification, then the binary name of the class is returned.

If this class object represents a primitive type or void, the returned name is a String equivalent to the Java language keyword corresponding to the primitive type or void.

When this class object represents a class of an array, the internal form of the name consists of one or more [characters, the name of the element type, which represents the nesting depth of the array. The encoding of the element type name is as follows:

Element type encoding boolean type Z byte B char C class or interface Lclassname; double D float F int I long J short S The class name of the class name or interface name is specified by the binary name of the class as in the example above.


String.class.getName() returns "java.lang.String" byte.class.getName() returns "byte" (new Object[3]).getClass().getName() returns "[Ljava.lang.Object;" (new int[3][4][5][6][7][8][9]).getClass().getName() returns "[[[[[[[I"

Simply put, it is a string that represents the type of the instance. Please pay attention to the case of array. The format is such that [ is lined up by the number of dimensions of the array, followed by the class name (L is inserted if it is not a primitive). In the last case of the example, since the array is 7-dimensional, 7 [ are lined up, followed by I indicating that it is an int array. In other words, [I was expressing that this object is a one-dimensional int array.

As mentioned above, the first seemingly incomprehensible output was output according to the specifications. Don't assume that it's a bug just because it's a string that doesn't make sense, but let's investigate the original behavior. By the way, if you want to output the contents of the array properly, pass it to Arrays.toString () (Arrays.deepToString () for a multidimensional array) to make it a string, or output it using a loop.

Recommended Posts

The story of toString () starting with passing an array to System.out.println
How to request by passing an array to the query with HTTP Client of Ruby
How to convert an array of Strings to an array of objects with the Stream API
A story addicted to toString () of Interface proxied with JdkDynamicAopProxy
Try to imitate the idea of a two-dimensional array with a one-dimensional array
[Swift5] How to get an array and the complement of arrays
A story of connecting to a CentOS 8 server with an old Ansible
Compare the elements of an array (Java)
Convert an array of strings to numbers
Get the type of an array element to determine if it is an array
The story of introducing Ajax communication to ruby
The story of raising Spring Boot 1.5 series to 2.1 series
The story of tuning android apps with libGDX
The story of adding the latest Node.js to DockerFile
[Swift] How to get the number of elements in an array (super basic)
The story of making an electronic New Year's card app with Vue.js + Rails
Rails6 I want to make an array of values with a check box
Speed comparison when the value side of Hash wants to retrieve all with array
Convert the array of errors.full_messages to characters and output
The story of migrating from Paperclip to Active Storage
Test the contents of an Excel file with JUnit
The story of making a reverse proxy with ProxyServlet
The story of an Illegal State Exception in Jetty.
Mandels to create an image of the Mandelbrot set
The story of making dto, dao-like with java, sqlite
The story of migrating a stray batch without an owner from EC2 to a Docker environment
The story of raising Spring Boot from 1.5 series to 2.1 series part2
A story packed with the basics of Spring Boot (solved)
How to retrieve the hash value in an array in Ruby
Initialization with an empty string to an instance of Java String type
How to add elements without specifying the length of the array
The story of pushing Java to Heroku using the BitBucket pipeline
Be sure to compare the result of Java compareTo with 0
[Apache Tomcat] The story of using Apache OpenWebBeans to enable CDI
[Java] How to search for a value in an array (or list) with the contains method
The story of fighting ubuntu errors 0x80370114, 0x80000000 to enable docker desktop with wsl2 on windows10 home
The basics of the process of making a call with an Android app
The story of the first Rails app refactored with a self-made helper
I tried to solve the problem of "multi-stage selection" with Ruby
I want to convert an array to Active Record Relation with Rails
I tried to build the environment of PlantUML Server with Docker
The story of Collectors.groupingBy that I want to keep for posterity
How to output the value when there is an array in the array
A story about hitting the League Of Legends API with JAVA
Cast an array of Strings to a List of Integers in Java
I tried to check the operation of gRPC server with grpcurl
A story that struggled with the introduction of Web Apple Pay
How to get the length of an audio file in java
A story that I was addicted to twice with the automatic startup setting of Tomcat 8 on CentOS 8
The story of introducing Gradle as a retrofit to an existing system that did not manage packages
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
[Java version] The story of serialization
Story of passing Java Gold SE8
The story of @ViewScoped consuming memory
The story I wanted to unzip
How to decorate the radio button of rails6 form_with (helper) with CSS
[Swift] Summary of how to remove elements from an array (personal note)
The story of making a game launcher with automatic loading function [Java]
[Java] How to turn a two-dimensional array with an extended for statement
The story of switching from Amazon RDS for MySQL to Amazon Aurora Serverless
How to access Socket directly with the TCP function of Spring Integration