0% found this document useful (0 votes)
35 views34 pages

CAJP Lecture 8

Wrapper classes in Java allow primitive data types like int and float to be wrapped in objects so they can be passed by reference rather than by value, with each primitive type having its own wrapper class like Integer and Float; these wrapper classes are contained in the java.lang package and provide functionality to convert between primitive types and their corresponding wrapper class objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views34 pages

CAJP Lecture 8

Wrapper classes in Java allow primitive data types like int and float to be wrapped in objects so they can be passed by reference rather than by value, with each primitive type having its own wrapper class like Integer and Float; these wrapper classes are contained in the java.lang package and provide functionality to convert between primitive types and their corresponding wrapper class objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

Wrapper classes

java. Lang.
 Classes and interfaces defined by java. Lang.
 java.lang is automatically imported into all programs.
 It contains classes and interfaces that are fundamental to
virtually all of Java programming.
 It is Java’s most widely used package.
 java.lang includes the following classes:

Boolean Long StackTraceElement (Java 2,1.4)


Byte Math StrictMath (Java 2,1.3)
Character Number String
Class Object StringBuffer
ClassLoader Package (Java 2) System
Compiler Process Thread
Double Runtime ThreadGroup
Float RuntimePermission ThreadLocal (Java 2)
InheritableThreadLocal SecurityManager Throwable
Integer Short Void
2
Wrapper Class
 Each of Java's eight primitive data types has a class
dedicated to it.
Primitive Type Wrapper Class Primitive Type Wrapper Class

boolean Boolean float Float

byte Byte int Integer

char Character long Long

double Double short Short

 These are known as wrapper classes, because they


"wrap" the primitive data type into an object of that
class.
 These wrapper language are included into java.lang
package 3
Need of Wrapper classes
 The need of wrapper classes is the primitive
data types are always referred to as pass by
values to the methods and cannot be passed
directly by reference.
 For pass by reference we need to create an
object for one of these simple data types.
 These classes encapsulate simple data types
within classes. Thus they are commonly
referred to as Wrapper classes
4
 Number class :
The abstract class Number defines a super class
which is implemented by the classes that wraps the
numeric values.
Show in following hierarchy:
Object Character

Boolean
Number

Byte Integer Float

Short Long Double


5
Following table shows the simple data types and
their corresponding wrapper class types

Wrapper classes for converting simple types


Simple type Wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
6
Float Wrapper class
 Float is a wrapper class for floating
point values.
 Different constructor:
Float (float f)
Float (double d)
Float (String s) throws NFE

7
Float Wrapper class
Different constructor
public class JavaFloatExample {
  public static void main(String[] args) {
  //create a Float object using one of the below given constructors
  //1. Create an Float object from float primitive type
float f = 10.10f;
Float fObj1 = new Float(f);
System.out.println(fObj1);
  //2. Create an Float object from double primitive type
double d = 10.10;
Float fObj2 = new Float(d);
System.out.println(fObj2);
/* 3. Create and Float object from String. Please note that this method can
  throw NumberFormatException if string doesnt contain parsable number.  */
Float fObj3 = new Float("25.34");
System.out.println(fObj3);
  }}
8
/*Java Float compare example
This example shows how to compare a Float object with other
Float object, Float with an Object, or two float primitive values
using methods provided by
java.lang.Float class.*/
 public class JavaFloatCompareExample {
  public static void main(String[] args) {
float f1 = 5.35f;
float f2 = 5.34f;
int i1 = Float.compare(f1,f2);
  if(i1 > 0){
System.out.println("First is grater"); // i1 = ?
}else if(i1 < 0){
System.out.println("Second is grater");
}else{
System.out.println("Both are equal");
}
Float fObj1 = new Float("5.35");
Float fObj2 = new Float("5.34");
int i2 = fObj1.compareTo(fObj2);
  if(i2 > 0){
System.out.println("First is grater"); //
}else if(i2 < 0){
System.out.println("Second is grater");
}else{
System.out.println("Both are equal");
} } } 9
Convert float to Float object Example
 This example shows how a float primitive value can be
converted to a Float object

public class JavafloatToFloatExample {


  public static void main(String[] args) {
float f = 10.56f;
  // Use Float constructor to convert float primitive type to a Float object.
    Float fObj = new Float(f);
System.out.println(fObj);
  }
}
 
/*
Output of the program would be
10.56
*/

