Sie sind auf Seite 1von 11

In the OOPs concepts guide, we learned that object oriented programming is all about objects.

The
eight primitive data types byte, short, int, long, float, double, char and boolean are not objects.

A Wrapper class is a class whose object wraps or contains a primitive data types.. In other words, we
can wrap a primitive value into a wrapper class object.

Primitive Data types and their


Corresponding Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

Need of Wrapper Classes

1. They convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method (because primitive types are passed by
value).
2. The classes in java.util package handles only objects and hence wrapper classes help
in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.
5.

Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive types to the object of their


corresponding wrapper classes is known as autoboxing. For example – conversion of
int to Integer, long to Long, double to Double etc.

Unboxing: It is just the reverse process of autoboxing. Automatically converting an


object of a wrapper class to its corresponding primitive type is known as unboxing.
For example – conversion of Integer to int, Long to long, Double to double etc.

Example:

// Java program to demonstrate Wrapping and UnWrapping


// in Java Classes
class WrappingUnwrapping
{
    public static void main(String args[])
    {
        //  byte data type
        byte a = 1;
  
        // wrapping around Byte object
        Byte byteobj = new Byte(a);
  
        // int data type
        int b = 10;
  
        //wrapping around Integer object
        Integer intobj = new Integer(b);
  
        // float data type
        float c = 18.6f;
  
        // wrapping around Float object
        Float floatobj = new Float(c);
  
        // double data type
        double d = 250.5;
  
        // Wrapping around Double object
        Double doubleobj = new Double(d);
  
        // char data type
        char e='a';
  
        // wrapping around Character object
        Character charobj=e;
  
        //  printing the values from objects
        System.out.println("Values of Wrapper objects (printing as
objects)");
        System.out.println("Byte object byteobj:  " + byteobj);
        System.out.println("Integer object intobj:  " + intobj);
        System.out.println("Float object floatobj:  " + floatobj);
        System.out.println("Double object doubleobj:  " + doubleobj);
        System.out.println("Character object charobj:  " + charobj);
  
        // objects to data types (retrieving data types from objects)
        // unwrapping objects to primitive data types
        byte bv = byteobj;
        int iv = intobj;
        float fv = floatobj;
        double dv = doubleobj;
        char cv = charobj;
  
        // printing the values from data types
        System.out.println("Unwrapped values (printing as data types)");
        System.out.println("byte value, bv: " + bv);
        System.out.println("int value, iv: " + iv);
        System.out.println("float value, fv: " + fv);
        System.out.println("double value, dv: " + dv);
        System.out.println("char value, cv: " + cv);
    }

Output:
Values of Wrapper objects (printing as objects)
Byte object byteobj: 1
Integer object intobj: 10
Float object floatobj: 18.6
Double object doubleobj: 250.5
Character object charobj: a
Unwrapped values (printing as data types)
byte value, bv: 1
int value, iv: 10
float value, fv: 18.6
double value, dv: 250.5
char value, cv: a

We will discuss about only Integer and Character wrapper class.

Integer class

Constructors :

 Integer (int arg) : Constructs integer object representing an int value.


