prometheuspk
prometheuspk

Reputation: 3815

Difference between Casting and Parsing

I have been working on some code for a while. for now i have just used the keywords as-is without actually understanding them. So here is my question

What is the difference between Casting and Parsing?

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"] as String--> is this Casting or parsing?

(String) UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"] -->is this Casting or parsing?

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"].ToString()
What is the difference bewtween x.ToString() and (String) x?

Upvotes: 4

Views: 9066

Answers (3)

Vijay
Vijay

Reputation: 1388

HERE IS THE DIFFERENCE:

char a = '3';
int number = 30;
if(number % (int) a == 0) System.out.println(true);
else System.out.println(false);

Above code will print false, because we are typecasting (just changing the data type).

if(number % Integer.parseInt(String.valueOf(a)) == 0) System.out.println(true);
else System.out.println(false);

Now above code will print true because we are parsing (logically setting) value.

SO WHAT IS THE DIFFERENCE (see this example):

int value = 11;
char a = (char) value;
System.out.println(a);  // result is -> 

Correct way :

int value = 11;
char a = String.valueOf(value).toCharArray()[0];
System.out.println(a);

Why because char can store only 1 character (ofcourse!).

SUMMARY - typecasting is just changing the datatype WHILE parsing means logically setting the values and generate expected result not like this .

Upvotes: 0

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

What is the difference between Casting and Parsing?

Those are unrelated.

Casting is changing the type of the variable.

Parsing is 'examining' the string and assigning its logical value to some variable.

(ADDITION: Well, they are related in a sense, because from far far away both can serve to 'convert' data, however, data is really converted ONLY in case of parsing)

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"] as String

is this Casting or parsing?

This is special kind of casting that will not fail if types aren't convertible (look here), but will get you null.

(String) UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"]

is this Casting or parsing?

This again is casting, but will throw an exception if expression isn't of type string.

What is the difference bewtween x.ToString() and (String) x?

x.ToString() will try to call ToString() on the object x.

(String) x will try to cast x to string, and will fail if x isn't string.

Upvotes: 12

Related Questions