views:

62

answers:

3

In .NET when I had a "value" that could exist as multiple types I could easily use a TypeConverter for switching between those types (currency types, xml data vs object representation, ect). In Java, I am not sure what the preferred way to handle this situation is. Is there a TypeConverter equivalent in Java?

A: 

Well you can typecast things... for example if you have a List object that contained strings.. you would grab a String from the list like this:

List aList = new List();
aList.add("Hello World);
String s = (String) aList.get(0);

If you are trying to convert a string to a number.. you would do something similar to this:

String aString = "200";
int i = Integer.Parse(aString);

I cheat when converting an integer to a string by doing this:

int i = 200;
String s = "" + i;
Boolean
+1  A: 

For someone from a .NET world it is going to be a surprise that there isn't one out of the box. This is because we have things like primitives (int, long) etc, their primitive-wrappers (Integer, Long etc), autoboxing from int to Integer when you require (this is from JDK 1.5).

So we the poor Java developers manually convert things (some examples given above by @Boolean) Also the endless hassles of using == operators when doing these. For ex: Autoboxed integers of upto 127 are cached.

public void testsimple() {
    Integer a = 124, b = 124, c = 500, d= 500;
    System.out.println(a == b); //prints true in JDK 1.6
    System.out.println(c == d); //prints false in JDK 1.6
}

If you are writing a huge app that needs too much data conversion you can write something on your own. Spring's "TypeConverter" interface can be a decent start.

Use this link http://imagejdocu.tudor.lu/doku.php?id=howto:java:how_to_convert_data_type_x_into_type_y_in_java if you have some trouble

Calm Storm