Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Object toString() Method

Java Object toString() Method

Java String ClassJava Object Class


The Object toString() method is used to return a string representation of the object.

Syntax


object.toString()

Parameters

Return Value

Returns a string representation of the object.

Default return format: the object's class name + @ + the hexadecimal string of the hashCode.

Example

The following example demonstrates the use of the toString() method:

Example

class

RunoobTest

{

public

static

void

main

(

String

[

]

args

)

{

//

toString() with Object

Object

obj1

=

new

Object

(

)

;

System

.

out

.

println

(

obj1

.

toString

(

)

)

;

Object

obj2

=

new

Object

(

)

;

System

.

out

.

println

(

obj2

.

toString

(

)

)

;

Object

obj3

=

new

Object

(

)

;

System

.

out

.

println

(

obj3

.

toString

(

)

)

;

}

}

The execution result of the above program is:


java.lang.Object@d716361
java.lang.Object@6ff3c5b5
java.lang.Object@3764951d

Output format description:

The Array class calls the toString() method:

Example

class

RunoobTest

{

public

static

void

main

(

String

[

]

args

)

{

//

toString() with array

//

Creating an Array

String

[

]

array

=

{

"

Google

"

,

"

Runoob

"

,

"

Taobao

"

}

;

System

.

out

.

println

(

array

.

toString

(

)

)

;

//

Returns a string representation of the array element values

//

Array inherits from the Object class, so it can use the toString() method directly

System

.

out

.

println

(

array

[

1

]

.

toString

(

)

)

;

//

Runoob

}

}

The execution result of the above program is:


Runoob

Java String ClassJava Object Class