Lecture 05
Lecture 05
Lecture 05
Integer i1 = Integer.valueOf(42);
Integer i2 = Integer.valueOf(“42”);
Long n1 = Long.valueOf(42000000L);
Long n1 = Long.valueOf(“42000000L”);
Object => Value
Each wrapper class Type has a method typeValue to obtain
the object’s value:
Integer i1 = Integer.valueOf(42);
Boolean b1 = Boolean.valueOf(“false”);
System.out.println(i1.intValue());
System.out.println(b1.intValue());
=>
42
false
Why use wrapper classes ?
We know that in java whenever we get input
form user, it is in the form of string value so
here we need to convert these string values in
different datatype (numerical or fundamental
data), for this conversion we use wrapper
classes.
`
Example
class WraperDemo
{
public static void main(String[] args)
{
String s[] = {"10", "20"};
System.out.println("Sum before:"+ s[0] + s[1]); // 1020
int x=Integer.parseInt(s[0]); // convert String to Integer
int y=Integer.parseInt(s[1]); // convert String to Integer
int z=x+y;
System.out.println("sum after: "+z); // 30
}
}
Explanation of Example
In the above example 10 and 20 are store in
String array and next we convert these values
in Integer using "int x=Integer.parseInt(s[0]);"
and "int y=Integer.parseInt(s[1]);" statement
In "System.out.println("Sum before:"+ s[0] +
s[1]);" Statement normally add two string and
output is 1020 because these are String
numeric type not number.
Converting String data into fundamental or
numerical
We know that every command line argument of java program is
available in the main() method in the form of array of object of
string class on String data, one can not perform numerical
operation. To perform numerical operation it is highly desirable
to convert numeric String into fundamental numeric value.
Example
"10" --> numeric String --> only numeric string convert into
numeric type or value.
"10x" --> alpha-numeric type --> this is not conversion.
"ABC" --> non-numeric String no conversion.
"A" --> char String no conversion.
List of Wrapper Classes
Below table lists wrapper classes in Java API with constructor
details.
}
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller
type, then you need to perform explicit type casting.
Example
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}}