Java Data Types Solutions

Java Programmers do need to tackle tasks like type juggling and type casting. There are also many other small tasks they need to do while working with various data types. So it is important for Learning Java.

Convert String to Integer

Suppose you have a number but technically, its data type is set to a string like you want to "12345" to 12345. Let's create it as an example:

String bar = "12345";

You can see in the code above that the value is wrapped in quotes making its data type to string instead of an integer. Now let's convert this variable bar.

int foo = Integer.parseInt(bar);

Explanation: We created a variable named foo and set the data type to an integer with int key. We assigned the value to this variable by parsing it to an integer using Integer.parseInt Method.

Convert using try/catch

If you want to set a default number in case of Parsing failure, you can catch an exception and set the default value in Java as shown below.

String bar = "12345";

int foo;
try {
   foo = Integer.parseInt(bar);
}
catch (NumberFormatException e) {
   foo = 100;
}

Explanation: We have a variable here named bar with the value of 12345 as a string. We create a variable named foo and set its data type to integer by adding key int. Then we tried to parse a string to an integer in the try block. We set the default value of 100 to this variable in the catch block if the code in try block fails.

Leave a Reply

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