Convert String to double in Java parseDouble()

Convert String to double in Java parseDouble()


Parsing operation with parseDouble() tutorial is given in Question/Answer format for easy understanding.

1. What is casting?

Casting is the process of converting one data type to another in a programmng language. Casting may be implict or explict.

2. Why casting is required in a programming language?

It is just due to user only. At runtime, what the value user inputs may not be in a format required by the program. For example, if you ask the user to enter the cost of mangoes, he enters 50. 50 is an integer value and user is very correct in his concept. But your program requires it as a double value because sometimes the mangoes value can be 50.5 rupees also. Then what to do? Simply convert int to double as 50 to 50.0 and use in the subsequent code.

3. Okay sir, then what is parsing in Java?

Casting (either implicit or explict) 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.

4. 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 done to use as a data type in program.

5. Give one example on parsing where string is converted to double data type using parseDouble() method?


parseDouble()
Output screenshot on parseDouble()

parseDouble() is a static method of Double class that converts string to data type double.

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 *