Java Primitive Type Conversions

Introduction:

These are few of the way to convert int, double, string to each other.

In Eclipse create a new project then create a class called temp in src directory. In case if you use another folder just include that package name.

For Dr. java users just paste code and save the file. In both case make sure class name matches the file name otherwise it will not compile.

The process should be same for other IDE’s.


Double to String Conversion:

public class Temp {
	public static void main(String[] args) {

		/*
		 * Double to String
		 */

		// Technique 1:
		double d0 = 4.0;
		String s0 = d0 + "";
		System.out.println(s0);

		// Technique 2:
		double d1 = 4.1;
		String s1 = String.valueOf(d1);
		System.out.println(s1);

		// Technique 3:
		double d2 = 4.2;
		String s2 = Double.toString(d2);
		System.out.println(s2);

		// Technique 4:
		double d3 = 4.3;
		StringBuilder s3 = new StringBuilder();
		s3.append(d3);
		System.out.println(s3);

		// Technique 5:
		double d4 = 4.4;
		StringBuffer s4 = new StringBuffer();
		s4.append(d4);
		System.out.println(s4);
	}
}

 

Integer to String:

public class Temp {
	public static void main(String[] args) {

		/*
		 * Integer to String
		 */

		// Technique 1:
		int i0 = 0;
		String m0 = Integer.toString(i0);
		System.out.println(m0); 

		// Technique 2:
		int i1 = 1;
		String m1 = "" + i1;
		System.out.println(m1); 

		// Technique 3:
		int i2 = 2;
		String m2 = String.valueOf(i2);
		System.out.println(m2); 

		// Technique 4:
		int i3 = 3;
		StringBuilder m3 = new StringBuilder();
		m3.append(i3);
		System.out.println(m3);

		// Technique 5:
		int i4 = 4;
		StringBuffer m4 = new StringBuffer();
		m4.append(i4);
		System.out.println(m4);
	}
}

 

String to Double:

public class Temp {
	public static void main(String[] args) {

		/*
		 * String to Double
		 */

		// Technique 1:
		String k0 = "20.22";
		double n0 = Double.parseDouble(k0);
		System.out.println(n0);

		// Technique 2:
		String k1 = "20.53";
		Double n1 = Double.valueOf(k1);
		System.out.println(n1);
	}
}

 

String to Integer:

public class Temp {
	public static void main(String[] args) {

		/*
		 * String to Integer
		 */

		// Technique 1:
		String p0 = "20";
		int u0 = Integer.parseInt(p0);
		System.out.println(u0);

		// Technique 2:
		String p1 = "203";
		Integer u1 = Integer.valueOf(p1);
		System.out.println(u1);
	}
}
Advertisements