How to use InBuilt Java function In Java
In this method instead of writing custom logic we will use inbuilt method given by Integer class in java. The method is “Integer.parseInt()”. We will give the string to this method and it will give us the resulting int as the ans. Following are the steps to implement the same.
- Declare a Integer variable result.
- Pass the given string to the “Integer.parseInt()” function.
- Store it int the result variable.
- Return the result.
Below is the Program to Convert a String to an Integer with User InBuilt Function:
Java
public class Helper { public static Integer convertStringToInteger(String s) { // Parse the string to an integer Integer result = Integer.parseInt(s); return result; } public static void main(String[] args) { // Example input string String inp1 = "213456" ; // Convert the input string to an integer // Using the convertStringToInteger method Integer output = convertStringToInteger(inp1); // Print the result System.out.println(output); } } |
Output:
21456
Complexity of the above Program:
Time complexity: O(N)
Space complexity: O(1)
How to Convert a String Class to an Integer Class in Java?
String in Java is used to store the sequence of characters in Java. A string can contain a character, a word, a sentence, or a paragraph. Integer is a Wrapper class that is used to store Integer values in Java. The range of the Integer class is from -2,147,483,648 to 2,147,483,647 (-2^31 to 2^31 – 1).
In this article, we will learn to Convert a String to an Integer in Java.
Examples of Converting a String to an Integer
Input: "213456" Output: 213456 Input: "2134567" Output: 2134567
To implement this we have two methods as given below.