Part-14 Datatype conversions/Typecasting
we will discuss1. Implicit conversions
2. Explicit Conversions
3. Parse() and TryParse()
Data Type : Data Type casting is when you assign a value of one data type and convert to another data type/Type Casting is called Data Type.
Typecasting is divided into two parts.
- Implicit Conversion
- Explicit Conversion
Implicit Conversions : Iimplicit conversion when a smaller data type is converted into a larger data type .
Ex:- int i = 24;long j = i;
char -> int -> long -> float -> double
class ImplicitConvert
{
public static void main(String[] args)
{
int i = 57;
// automatic type conversion
long l = i;
// automatic type conversion
float f = l;
Console.WriteLine("Int value " +i);
Console.WriteLine("Long value " +l);
Console.WriteLine("Float value " +f);
}
}
Parse
Int.Parse(string str) method converts the string to integer
Let’s try to understand with a simple example as shown in below.
string val = "24";
int value = int.Parse(val);
In this case the string val, would be converted into integer without any error or exception; and that is what is intended with int.Parse() method.
- If string 'str' is null, then it will throw 'ArgumentNullException'
string str = null;
int value = int.Parse (str);
2 .If string 'str' is other than integer value, then it will throw 'FormatException'
Example:-
string str = "101.1";
int value = int.Parse (str);
3. If string 'str' represents out of integer ranges, then it will throw 'OverflowException'
Example:- string str = "9999999999999999999";
int value = int.Parse (str);
Int.TryParse contain two arguments first is string and another is int(out type). If the input string is integer it returns 2nd arguments(out type int). Else it returns first argument(string).
class Program
{
public static void main(String[] args)
{
Int.TryParse contain two arguments first is string and another is int(out type). If the input string is integer it returns 2nd arguments(out type int). Else it returns first argument(string).
class Program
{
public static void main(String[] args)
{
bool res;
int val;
string str = "12";
res = int.TryParse(str, out val);
Console.WriteLine("Value of i is " +res);
}
}
Output:-
Value of i is True
Output:-
Value of i is True