Java

How to use toString Method in java using NetBeans

toString Method: how to convert numbers to a string

Description:

Java has a “toString method” for converting numbers to strings. Please note that you need to “override” when using the toString method in your own class.

In this article we will learn

  • What is the toString method?
  • How to use the toString method
  • Precautions when using in your own class
  • How to override and use in your own class

From the basic contents such as, we will also explain the applied usage. This time, in order to learn these methods, I will explain how to use the “toString method” in an easy-to-understand manner!


What is the toString method?

The toString method is used to convert a numeric type etc. to a String type string. In the toString method, specify the variable you want to convert to a String type string in the argument.

As a return value, a String type string is returned.

How to use the toString method:

Here, we will explain how to convert a number to a string using the toString method. If you specify the value you want to convert to a string in the argument, the toString method will return the converted string as a return value.



Let’s check with the following program.

Output:

tostring method

In this program, the result of adding numbers with the + operator and the result of combining character strings are displayed respectively. An integer is a wrapper class of type int and is used to call the toString method.


Precautions when using toString method in your own class:

If you use the toString method in your own class, you need to be careful because it cannot be used as it is. In your own class, you need to override it to specify the string to display. Let’s check what happens if we do not override it with the following program.

output:

tostring method

Like this execution result, a character string that does not make sense is displayed. I’ll explain how to override the toString method to get the desired string later.


How to override the toString method in your own class:

To use the toString method in your own class, you need to override it. Let’s see how to override and get the desired string with the following program.

output:

tostring method

In this program, I override the toString method in my class to return “amount = 2000”. When overriding, annotate “@Override”.

Fawad

Shahzada Fawad

Related Articles

Leave a Reply

Back to top button