10
/*  Convert Float object to String object.
  This example shows how a Float object can be
converted into a String object.*/
public class floattostring {
public static void main(String[] args) {
Float fObj = new Float(10.25);
//use toString method of Float class to convert Float into String.

String str = fObj.toString();


System.out.println("Float converted to String as " + str);

String str1 = Float.toString(fObj);


System.out.println("Float converted to String as " + str1);

/*
Output of the program would be
Float converted to String as 10.25
*/

11
/* Convert Float to numeric primitive data types example
    - Convert Float to byte
  - Convert Float to short
  - Convert Float to int
  - Convert Float to float
  - Convert Float to double*/

 public class JavaFloatToNumericPrimitiveTypesExample {


 public static void main(String[] args) {
 Float fObj = new Float("10.50");
//use byteValue method of Float class to convert it into byte type.
byte b = fObj.byteValue();
System.out.println(b);  //10
//use shortValue method of Float class to convert it into short type.
short s = fObj.shortValue();
System.out.println(s);  //10
//use intValue method of Float class to convert it into int type.
int i = fObj.intValue();
System.out.println(i);  //10
//use floatValue method of Float class to convert it into float type.
float f = fObj.floatValue();
System.out.println(f); //10.5
//use doubleValue method of Float class to convert it into double type.
double d = fObj.doubleValue();
System.out.println(d); //10.5
 }}
12
 
/*Java Float isInfinite example
This example shows how to use isInfinite() method of the Float
class.*/

public class JavaFloatIsInfiniteExample {


public static void main(String[] args) {
/*
boolean isInfinite(float) static method checks whether the agrument primitive
float value is infinite number or not.
It return true if the specified argument is infinite value, false otherwise.
*/
float f = (float) 1/0;
boolean b1 = Float.isInfinite(f);
System.out.println(b1); //true
/*
boolean isInfinite() instance method checks whether the Float object
is infinite number or not.
It return true if the object is infinite value, false otherwise.
*/
Float fObj = new Float(f);
boolean b2 = fObj.isInfinite();
System.out.println(b2); //true
}
}

13
boolean equals(object o)
It returns true if invoking float object is equivalent to the object ‘o’

is also float object

public class booleanequals {


public static void main(String[] args) {
Float f1 = new Float(10.25);
Float f2 = new Float(10.25);
// Use Float constructor to convert float primitive
type to a Float object.
boolean b = f1.equals(f2);
System.out.println(b);
}
}

14
/* Java Float isNaN method example
  This example shows how to use isNaN()
method of the Float class. */

public class JavaFloatIsNaNExample {


  public static void main(String[] args) {
  float f = (float) Math.sqrt(-10);
boolean b1 = Float.isNaN(f);
System.out.println(b1); //true
Float fObj = new Float(f);
boolean b2 = fObj.isNaN();
System.out.println(b2); //true
}
}

15
Wrapper classes
2. Double wrapper class :-
Constructor are:
 Double (float f)
 Double (double d)
 Double (String S) throws NFE

All the methods are SAME AS Float

16
Wrapper classes
3. Byte Wrapper class
Constructors are:
 Byte (byte b)
 Byte (String S) throws NFE
4. Integer Wrapper class
Constructors are:
 Integer (int i)
 Integer (String S) throws NFE
17
Wrapper classes
5. Long Wrapper class
Constructors are:
 Long (long l)
 Long (String S) throws NFE
6. Short Wrapper class
Constructors are:
 Short (short s)
 Short (String S) throws NFE
18
Wrapper classes
 All the typecasting methods are same
as Float.
 isIfinite and isNaN are not supported by
last four.
 All remaining method replace the
primitive and nonprimitive data type
with the respective class.

19
Converting Numeric Strings to Primitive
Numbers using Parsing Method

 int i = Integer.parseInt(str)
Converts string to primitive integer.
 long l = Long.parseLong(str)
Converts string to primitive long.

Note: parseInt() and parseLong() methods throw a


NumberFormatException if the value of the str does not
represent an integer.

20
Converting Numeric Strings to Primitive
Numbers using Parsing Method (Example)
class i {
public static void main(String[] args) {
int i ;
long j;
String str = "10";
String str1 = "100";
i= Integer.parseInt(str);
j= Long.parseLong(str1);

System.out.println(str);//10
System.out.println(i);//10
System.out.println(j);//100
}
}

21
Integer Wrapper Class
 Static int parseInt(String s, int r)
 It returns an int value specified by ‘s’
using the specified radix ‘r’.
 By default the value of r = 10.
i.e. Indicates decimal value.
 The ‘r’ can be 2, 8, 16 for different
representation

22
Integer Wrapper Class
 Static String toBinaryString(int i) :
It returns a string that contains binary
equivalent of i.
 Static String toOctalString(int i) :
It returns a string that contains Octal
equivalent of i.
 Static String toHexString(int i) :
It returns a string that contains Hexadecimal
equivalent of i.

23
Example
class conversion {
public static void main(String[] args) {
//declare string containing binary number
String strBinaryNumber = "111000";
int decimalNumber = Integer.parseInt(strBinaryNumber,2);
System.out.println("Binary number converted to decimal number");

System.out.println("Decimal number is : " + decimalNumber); // 56

System.out.println("Decimal number converted to Binary number");

String strBinaryNumber1 = Integer.toBinaryString(decimalNumber);

System.out.println("Binary value of " + decimalNumber + " is " + strBinaryNumber1);


}}

24
Boolean Wrapper class
 Boolean is very thin wrap class which wraps
the boolean values.
 It is useful when we want to pass boolean
variable by reference
 Constants: True False
 Constructor:
 Boolean (boolean b)
 Boolean (String s)

Where ‘b’ and ‘s’ either true or false

25
Boolean Wrapper class methods:
 boolean booleanValue
It returns the primitive boolean value of the boolean
object.
 boolean equals (Object o)
If the values of two boolean objects are same then it
returns true.
 String toString()
It converts boolean object into string.
 Static string toString (boolean b)
It converts primitive boolean into string
 Static Boolean valueOf (String S)
It returns true if s = “true” else it returns False

26
Character Wrapper class
 Constructor : Character (char ch)
‘ch’ specifies a character that will be
wrapped by a character object.
Eg:
Character ch = new Character ('A');

27
Character Wrapper class methods
 char charValue()

It returns a primitive char value of the character object.


Eg: char c = ch.charvalue(); //A

 toString()

Converts the character as a string object.


Eg:String s = c.toString ();

28
Character Wrapper class methods
 boolean equals (object o)
If values of two char objects are same it returns true.

 int compareTo(object ch)


It return 0 if invoking object is equal to ‘ch’ object. –ve if invoking object
is lower than ‘ch’ object else returns +ve.

Character c1 = new Character ('A');


Character c2 = new Character ('B');
Character c3 = new Character ('A');
System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2)); //-1
System.out.println ("c1.equals (c2): " + c1.equals (c2)); //False
System.out.println ("c1.equals (c3): " + c1.equals (c3)); //True