 Integer (String arg) : Constructs string object representing a string value.

A few Integer class methods (all methods are static methods):

1. toBinaryString() : java.lang.Integer.toBinaryString() method converts the


integer value of argument its Binary representation as a string.
Syntax

public static String toBinaryString(int arg)

Parameters
arg : integer argument whose Binary representation we want
Return
Binary representation of the argument.

2. bitcount() : java.lang.Integer.bitCount()
method converts the integer value of argument to Binary string and then returns
the no. of 1’s present in it.
Syntax

public static int bitCount(int arg)


Parameters
arg : integer argument whose no. of 1's bit we want
Return
no. of 1's bit present in the argument.

3. toHexString() : java.lang.Integer.toHexString() method converts the integer


value of argument its Hexadecimal representation as a string.
Syntax

public static String toHexString(int arg)


Parameters
arg : integer argument whose Hexadecimal representation we want
Return
Hexadecimal representation of the argument.

4. toOctalString() : java.lang.Integer.toHexString() method converts the integer


value of argument its Hexadecimal representation as a string.
Syntax

public static String toHexString(int arg)


Parameters
arg : integer argument whose Hexadecimal representation we want
Return
Hexadecimal representation of the argument.

5. parsedatatype() : java.lang.Integer.parse__() method returns primitive data


type of the argumented String value.
Radix (r) means numbering format used is at base ‘r’ to the string.
Syntax

public static int parseInt(String arg)


or
public static int parseInt(String arg, int r)
Parameters
arg : argument passed
r : radix
Return
primitive data type of the argumented String value.

// Java code explaining the Integer Class methods


// bitcount(), toBinaryString(), toHexString(), toOctalString(),
parse__()
import java.lang.*;
public class NewClass
{
    public static void main(String args[])
    {
        int x = 15, count1, y = 128, count2;
  
        // Use of toBinaryString() method
        System.out.println("Binary string of 16 : "
                           + Integer.toBinaryString(x));
        System.out.println("Binary string of 100 : "
                           + Integer.toBinaryString(y));
  
        // Use of bitCount() method
        count1 = Integer.bitCount(x);
        System.out.println("\n 1's bit present in 16 : "+count1);
  
        count2 = Integer.bitCount(y);
        System.out.println(" 1's bit present in 100 : "+count2);
  
        // Use of toHexString() method
        System.out.println("\nHexadecimal string of 16 : "
                           + Integer.toHexString(x));
        System.out.println("Hexadecimal string of 100 : "
                           + Integer.toHexString(y));
        System.out.println("");
  
        // Use of toOctalString() method
        System.out.println("Octal string of 16 : "
                           + Integer.toOctalString(x));
        System.out.println("Octal string of 100 : "
                           + Integer.toOctalString(y) + "\n");
  
        // Use of parseInt() method
        int i1 =Integer.parseInt("34");
        int i2 = Integer.parseInt("15",8);
        double d = Double.parseDouble("54");
  
        System.out.println(i1);
        System.out.println(i2);
        System.out.println(d);
    }
}

Output:

Binary string of 16 : 1111


Binary string of 100 : 10000000

1's bit present in 16 : 4


1's bit present in 100 : 1

Hexadecimal string of 16 : f
Hexadecimal string of 100 : 80

Octal string of 16 : 17
Octal string of 100 : 200

34
13
54.0

Character class

An object of type Character contains a single field, whose type is char.

 Creating a Character object :


 Character ch = new Character('a');

The above statement creates a Character object which contain ‘a’ of type char. There
is only one constructor in Character class which expect an argument of char data type.

