Java Parsing Convert String to int in Java parseInt()

Java Parsing Convert String to int in Java parseInt()

Parsing operation in Java explained with parseInt() method in Question/Answer format.

1. What is parsing?

Casting (either implicit or explicit) is the process of converting one data type to another. But in all programming languages, sometimes a string value is required to convert into data type like int. In Java, String is class. Conversion of string to data type cannot be done with simple casting because string is an object and int is a data type; both are incompatible types. Conversion of string to data type requires special code (not casting) known as parsing. Conversion of string to data type is known as parsing because methods of type parseXXX() are used.

2. By the by, why parsing is required in a programming language?

It is all due to user’s input only. Programmer knows very well what data type should taken to fit the value. User may give an int value to a running Java program, but the program returns it as a string. Let us see some cases.

  1. Best example is command-line arguments. All the values passed from the command-line are converted into strings and then passed to args[] array by JVM. They are retrived by the Programmer as strings only and is necessary to convert into data types.
  2. Same case with TextField also. The value entered in TextField is returned as a string and requires parsing to be used as data type in program.

3. Give one example on parsing where string is converted to int data type with parseInt() method.

Output screenshot on parseInt()

parseInt() is a static method of Integer class that converts string to data type int.

Integer and Double are known as wrapper classes.

View all for 65 types of Data type Conversions

Leave a Reply

Your email address will not be published. Required fields are marked *