29
Character Wrapper class methods
 boolean isLetter(char ch)
Returns true if passed character is really a character.
Eg:
System.out.println( Character.isLetter('c')); //True
System.out.println( Character.isLetter('5')); //false

 boolean isDigit(char ch)


Returns true if passed character is really a digit.
Eg:
System.out.println( Character.isDigit('c')); //false
System.out.println( Character.isDigit('5')); //true

30
Character Wrapper class methods
 boolean isUpperCase(char ch)
Returns true if passed character is really an uppercase.
Eg: System.out.println( Character.isUpperCase('c')); //false
System.out.println( Character.isUpperCase('C')); //true
System.out.println( Character.isUpperCase('\n')); //false
System.out.println( Character.isUpperCase('\t')); //false

 boolean isLowerCase(char ch)


Returns true if passed character is really an lowercase.
Eg: System.out.println( Character.isUpperCase('c')); //true
System.out.println( Character.isUpperCase('C')); //false
System.out.println( Character.isUpperCase('\n')); //false
System.out.println( Character.isUpperCase('\t')); //false 31
Character Wrapper class methods

char toUpperCase(char ch)
Returns the uppercase form of the specified char value.

char toLowerCase(char ch)
Returns the lowercase form of the specified char value.
Eg: System.out.println( Character.toUpperCase('c')); //C
System.out.println( Character.toLowerCase('C')); //c

32
Character Wrapper class methods
 boolean isWhitespace(char ch)
The method determines whether the specified char value is a
white space which includes space, tab or new line.

Eg: System.out.println( Character.isWhitespace('c')); //false


System.out.println( Character.isWhitespace(' ')); //true
System.out.println( Character.isWhitespace('\n')); //true
System.out.println( Character.isWhitespace('\t')); //true

33
Character Wrapper class methods
 Static char forDigit(int i, int r)
It converts an integer value into character value
for (int i = 0; i < 16; i++)
System.out.println (Character.forDigit (i, 16));
 Static int digit(char ch, int r)
It converts an character into integer by specified radix

char [] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'x' };
for (int i = 0; i < digits.length; i++)
System.out.println (Character.digit (digits [i], 16));
34

You might also like