Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

conversion and casting

Status
Not open for further replies.

mn12

Programmer
Dec 22, 2002
52
0
0
IL
what is the difference between conversion and casting?

Thanks for your time!
 
Hello sedj,

I think this is eg. for casting:

Object o = session.getAttribute("abc");
Integer i = (Integer)o;
int ii = i.intValue();

and this is conversion eg.:

Object o = session.getAttribute("abc");
String s = +""o;
int i=Integer.parseInt(s)

Can you explain please when will I use each way?

Thank You!
 
The examples you show above are not good examples of how the two things might be different.

There might be a time when you want to save, hypothetically, several different types of variables into an array (maybe to return them back from procedure in one variable). Since arrays must be of one type, you make the array and Object array:

Code:
Object myArray[] = new Object[3]; //for example

To populate the array, you would have to CAST the variables to OBJECTS:

Code:
myArray[0] = (Object)myInteger;
myArray[1] = (Object)myString;
myArray[2] = (Object)(new Integer(myint));

When you retrieve these items later, if you want to use them AS their original variable types, you will have to CAST them back:

Code:
Integer myRetrievedInteger = (Integer)myArray[0];
String myRetrievedString = (String)myArray[1];
int myRetrievedin = ((Integer)myArray[2]).intValue();

What you refer to as CONVERT-ing is merely for when you have a String that you know is a number and you would like to do some mathematical or logical operation on it:

Code:
String two = "1";
String one = "2";
if(Integer.parseInt(two) < Integer.parseInt(one))
{
 String message = "What the heck is going on here!?!";
}

Follow?

There are other reasons one might want to cast objects, but I think the CONVERSION you are talking about is strictly related to using Strings as numbers.

'hope that helps.

--Dave
 
To translate LookingForInfo's reply into a brief definition:
You may cast from a general type to a more specific type.

You convert if there is a method to support this. (could be from .wav to .ogg or .jpg to .png or XY.z to Foo.bar too - not only String-Number).

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top