String Conversion and toString() in Java

By: Mashoud Emailed: 1728 times Printed: 2329 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String. valueOf( ) is overloaded for all the simple types and for type Object. For the simple types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf( ) calls the toString( ) method on the object. We will look more closely at valueOf( ) later in this chapter. Here, let's examine the toString( ) method, because it is the means by which you can determine the string representation for objects of classes that you create.

Every class implements toString( ) because it is defined by Object. However, the default implementation of toString( ) is seldom sufficient. For most important classes that you create, you will want to override toString( ) and provide your own string representations. Fortunately, this is easy to do. The toString( ) method has this general form:

String toString( )

To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class.

By overriding toString( ) for classes that you create, you allow the resulting strings to be fully integrated into Java's programming environment. For example, they can be used in print( ) and println( ) statements and in concatenation expressions. The following program demonstrates this by overriding toString( ) for the Box class:

// Override toString() for Box class.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions are " + width + " by " +
depth + " by " + height + ".";
}
}
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}

The output of this program is shown here:

Dimensions are 10 by 14 by 12.
Box b: Dimensions are 10 by 14 by 12.

As you can see, Box's toString( ) method is automatically invoked when a Box object is used in a concatenation expression or in a call to println( ).


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(20)


1. View Comment

This solve my problem to use toString() method. Thank you very much it is great!!!

View Tutorial          By: Simon at 2009-07-31 08:56:36
2. View Comment

This was very helpful! Thanks!!!

View Tutorial          By: Andreas Clausen at 2009-09-03 15:07:14
3. View Comment

Good example.

Leslie V
www.googlestepper.blogspot.com
www.scrollnroll.blogspot.com


View Tutorial          By: Leslie V at 2009-10-14 00:47:06
4. View Comment

Good and Effective example
thank you


View Tutorial          By: Perumal Naren at 2009-12-30 03:10:50
5. View Comment

it is unfair to leave this portal without thanking you.this example explained me the role of toString(). previously i had an idea that this method is only used to convert a non string variables to string variables.

View Tutorial          By: anil kumar at 2009-12-30 23:40:25
6. View Comment

that was useful to me, thank you so much .

View Tutorial          By: ahmed at 2010-01-11 15:59:42
7. View Comment

This example really works and help a lot me to disloge my confusion.

View Tutorial          By: Monu Kumar at 2010-03-30 09:26:23
8. View Comment

Yes, finaly toString start making sense to me, thanks a lot

View Tutorial          By: Ted at 2010-04-10 19:15:50
9. View Comment

I didnt get the use of public Sting toString().. I am a bigenner in java .. please send a solution with basic example

View Tutorial          By: Pradesh at 2010-05-06 05:38:23
10. View Comment

sir... i made a program just like that ... but there is an error "C:\Documents and Settings\ali\My Documents\Triangle.java:38: toString() in Triangle cannot override toString() in java.lang.Object; attempting to use incompatible return type
found : String
required: java.lang.String
public String toString()" <-- this is my problemm... it will not override...please elp...


View Tutorial          By: David at 2010-07-08 03:34:13
11. View Comment

good job.thanks

View Tutorial          By: bistrita at 2010-09-09 09:33:31
12. View Comment

Hi thanks for the example for overriding toString() function. Solved my problem.

View Tutorial          By: Reshma at 2011-05-11 10:46:08
13. View Comment

this article is excellent....solve all my doubt regarding tostring().thnx

View Tutorial          By: pramodk at 2011-07-18 14:22:18
14. View Comment

Thanks ,got useful information on toString().

View Tutorial          By: jaffar at 2011-08-01 10:15:04
15. View Comment

Thanks a lot. In a very Simple way you explained.

Shoaeb Cognizant..


View Tutorial          By: Shoaeb uddin at 2012-01-13 18:53:45
16. View Comment

Good stuff and good example to support it.

View Tutorial          By: tabrez at 2012-04-10 01:44:48
17. View Comment

this helped a lot!!!!

View Tutorial          By: karthik rk at 2012-09-04 16:32:25
18. View Comment

It is very useful for me guyzz......thanx.......:-)

View Tutorial          By: Rajesh at 2012-09-29 10:11:45
19. View Comment

Your explanation and example for toString() is great. It cleared my doubt. Thanks..

View Tutorial          By: Dinesh at 2012-10-19 08:29:13
20. View Comment

I will not contest. Certainly this is extremely important information about forString() will save my life on the exam. Do not use forString() nervously. It is hardly, but this clear explanation makes it easy to read. I need more tutorials in Java. Sir, I am proud to tell all my friends for String().

View Tutorial          By: Bangabee at 2012-11-10 18:17:40

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Mashoud
ThreadGroup Sample in Java
Converting Numbers to and from Strings using Java
Using toLowerCase( ) and toUpperCase( ) in Java
How to use regionMatches( ) in Java
startsWith( ) and endsWith( ) in Java
equals( ) Versus == in Java
compareTo( ) in Java
String Conversion and toString() in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
The Basic Structure of a Simple Java program
XML and Java - Parsing XML using Java Tutorial
What is Java?
Method Overloading (function overloading) in Java
Method Overriding in Java
How to use ArrayList in Java
FileReader and FileWriter example program in Java
Vector example in Java
Simple Port Scanner application using Java
append() in Java
Read from a COM port using Java program
Calendar - sample program in Java
Count number of vowels, consonants and digits in a String in Java
indexOf( ) and lastIndexOf( ) in Java
Most Emailed Articles (in Java)
Vector in Java - Sample Program
Configuring a DataSource in Tomcat
Applet Notinited : Applet xxxxxxxxxxxx notinited
Use of 'finally' in Java
Basics of Exception Handling in Java
Tomcat and httpd configured in port 8080 and 80
Calculate average sale of the week in Java
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
LinkedList in Java
Taking the size of an Array at runtime & generate random numbers to populate the Array
Getting Started with Java
Creating Users and Passwords with Tomcat using tomcat-users.xml
What is JasperReports?