Convert String to Other Data Types in Java

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.

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);
	}

}
i: 678
 

String to Long

You convert a string to a long number by calling the parseLong method.

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);
	}

}
lo: 123
 

String to Float

You convert a string to a float by calling the parseFloat method.

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);
	}

}
f: 6.78
 

String to Double

You convert a string to a double by calling the parseDouble method.

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);
	}

}
f: 6.78
 

String to Boolean

You convert a string to a boolean by calling the parseBoolean method.

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);
	}

}
bool1: true
bool2: false

Best Laptops for Programming