Java Basic Knowledge (2) : Convert String to Integer, Double, or Float

Welcome to mil-notes. Today I'm going to talk about how to convert a string to integer, double, or float so we can do a mathematical operation to it. Okay, for example I have some string :

String a = "9";
String b = "10;

Then, I want to multiply them. Can I directly multiply them?. Let's take a look.


You can see, If I directly do a mathematical operation to them, compiler display an error message: bad operand types for binary operator '*'

So that's mean, we can't do a math operation directly to String. So what the solution?. The solution is, we should convert that String. We can convert to integer, double, or float. So, how we can do that?. Let's take a look.

String a = "9";
String b = "10";

int a1 = Integer.parseInt(a);
int b2 = Integer.parseInt(b);

System.out.println(a1*b1);

Result? let's take a look.. 

Yes! there's no problem and we can multiply them!. The key is on these code:
To convert to Integer: Integer.parseInt(String)
To convert to Double: Double.parseDouble(String)
To convert to Float: Float.parseFloat(String)

Let's try those code in our code:
Then we compile and run it:
Yes.., we successfully multiplying "String" by convert it first to Integer, Double, and Float. How about with others? I mean.., there are so many variable type that I don't discuss here. So? Do you interested with it? 

- FIN -

[DOWNLOAD SOURCE CODE]
  1. StringConvert.java

Comments