Home | FAQ | Contact me

Common Conversions in Java

A page of sample conversions is always a useful thing especially when you're arriving from a different language. The examples are encumbered a bit with some exception handling, but that's important in the real world too.

(The output from the test is below.)

package com.javahotchocolate.conversions;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Conversions
{
	public static void main( String[] args )
	{
		try
		{
			// convert a string to integer...
			Integer	x = Integer.parseInt( "46" );
			int		y = Integer.parseInt( "1573" );
			Integer	z = Integer.parseInt( "10010011", 2 );
			//Long	bad = Long.parseLong( "This will throw an exception." );

			System.out.println( "String to number: x = " + x + ", y = " + y + ", z = " + z );
		}
		catch( NumberFormatException e )
		{
			System.out.println( "String was not a number!" );
		}

		// convert a number to a string...
		String	s = "" + 1573;
		String	t = "" + 10.2;
		String	u = Integer.toString( 99 );
		System.out.println( "Number to string: s = " + s + ", t = " + t + ", u = " + u );

		// converting a string date to Date...
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

		try
		{
			Date today = df.parse( "5/12/2010" );
			//Date tomorrow = df.parse( "This will throw an exception." );
			System.out.println( "The specified date is " + df.format( today ) );
		}
		catch( ParseException e )
		{
			System.out.println( "String date was not in correct dd/MM/yyyy format!" );
		}

		// convert from Unicode to UTF-8 and back...
		try
		{
			String	unicode = "abc\u5639\u563b";
			byte[]	utf8    = unicode.getBytes( "UTF-8" );

			String	U = new String( utf8, "UTF-8" );
			System.out.println( "Unicode string: " + U );
		}
		catch( UnsupportedEncodingException e )
		{
			System.out.println( "Unicode string was bad!" );
		}
	}
}

Output from the test above...

String to number: x = 46, y = 1573, z = 147 Number to string: s = 1573, t = 10.2, u = 99 The specified date is 05/12/2010 Unicode string: abc??

More conversions...

This is nonsense, but it's occasionally necessary to understand how to move from a complex Java type like ArrayList to an array of objects (or ints).

import java.util.ArrayList;

public class ArrayListToArray
{
	public static void main( String[] args )
	{
		int	sum = 0;

		// create an array list...
		ArrayList al = new ArrayList();

		// add elements...
		al.add( new Integer( 1 ) );
		al.add( new Integer( 2 ) );
		al.add( new Integer( 3 ) );
		al.add( new Integer( 4 ) );
		al.add( new Integer( 5 ) );

		System.out.println( "contents of al : " + al );

		Object oa[] = al.toArray();

		// add up the array elements...
		for( int i = 0; i < oa.length; i++ )
			sum += ( ( Integer ) oa[ i ] ).intValue();

		System.out.println( "Sum is :" + sum );
	}
}