 If we pass a primitive char into a method that expects an object, the compiler
automatically converts the char to a Character class object. This feature is called
Autoboxing and Unboxing.
 Note : The Character class is immutable like String class i.e once it’s object is
created, it cannot be changed.

A few Methods in Character Class :


1. boolean isLetter(char ch) : This method is used to determine whether the
specified char value(ch) is a letter or not. The method will return true if it is
letter([A-Z],[a-z]), otherwise return false. In place of character, we can also
pass ASCII value as an argument as char to int is implicitly typecasted in java.

Syntax :
boolean isLetter(char ch)
Parameters :
ch - a primitive character
Returns :
returns true if ch is a alphabet, otherwise return false

Example:

// Java program to demonstrate isLetter() method


public class Test
{
    public static void main(String[] args)
    {
        System.out.println(Character.isLetter('A')); 
          
        System.out.println(Character.isLetter('0')); 
          
     }
}

Output:

true
false

2. boolean isDigit(char ch) : This method is used to determine whether the


specified char value(ch) is a digit or not. Here also we can pass ASCII value as
an argument.

Syntax :
boolean isDigit(char ch)
Parameters :
ch - a primitive character
Returns :
returns true if ch is a digit, otherwise return false

Example:

// Java program to demonstrate isDigit() method


public class Test
{
    public static void main(String[] args)
    {
        // print false as A is character
        System.out.println(Character.isDigit('A')); 
          
        System.out.println(Character.isDigit('0')); 
          
    }
}
Output:

false
true

3. boolean isWhitespace(char ch) : It determines whether the specified char


value(ch) is white space. A whitespace includes space, tab, or new line.

Syntax :
boolean isWhitespace(char ch)
Parameters :
ch - a primitive character
Returns :
returns true if ch is a whitespace.
otherwise return false

Example:

// Java program to demonstrate isWhitespace() method


public class Test
{
    public static void main(String[] args)
    {
        System.out.println(Character.isWhitespace('A')); 
        System.out.println(Character.isWhitespace(' ')); 
        System.out.println(Character.isWhitespace('\n')); 
        System.out.println(Character.isWhitespace('\t')); 
          
        //ASCII value of tab
        System.out.println(Character.isWhitespace(9));
          
        System.out.println(Character.isWhitespace('9')); 
    }
}

Output:

false
true
true
true
true
false

4. boolean isUpperCase(char ch) : It determines whether the specified char


value(ch) is uppercase or not.

Syntax :
boolean isUpperCase(char ch)

Example:

// Java program to demonstrate isUpperCase() method


public class Test
{
  public static void main(String[] args)
  {
    System.out.println(Character.isUpperCase('A'));
    System.out.println(Character.isUpperCase('a'));
    System.out.println(Character.isUpperCase(65)); 
  }
}

Output:

true
false
true

5. boolean isLowerCase(char ch) : It determines whether the specified char


value(ch) is lowercase or not.

Syntax :
boolean isLowerCase(char ch)

Example:

// Java program to demonstrate isLowerCase() method


public class Test
{
  public static void main(String[] args)
  {
    System.out.println(Character.isLowerCase('A')); 
    System.out.println(Character.isLowerCase('a')); 
    System.out.println(Character.isLowerCase(97)); 
   }
}

Output:

false
true
true

6. char toUpperCase(char ch) : It returns the uppercase of the specified char


value(ch). If an ASCII value is passed, then the ASCII value of it’s uppercase
will be returned.

Syntax :
char toUpperCase(char ch)
Parameters :
ch - a primitive character
Returns :
returns the uppercase form of the specified char value.

Example:

// Java program to demonstrate toUpperCase() method


public class Test
{
   public static void main(String[] args)
   {
     System.out.println(Character.toUpperCase('a')); 
     System.out.println(Character.toUpperCase(97)); 
     System.out.println(Character.toUpperCase(48));
   }
}

Output:

A
65
48

7. char toLowerCase(char ch) : It returns the lowercase of the specified char


value(ch).

Syntax :
char toLowerCase(char ch)
Parameters :
ch - a primitive character
Returns :
returns the lowercase form of the specified char value.

Example:

// Java program to demonstrate toLowerCase() method


public class Test
{
   public static void main(String[] args)
   {
     System.out.println(Character.toLowerCase('A')); 
     System.out.println(Character.toLowerCase(65)); 
     System.out.println(Character.toLowerCase(48)); 
   }
}

Output:

a
97
48

8. toString(char ch) : It returns a String class object representing the specified


character value(ch) i.e a one-character string. Here we cannot pass ASCII
value.

Syntax :
String toString(char ch)
Parameters :
ch - a primitive character
Returns :
returns a String object.

Example:

// Java program to demonstrate toString() method


public class Test
{
   public static void main(String[] args)
   {
    System.out.println(Character.toString('x')); 
    System.out.println(Character.toString('Y')); 
   }
}

Output:

x
y

A few more methods:

9. static int charCount(int codePoint): This method determines the number of


char values needed to represent the specified character (Unicode code point).
10. char charValue(): This method returns the value of this Character object.
11. static int codePointAt(char[] a, int index): This method returns the code
point at the given index of the char array.
12. static int codePointAt(char[] a, int index, int limit): This method returns the
code point at the given index of the char array, where only array elements with
index less than limit can be used.
13. static int codePointAt(CharSequence seq, int index): This method returns
the code point at the given index of the CharSequence.
14. static int codePointBefore(char[] a, int index): This method returns the code
point preceding the given index of the char array.
15. static int codePointBefore(char[] a, int index, int start): This method
returns the code point preceding the given index of the char array, where only
array elements with index greater than or equal to start can be used.
16. static int codePointBefore(CharSequence seq, int index): This method
returns the code point preceding the given index of the CharSequence.
17. static int codePointCount(char[] a, int offset, int count): This method
returns the number of Unicode code points in a subarray of the char array
argument.
18. static int codePointCount(CharSequence seq, int beginIndex, int
endIndex): This method returns the number of Unicode code points in the text
range of the specified char sequence.
19. static int codePointOf(String name): This method returns the code point
value of the Unicode character specified by the given Unicode character name.
20. static int compare(char x, char y): This method compares two char values
numerically.
21. int compareTo(Character anotherCharacter): This method compares two
Character objects numerically.
22. static int digit(char ch, int radix): This method returns the numeric value of
the character ch in the specified radix.
23. static int digit(int codePoint, int radix): This method returns the numeric
value of the specified character (Unicode code point) in the specified radix.
24. boolean equals(Object obj): This method compares this object against the
specified object.
25. static char forDigit(int digit, int radix): This method determines the
character representation for a specific digit in the specified radix.
26. static byte getDirectionality(char ch): This method returns the Unicode
directionality property for the given character.

Das könnte Ihnen auch gefallen