How to Turn an Integer Into a String Java
In this tutorial we will explore the different methods to convert Integer to String in Java along with interesting programming examples:
We will be covering the use of the following methods provided by the different Java classes to convert Int to String in Java:
- String concatenation
- String.valueOf()
- String.format()
- Integer.toString()
- Integer.String(int)
- StringBuilder append ()
- StringBuffer append ()
- DecimalFormat format ()
We will have a look at these methods in detail one by one.
=> Visit Here To Learn Java From Scratch
What You Will Learn:
- Covert Integer To String In Java
- #1) Using String Concatenation
- #2) Using String.ValueOf () Method
- #3) Using String.format () Method
- #4) Using Integer(int).toString() Method
- #5) Using Integer.toString(int) Method
- #6) Using StringBuilder Class Methods
- #7) Using StringBuffer Class Methods
- #8) Using DecimalFormat Class Methods
- FAQ About Converting Int To String In Java
- Conclusion
- Recommended Reading
Covert Integer To String In Java
In various scenarios, while developing any application or website, it is required to write a Java program to convert an integer to String.
Let's consider a scenario in our Java program, where after performing certain arithmetic operations on int variables, the result value received is an integer value. However, this value needs to be passed to some text field or text area field on the web page. In such cases, it is required to first convert this int value to String.
#1) Using String Concatenation
We have used Java plus '+' operator multiple times. This is very commonly used while printing any output on the console using the System.out.println() method.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using String concatenation * * @author * */ public class IntStringDemo1 { public static void main(String[] args) { // Assign int 25 to int variable length int length = 25; // Assign int 10 to int variable width int width = 10; // Multiply variable value length and width and assign to calculatedArea int calculatedArea = length * width; // concatenate calculatedArea to String "Variable calculatedArea Value --->" using plus '+' // operator // print variable int type calculatedArea System.out.println("Variable calculatedArea Value --->" + calculatedArea); } }
Here is the program Output:
Variable calculatedArea Value —>250
In the above program, we are concatenating the int calculated area with the String "Variable calculated area Value —>" as follows:
"Variable calculatedArea Value —>"+ calculatedArea
This converts int calculated area to String. Then this String is passed as an argument to System.out.println() method to print on the console as follows:
System. out .println("Variable calculatedArea Value —>"+ calculatedArea);
This prints the String on the console:
Variable calculatedArea Value —>250
#2) Using String.ValueOf () Method
The String class has static overloading methods of valueOf(). The purpose of these overloading methods is to convert arguments of primitive data types like int, long, float to String data type.
Let's have a look at the method signature for the int data type below:
public static String valueOf(int i)
This static method receives an argument of data type int and returns the string representation of the int argument.
Parameters:
i: This is an integer.
Returns:
The string representation of the int argument.
Let's understand how to use this String.valueOf() method using the following sample program. In this program, we are adding two numbers and will use the String.valueOf() method to convert the integer sumValue to String.
Given below is a sample program for your reference:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using String.valueOf() method * * @author * */ public class IntStringDemo2 { public static void main(String[] args) { // Assign int 300 to int variable x int x = 300; // Assign int 200 to int variable y int y = 200; // Add variable value x and y and assign to sumValue int sumValue = x + y; // Pass sumValue as an argument to String.valueOf() to convert // sumValue to String String sum = String.valueOf(sumValue); // print variable String sum System.out.println("Variable sum Value --->" +sum); } }
Here is the program Output:
Variable sum Value —>500
#3) Using String.format () Method
The String class has a static method to convert arguments to the specified format.
Let's have a look at the method signature below:
public static String format(String format, Object… args)
This is a String class static method that uses specified String format and Object arguments args and returns formatted String. In case of more arguments than format specifiers, arguments which are extra gets ignored. The number of arguments is variable, maybe zero.
Parameters:
format: format string
args: arguments which need to be formatted as per format string
Returns:
A string formatted as per the format string specified
Throws:
This method throws IllegalFormatException, NullPointerException.
Let's understand the use of this String.format() method.
Let's see the same program code of comparing 2 integer numbers. The program will print a larger number among 2 numbers. This program is using the String.format() method to convert the integer largeNumber to String.
A sample program is given below:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using String.format() method * * @author * */ public class IntStringDemo3 { public static void main(String[] args) { // Assign int 25 to int variable a int a = 25; // Assign int -50 to int variable b int b = -50; // Compare two numbers a and b int largeNumber = 0; if(a>b) { //if a is greater than b assign it to largeNumber variable largeNumber = a; }else { //if a is less than b then assign b to largeNumber variable largeNumber = b; } // Pass largeNumber as an argument to String.format() to convert // largeNumber to String String largeNumberString = String.format("|%5d|",largeNumber); // print variable String largeNumberString System.out.println("Variable largeNumber Value --->" + largeNumberString); } }
Here is the program Output:
Variable largeNumber Value —>| 25|
In the above sample code, we have used the String.format() method. We are using "|%5d|" as a format and passing int value largeNumber as below:
String largeNumberString = String.format("|%5d|",largeNumber);
String.format() returns formatted String as per the specified format '|%5d|' i.e. number specified in '||' with width 5 and right-justified i.e. | 25| and prints the same on the console.
System. out .println("Variable largeNumber Value —>" + largeNumberString);
So, the output on the console is Variable largeNumber Value —>| 25|
Now, let's see the integer to String Java conversion methods provided by the Integer class.
We will see the following Integer class methods:
-
-
- Integer(int).toString().
- Integer.toString(int)
-
#4) Using Integer(int).toString() Method
Integer class provides a method toString () to convert int to String.
Let's have a look at the method signature below:
public String toString()
This method converts the value to the signed decimal representation and returns a String object.
Let's understand the use of this Integer(int).toString() method.
Let's see the sample code to calculate the remainder of two numbers and print on the console using the Integer(int).toString() method to convert the integer remainderValue to its String representation.
Here is the sample program below:
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using Integer.toString() method * * @author * */ public class IntStringDemo4 { public static void main(String[] args) { // Assign int 33 to int variable dividentValue int dividentValue = 33; // Assign int 5 to int variable dividerValue int dividerValue = 5; // Calculate remainder of dividentValue and dividerValue using modulus int remainderValue = dividentValue % dividerValue; // Pass remainderValue as an argument to new Integer() to convert it to Integer object Integer remainderIntValue = new Integer(remainderValue); // Invoke toString() method on Integer object remainderIntValue convert it to String String remainder = remainderIntValue.toString(); // print variable String remainder System.out.println("Variable remainder Value --->" + remainder); } } }
Here is the program Output:
Variable remainder Value —>3
In above program, we have created instance of Integer class
new Integer(remainderValue);
and invoked toString () method on it as below:
String remainder = remainderIntValue.toString();
This statement returns the String representation of the Integer class object remainderIntValue.
#5) Using Integer.toString(int) Method
Integer also provides a static method toString () to convert int to String.
Let's have a look at the method signature below:
public static String toString(int i)
This static method returns the String object representation for the specified integer. Here, an argument gets converted to signed decimal representation and returns as a String. This is exactly the same as the overloaded method toString(int i, int radix ) where the radix value is 10.
Parameters:
i: This is an integer value which needs to be converted
Returns:
A string representation of the argument i having radix 10.
Let's understand the use of this Integer.toString(int i) method.
Let's write the sample program code which prompts the user to enter the number, calculate the square of the number, and print square on the console using the Integer.toString(int i) method to convert the integer squareValue to String.
Here is the sample program below:
package com.softwaretestinghelp; import java.util.Scanner; /** * This class demonstrates sample code to convert int to String Java program * using Integer.toString(int i ) method * * @author * */ public class IntStringDemo5 { private static Scanner scanner; public static void main(String[] args) { //Prompt user to enter input using Scanner and here System.in is a standard input stream scanner = new Scanner(System.in); System.out.print("Please Enter the number"); //Scan the next token of the user input as an int and assign it to variable x int x= scanner.nextInt(); //Calculate square of the number assigned to x int squareValue = x*x; // Pass squareValue as an argument to Integer.toString() to convert // squareValue to String String square = Integer.toString(squareValue); // print variable String square System.out.println("Variable square Value --->" + square); } }
Here is the program Output:
Please Enter the number 5
Variable square Value —>25
In the above program, we invoked the static method toString on Integer class by passing squareValue as an argument
String square = Integer.toString(squareValue);
This returns a String representation of the int value squareValue
Let's see some more ways i.e. utilizing StringBuffer, StringBuilder class methods.
StringBuffer class is used for appending multiple values to String. StringBuilder does the exact task, the only difference is that StringBuffer is thread-safe, but StringBuilder is not.
Recommended Reading => Java String Tutorial
#6) Using StringBuilder Class Methods
Let's see how to use StringBuilder methods to convert int to String in Java.
Here are the method signatures:
public StringBuilder append(int i)
This method appends the string representation of the int argument to the sequence.
Parameters:
i: This is an integer.
Returns:
This is a reference to the object.
public String toString()
This method returns a string representing the data in this sequence.
Given below is a sample program that calculates the average of integer values and illustrates the use of StringBuilder to convert the integer avgNumber to String.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using StringBuilder append() toString() method * * @author * */ public class IntStringDemo6 { public static void main(String[] args) { // Assign values to array of type int int[] numArray = {15,25,60,55}; //Find the array size int arrLength = numArray.length; int arrSum = 0; //Calculate addition of all numbers for(int i=0;i<arrLength;i++) { arrSum = arrSum+numArray[i]; } //Calculate average of all the numbers int avgNumber = arrSum/arrLength; // Pass avgNumber as an argument to StringBuilder.append() method StringBuilder strbAvg = new StringBuilder(); strbAvg.append(avgNumber); //Convert strbAvg to String using toString() method String average = strbAvg.toString(); // print variable String average System.out.println("Variable average Value --->" + average); } }
Here is the program Output:
Variable average Value —>38
In the above program, we used StringBuilder append () method and converted StringBuilder object to String using the toString () method
strbAvg.append(avgNumber);
String average = strbAvg.toString();
#7) Using StringBuffer Class Methods
Let's see the Java convert int to String way using the StringBuffer methods.
Here are the method signatures:
public StringBuffer append(int i)
This method appends the string representation of the int argument to the sequence.
Parameters:
i: This is an integer.
Returns:
This is a reference to the object.
public String toString()
This method returns a string representing the data in this sequence.
Let's have a look at the sample program below. We are using the lower Math.min() method to find the lower value among 2 int values and StringBuffer methods to convert the integer minValue to String.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using StringBuffer append() toString() method * * @author * */ public class IntStringDemo7 { public static void main(String[] args) { // Assign int 60 to int variable a int a = 60; // Assign int -90000 to int variable b int b = -90000; // Get lower value between int a and b using Math class method min() int minValue = Math.min(a, b); // Pass minValue as an argument to StringBuffer.append() method StringBuffer strbMinValue = new StringBuffer(); strbMinValue.append(minValue); //Convert strbMinValue to String using toString() method String minimumValue = strbMinValue.toString(); // print variable String miniumValue System.out.println("Variable miniumValue Value --->" + minimumValue); } }
Here is the program Output:
Variable miniumValue Value —>-90000
In above program, we used StringBuffer append () method and converted StringBuffer object to String using the toString () method
strbMinValue.append(minValue);
String minimumValue = strbMinValue.toString();
#8) Using DecimalFormat Class Methods
Java int can also be converted to String using the java.text.DecimalFormat Class method.
Here is the method signature of the format () method of the class.
NumberFormat. DecimalFormat extends NumberFormat class.
public final String format(long number)
This method returns the formatted string for the argument of datatype long
Parameters:
number: This is the value of data type long
Returns:
the formatted String
Given below is the sample program that illustrates the use of the DecimalFormat class method to convert the integer elementValue to String.
package com.softwaretestinghelp; import java.text.DecimalFormat; import java.util.Scanner; /** * This class demonstrates sample code to convert int to String Java program * using DecimalFormat format() method * * @author * */ public class IntStringDemo8 { private static Scanner scanner; public static void main(String[] args) { // Assign values to array of arrays of type int int[][] numArray = { {15,20,30,60}, {300,600,900} }; //Prompt user to enter input using Scanner and here System.in is a standard input stream scanner = new Scanner(System.in); System.out.println("Please Enter the array number"); //Scan the next token of the user input as an int and assign it to variable x int x= scanner.nextInt(); System.out.println("Please Enter the element number"); //Scan the next token of the user input as an int and assign it to variable y int y= scanner.nextInt(); int elementValue = numArray[x][y]; System.out.println(elementValue); // Pass "#" as format for DecimalFormat DecimalFormat formatElement = new DecimalFormat("#"); //Pass elementValue as an argument to format() method to convert it to String String element = formatElement.format(elementValue); // print variable String element System.out.println("Variable element Value --->" + element); } }
Here is the program Output:
Please Enter the array number
1
Please Enter the element number
1
600
Variable element Value —>600
In the above program, we used the DecimalFormat class format () method and converted int elementValue to String as below:
String element = formatElement.format(elementValue);
Thus, we have covered multiple methods of converting Java integer to a String value. In all sample programs, we have seen various scenarios where it is required to convert integer values to String values and the console output gets displayed.
So, for the purpose of converting an integer to String in Java, any of the methods demonstrated in the above sample codes can be used in your Java program.
Given below are some of the frequently asked questions about the int to String conversion.
FAQ About Converting Int To String In Java
Q #1) Can we convert int to String in Java?
Answer: Yes, in Java we can convert int to String.
We can convert int to String using the following methods:
- String concatenation
- String.valueOf ()
- String.format()
- Integer.toString()
- Integer.String(int)
- StringBuilder append ()
- StringBuffer append ()
- DecimalFormat format ()
Q #2) Can we type cast int to string?
Answer: Yes, we can convert int to String using the String and Integer class methods like String.valueOf(), Integer.toString() etc.
Q #3) How do we convert a string to a number?
Answer: String can be converted to a number of type int using the methods of Integer class like Integer.valueOf() and Integer.parseInt()
Conclusion
In this tutorial, we explored how to convert an integer to String in Java using the following methods:
- String concatenation
- String.valueOf ()
- String.format()
- Integer.toString()
- Integer.String(int)
- StringBuilder append ()
- StringBuffer append ()
- DecimalFormat format ()
We covered each method in detail and illustrated the use of each method with the help of a sample example.
=> Explore The Simple Java Training Series Here
How to Turn an Integer Into a String Java
Source: https://www.softwaretestinghelp.com/convert-integer-to-string-in-java/
0 Response to "How to Turn an Integer Into a String Java"
Post a Comment