Wrapper classes provide a way to use primitive data types (
int
, boolean
, etc..) as objects.Primitive data type | Constructors | Wrapper Class |
char | char | Character |
byte | byte, String | Byte |
short | short, String | Short |
int | int, String | Integer |
long | long, String | Long |
float | double, float, String | Float |
double | double, String | Double |
boolean | boolean, String | Boolean |
Putting the primitive value inside the object is called wrapping or boxing and taking out the value from object is called unwrapping or unboxing.
Methods:
- toString(); Whenever, we are printing reference variable, internally it calls toString() present in object class.
class Test{
public static void main(String[] args) {
Test t = new Test();
System.out.println(t);
System.out.println(t.toString());
Integer i = new Integer(100);
System.out.println(i);
System.out.println(i.toString()); //actual i.e. calls toString method implicitly
}
}
Output
com.cerotid.oo.principles.Test@15db9742
com.cerotid.oo.principles.Test@15db9742
100
100
toString() belongs to the object class and it returns class-name@hashcode (unique identification number of object generated by JVM to identify the object uniquely) but in all wrapper classes, toString() is overriding to returns the content of the all wrapper class object.
Example
Converting a primitive type to Wrapper object
public class Wrapper1 {
public static void main(String[] args) {
int num = 100;
Integer obj = Integer.valueOf(num);
System.out.println(num);
System.out.println(obj);
}
}
Output:
100
100
Example
Converting Wrapper class object to Primitive
package com.cerotid.methodconcept;
public class Wrapper1 {
public static void main(String[] args) {
Integer obj = new Integer(100); // 100 here is object value
int num = obj.intValue();
System.out.println(num);
System.out.println(obj);
}
}
Output:
100 (primitive)
100 (object)
No comments:
Post a Comment