- Introduction
- Why is the conversion of int to string required in Java?
- Importance of string in Java Programming Language
- How Can We Convert Integers To String In Java?
- Conclusion
Introduction
It is a specialty of a string that can perform many operations like concatenation, finding a substring, etc., but it doesn’t happen in the case of an integer.
If there is a requirement for concatenation of two integers or finding out if an integer contains a digit or not, then this can be a difficult task if using only numeric operations. However, this can be made easy by converting an integer to a string.
Java permits the conversion of values from one data type to another under certain conditions. In Java, it is possible to convert a string variable to a numeric value and a numeric value into a string variable.
Why is the conversion of int to String needed in Java?
The requirement to write a Java program for converting an integer to a String arises in many scenarios while developing any application or website.
Let’s take a scenario in a Java program where after performing specific operations on an int variable, the result obtained as an integer value is required to be passed to some text field/text area field on the web page.
In these situations, firstly int value has to be converted to a String because the text area/field accepts only text value, then only the rest of the operations can be completed.
Importance of string in Java Programming Language
Strings are fundamental in Java, and Java programmers use them very frequently while developing a program. Java developers should have good knowledge of the String class to use them effectively. Some of the important aspects of the String are discussed below:
1. For termination Strings, do not use any null character.
There is no need for any null character in the String for termination. In the Java programming language, programmers can use the character array to represent a String. They can use the java.lang.String class of JDK.
2. Strings are not modifiable
Java programmers should know that String is immutable, meaning that it cannot be modified once the String is created. If programmers try to carry out modifications o the content of the string, a new string is created, and inclusion of new content is not at all possible in the existing String. We cannot override the functionalities of string.
3. Strings are placed in the String Pool
Strings are maintained in a separate String pool, a particular memory location available inside Java.
Whenever a String object is created by a programmer using String literal, Java Virtual Machine first checks the String pool. If JVM detects any similar content in the String pool, it returns that string and does not create a new object.
If the programmer creates an object using the new operator, Java Virtual Machine does not check the String pool.
4. Comparison of Strings is made using the equals method
For comparing two strings, the String class uses the equals() method in place of the equality operator. The String class overrides the equal method and offers content equality using characters, cases, and order.
5. Retrieving part of String in Java
The Substring() method is used by the Java programmers to retrieve only some part of the data in the String. The start and end index from the specified range has to be specified. Substring() methods are also backed by character arrays used by the original string. Sometimes this method can be risky if the String object is vast and the substring is very small.
6. Strings Support Operator Overloading
The Java programming language does not support the operator overloading concept. For concatenating two strings, Java programmers use the “+” operator. Programmers convert int, char, long, or double into String by using an empty string.
7. Removing White Spaces
Java programmers use the trim() method to remove additional spaces within the String. In case of any white spaces present within the string, the trim() method returns a new string after removing white spaces. The trim() method will return the same string if there are no white spaces. Java programmers can also use replace() and ReplaceAll() methods for replacing characters.
How Can We Convert Integers To String In Java?
This article provides insight into converting int to String in Java. There are many ways in Java to convert int to string. They are listed below:
Integer.toString(int)
It is a static method in the Integer class that returns a String object that represents the int parameter specified in the Integer.toString(int) function. This approach, unlike the others, can return a NullPointerException.
Syntax
There are two different expressions for Integer.toString() method:
- public static String toString(int i)
- public static String toString(int i, int radix)
Parameters
Let’s see the below-mentioned parameters of this method:
i: It denotes an integer that is to be converted.
radix: In Latin, the meaning of Radix is root. Radix refers to the base numbering system and uses a base 10 numbering system to represent the string. The radix value is an optional parameter; if it is not set for the decimal base system, the default value will be 10.
Return Value
For both the expressions, the returned value is a Java String representing the integer “i” argument. When the radix parameter is used, the respective radix specifies the returned string.
Example:
Converting Integer to String using Integer.toString().
public class IntToStringExample2
{
public static void main(String args[])
{
int i=200;
String s=Integer.toString(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is a string concatenation operator
}
}
Test it Now
Output:
300
200100
String.valueOf(int)
String.valueOf() is a static utility method of the String class that converts most primitive data types to their String representation. It includes integers. Because of the simplicity, using this method is considered a best practice.
Syntax
The syntax is expressed as:
public static String valueOf(int i)
Parameter
i: the integer which is to be converted
Return Value
This method returns the string representation of the int present in the argument.
Example:
Convert Integer to String using String.valueOf().
public class JavaExample
{
public static void main(String args[])
{
char name[] = {'J', 'O', 'H', 'N'};
String str = String.valueOf(name);
System.out.println(str);
}
}
Output:
JOHN
String.format()
In Java, String.format() is a newly developed alternative method that converts an Integer to a String object. The primary use of this method is to format a string, but we can also use it for conversion purposes.
Syntax
There are two types of expressions:
- public static String format(Locale l, String format, Object… args)
- public static String format(String format, Object… args)
Parameters
The following parameters are used in this method:
l: The local to be addressed during the formatting.
format: It is the format string in which a format specifier and sometimes a fixed text are included.
args: The arguments refer to the format specifiers set in the format parameter.
Return Value
According to the format specifier and the specified arguments, the output of this method is a formatted string.
Example:
Convert int to String using String.format().
public class IntToString
{
public static void main(String args[])
{
int i=400;
String s=String.format("%d",i);
System.out.println(s);
}
}
Test it Now
Output:
400
DecimalFormat
DecimalFormat class is a subclass of NumberFormat class and is used for formatting numbers using the specified formatting pattern. It has many features that are designed to parse and format numbers. Using this method, a number can be formatted up to 2 decimal places, up to 3 decimal places, using commas to separate digits.
Example
import java.text.DecimalFormat;
public class Main
{
public static void main(String args[])
{
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(111156789.123);
System.out.println(format);
}
}
Output:
111,156, 789.123
Suppose the user knows how to use the DecimalFormat method. In that case, this is the best method to convert Integer to String because it provides a level of control with the formatting. The number of decimal places and comma separators can be specified for better readability.
StringBuffer or StringBuilder
StringBuilder and StringBuffer are the classes used to combine multiple values into a single String.
StringBuffer is thread-safe which means it is synchronized, which means the method of StringBuffer can not be called by two threads simultaneously. But it is slower.
On the other hand, StringBuilder is faster but not synchronized, which means it is not thread-safe. The method of StringBuilder can be called by two threads simultaneously.
We can understand this with the help of an example given below that demonstrates these classes and explains how it works. Let’s have a look.
Example
Convert int to String using StringBuilder/StringBuffer
public class Test
{
public static void main(String a1[])
{
int number1 = -1234;
StringBuilder sb = new StringBuilder();
sb.append(number1);
String str1 = sb.toString();
System.out.println("Output result with StringBuilder= " + str1);
StringBuffer SB = new StringBuffer();
SB.append(number1);
String str2 = SB.toString();
}
}
Output:
Output result with StringBuilder= -1234
Output result with StringBuffer= -1234
The StringBuilder object is like a String object that can be modified and treated like a variable-length array with a sequence of characters.
The length and content of the sequence can be changed at any point through method invocations. For adding a new argument at the end of the string, StringBuilder implements the append() method.
In the end, it is crucial to call the toString() method to take the string representation of the data. Alternatively, the shorthand version of these classes can be used as well. Let’s see how to convert int to String in Java:
Example (a shorter version of the above program)
Converting int to String using StringBuilder/StringBuffer
public class Test
{
public static void main(String a1[])
{
String str1 = new StringBuilder().append(1234).toString();
System.out.println("Output result with StringBuilder= " + str1);
String str2 = new StringBuffer().append(1234).toString();
System.out.println("Output result with StringBuffer= " + str2);
}
}
Output
Output result with StringBuilder= -1234
Output result with StringBuffer= -1234
Conclusion
The most important thing is to call the toString() method to get the string representation of the data.
With this, we reached the end of this article, How to Convert int to String in Java. We have tried to cover one of the fundamental topics of Java to a great extent, converting an int or Integer to a String using tools shipped with the JDK. We hope you have understood all that has been shared with you in this article.
You should practice as much as possible to scale your experience to the maximum level and fulfilling your dreams of becoming a Java Developer.