Conversion of an integer into a string in java refers to the process of converting the value of an integer data type into the value of the data type string, the size of the data does not matter. This process is performed because there are some specific operations that can be operated only on a string data type.
An integer data type can be converted into a string data type in java using various methods, such as Integer.toString() Method, String.valueOf() Method and String Concatenation.
Why there is a need to convert an integer into a string in java?
While programming there can be multiple instances where one needs to convert an integer data type into a string data type for accessing, manipulating, and using data as an input for any function, following are the four ways to convert an integer into a string:
• String Concatenation: In Java, the + operator can be used to combine strings. Converting an integer to a string is the first step in concatenating an integer with a string.
• Input/output operations: Data is frequently kept as strings when it is read from a file or user input. You might need to convert an integer to a string when saving data to a file or displaying it on the screen.
• Data processing: In order to manipulate the data as a string and perform operations on it, such as sorting or searching, you may need to convert an integer to a string.
• Representation: In order to print a value to the console or show it in a GUI program, you may occasionally need to represent an integer as a string.
Eight Methods/Techniques for converting Integers to Strings in Java:
- Using the Integer.toString() Method
- Using the String.valueOf() Method
- Using String Concatenation
- Using String.format()
- Using Integer.String(int)
- StringBuilder append()
- StringBuffer append()
- DecimalFormat format()
1. Using the Integer.toString() Method
Using Java’s Integer.toString() method is the simplest approach to changing an integer into something of a string. This method accepts an integer as a parameter and outputs a string representation of the integer.
Here is an example of how to convert an integer in java to a string by using an Integer.toString() method:
//This class is used to convert an integer to a string
public class IntegerToString {
//The main method serves as the entry point of the program
public static void main(String[] args) {
//This declares an integer variable with the value 45
int number = 45;
//This converts the integer 'number' to its string representation and assigns it to the 'str' variable
String str = Integer.toString(number);
System.out.println("Integer: " + number);
//This line prints the text "String: " followed by the string representation of the 'number' variable
System.out.println("String: " + str);
}
}
Output:
Integer: 45
String: 45
2. Using the String.valueOf() Method
Applying Java’s String.valueOf() function is another way by which we can learn how to convert integer to string in java besides Integer.toString(). This function returns the string representation of an object or primitive type that it takes as input.
Here is an illustration of how to do it in Java using the String.valueOf() method:
//This class is used to convert an integer to a string
public class IntegerToString {
public static void main(String[] args) {
int number = 45;
//This converts the integer 'number' to its string representation
String str = String.valueOf(number);
//This line prints the text "Integer: " followed by the value of the 'number' variable
System.out.println("Integer: " + number);
//This line prints the text "String: " followed by the string representation of the 'number' variable
System.out.println("String: " + str);
}
}
Output:
Integer: 45 String: 45
3. Using String Concatenation
You can also convert an integer to a string in Java by concatenating it with an empty string. This will force Java to implicitly call the toString() method of the integer, which returns its string representation.
Here is an example of using string concatenation to convert an integer to a string in Java:
//This class is used to convert an integer to a string
public class IntegerToString {
public static void main(String[] args) {
int number = 42;
//This converts the integer 'number' to its string representation
String str = "" + number;
//This line prints the text "Integer: " followed by the value of the 'number' variable
System.out.println("Integer: " + number);
//This line prints the text "String: " followed by the string representation of the 'number' variable
System.out.println("String: " + str);
}
}
Output:
Integer: 42
String: 42
4. Using String.format()
String.format() is a static method in Java that is used to format a string, usually for printing purposes. It takes one or more arguments and replaces placeholders in the string with their values. The placeholders are specified using a format string, which is a string containing a mix of text and format specifiers.
public class IntStringformat {
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
String largeNumberString = String.format("|%5d|", largeNumber);
// print variable String largeNumberString
System.out.println("Variable largeNumber Value: " +
largeNumberString);
}
}
The output of this program will be:
Variable largeNumber Value: 25
5. Using Integer.toString(int) Method
The Integer.toString(int) method is a static method in the Integer class in Java that converts an int type value to a String type. This is a convenient method to convert an int to a String without having to manually create a StringBuilder or StringBuffer and append the value.
public class IntString {
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
String square = Integer.toString(squareValue);
// print variable String square
System.out.println("Variable square Value :" + square);
}
}
Output:
Please Enter the number 5
Variable square value: 25
6. Using StringBuilder Class Methods
The StringBuilder class in Java is a mutable (modifiable) sequence of characters. It provides a variety of methods for appending, inserting, deleting, and manipulating characters within the string. The StringBuilder class is an efficient alternative to the StringBuffer class for cases where you need to build strings dynamically and the string will be modified frequently.
public class IntegerString {
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);
}
}
Output:
Variable average Value: 38
7. Using StringBuffer Class Methods
The StringBuffer class in Java is similar to the StringBuilder class, but with the difference that it is thread-safe. This means that multiple threads can safely access a StringBuffer object simultaneously, without encountering synchronization issues. The StringBuffer class is less efficient than the StringBuilder class, as it has to synchronize access to the object across multiple threads. However, if you need to use a String-like object in a multithreaded environment, the StringBuffer class is a good choice.
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);
}}
Output:
Variable miniumValue Value: -90000
8. Using DecimalFormat Class Methods
The DecimalFormat class in Java is a class that is used to format decimal numbers. It provides methods for formatting decimal numbers as strings, and also for parsing strings into decimal numbers.
import java.text.DecimalFormat;
import java.util.Scanner;
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);
}
}
Output:
Please Enter the array number
1
Please Enter the element number
1
600
Variable element Value : 600
Best approach for converting int to string in java:
The easiest and most often used method for converting an integer to a string in Java is Integer.toString(). It is a static method that accepts an integer value as an input and returns a string that represents that integer. It is also a very efficient approach to convert small numbers because it only requires one function call.
The technique provides an easy and clear way to convert an integer to a string, and it is accessible in many programming languages, including Java. The function toString() { [native code] }() method can be used to represent any integer object as a string in a variety of circumstances. It can be invoked on any integer object.
Sample Problem for converting int to string in java:
Sample Problem 1
Write a program to calculate the area of an object by taking length and breadth as input with the use of the concatenation method.
public class IntStringDemo1 {
public static void main(String[] args) {
// Give value 25 to integer variable length
int length = 25;
// Assign int 10 to int variable width
int width = 10;
// Perform product between length and width
int calculatedArea = length * width;
// concatenate calculatedArea to String "Variable calculatedArea
Value-- -> " using plus ‘+’
// print variable int type calculatedArea
System.out.println("Variable calculatedArea Value --->" + calculatedArea);
}
}
Output:
Variable calculatedArea Value —>250
Sample Problem 2
Program to add two numbers with the use of String.valueOf() method to convert the integer sumValue to String.
public class IntStringDemo2 {
public static void main(String[] args) {
// Allocate integer value 300 to integer 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
String sum = String.valueOf(sumValue);
// print variable String sum
System.out.println("Variable sum Value - " + sum);
}
}
Output:
<p>Variable sum Value — 500</p>
Conclusion
In conclusion, there are generally three ways to convert an integer to a string in Java and those are using the string.valueof() method, Using the Integer.toString() Method, and Using String Concatenation, choosing one method over the other will depend on the specific use case and personal preference. Regardless of the method used, the result will be a string representation of the integer.
So, it’s recommended to try each and every method discussed above and use which has the least time complexity.