Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
ParseInt
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
In Java, the Integer class is part of the java.lang package and is automatically imported just like the String class. The parseInt() method is part of the Integer class. This method converts a String that only consists of numbers into an integer value while simultaneously assigning it to the primitive data type int. The syntax for this method is as follows, Integer.parseInt(stringname). Let's see how this method works in the code below.
ParseIntExample.java
package exlcode;
public class ParseIntExample {
public static String exampleVariableOne = "5666";
public static String exampleVariableTwo = "423";
public static int exampleVariableThree = Integer.parseInt(exampleVariableOne);
public static int exampleVariableFour = Integer.parseInt(exampleVariableTwo);
public static void main(String[] args) {
System.out.println("Integer exampleVariable of exampleVariableOne is " + exampleVariableThree);
System.out.println("Integer exampleVariable of exampleVariableTwo is " + exampleVariableFour);
}
}
The parseInt() method returns an int, not an object from the Integer class. This method only works if the String consists solely of numbers and no characters. If that is not the case, an error will be thrown and an integer will not be created.
The parseInt() function is extremely useful when dealing with user input or calculating numbers from text files. With this method, Java is saving the programmer time from creating long methods to convert strings into integers, by having an included parseInt() method.