This post will discuss how to convert string to different primitive data types in Java
String to Int
You convert a string to a integer by calling the parseInt method.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
String s = "678";
int i = Integer.parseInt(s);
System.out.println("i: " + i);
}
}
Output:
i: 678
String to Long
You convert a string to a long number by calling the parseLong method.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
String s = "123";
long lo = Long.parseLong(s);
System.out.println("lo: " + lo);
}
}
Output:
lo: 123
String to Float
You convert a string to a float by calling the parseFloat method.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
String s = "6.78";
float f = Float.parseFloat(s);
System.out.println("f: " + f);
}
}
Output:
f: 6.78
String to Double
You convert a string to a double by calling the parseDouble method.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
String s = "6.78";
double d = Double.parseDouble(s);
System.out.println("d: " + d);
}
}
Output:
f: 6.78
String to Boolean
You convert a string to a boolean by calling the parseBoolean method.
Example:
package octopuscodes.com.demo;
public class Demo {
public static void main(String[] args) {
String s1 = "true";
boolean bool1 = Boolean.parseBoolean(s1);
System.out.println("bool1: " + bool1);
String s2 = "false";
boolean bool2 = Boolean.parseBoolean(s2);
System.out.println("bool2: " + bool2);
}
}
Output:
bool1: true
bool2: false