![]() |
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 IntegerInput: "213456" Output: 213456 Input: "2134567" Output: 2134567 To implement this we have two methods as given below. 1. User ImplementationIn this method, we will write a user-defined function to convert the given string into an Integer. The idea is to iterate the string from start to end. First, we will declare an Integer variable result to store the Integer value. Then we will simply loop through the string and at each iteration we will multiply the current result by 10 and then add the current character to the result by converting the character to int. We will perform the following tasks to implement this algorithm.
Below is the Program to Convert a String to an Integer with User Implementation: Java
Output: 21456
Complexity of the above Program:
2. Using InBuilt Java functionIn 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.
Below is the Program to Convert a String to an Integer with User InBuilt Function: Java
Output: 21456
Complexity of the above Program:
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |