Convert int to string in Java
In this tutorial, you will learn how to convert integer data type to string data type in Java. We generally encounter such a problem when we are dealing with practical programming in Java where we need to convert the primitive data type to string or objects. We can convert primitive data types to Objects or Strings with the help of Wrapper Class.
Suppose you are given an integer and you want to convert it into a String, to convert the integer you have different methods to convert it into String. You simply need to write the value you want to convert in the method to get your desired String value.
Methods to convert int to string
To convert an integer to a string you need some pre-defined methods to get the string. Initially, you need to input the integer that you want to convert into a string. Then use the pre-defined methods to get the string.
String.valueOf() method
This is one of the easy and frequently used methods to convert an integer to a String. You simply need to write this method along with the integer like:
String s=String.valueOf(55);
Now this 55 will be a String rather than an integer and its length will be 2.
Integer.toString() method
This method is also the easiest and most widely used method to convert an integer to a string. What you need to do is simply write the method and in the bracket write the value that you want to convert into string.
String s=Integer.toString(988);
Converted String is 988 Length of the string is 3
Steps required:
- Input the integer you want to convert into a String.
- Use one of the predefined methods to get the String.
- Find the length of the string.
- Print the String and its length.
Java program to convert int to string:
public class Main { public static void main(String[] args) { int num1=546; int num2=7896; String s=Integer.toString(num1); //Conversion of Integer to String by step 2 String st=String.valueOf(num2); //Conversion of Integer to String by step 1 System.out.println("Converted Number 1 to String is "+s+" and length of the string is "+s.length()); System.out.println("Converted Number 2 to String is "+st+" and length of the string is "+st.length()); } }
Output of the above Solution is:
Converted Number 1 to String is 546 and length of the string is 3 Converted Number 2 to String is 7896 and length of the string is 4
Also read:
Leave a Reply