SlideShare a Scribd company logo
Java Primer WrapperClasses-1 © Scott MacKenzie
Wrapper Classes
Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper
classes, because they "wrap" the primitive data type into an object of that class. So, there is an
Integer class that holds an int variable, there is a Double class that holds a double
variable, and so on. The wrapper classes are part of the java.lang package, which is imported
by default into all Java programs. The following discussion focuses on the Integer wrapper
class, but applies in a general sense to all eight wrapper classes. Consult the Java API
documentation for more details.
The following two statements illustrate the difference between a primitive data type and an object
of a wrapper class:
int x = 25;
Integer y = new Integer(33);
The first statement declares an int variable named x and initializes it with the value 25. The
second statement instantiates an Integer object. The object is initialized with the value 33 and
a reference to the object is assigned to the object variable y. The memory assignments from
these two statements are visualized in Figure 1.
(a) (b)
25
x y
33
Figure 1. Variables vs. objects (a) declaration and initialization
of an int variable (b) instantiation of an Integer object
Clearly x and y differ by more than their values: x is a variable that holds a value; y is an object
variable that holds a reference to an object. As noted earlier, data fields in objects are not, in
general, directly accessible. So, the following statement using x and y as declared above is not
allowed:
int z = x + y; // wrong!
The data field in an Integer object is only accessible using the methods of the Integer class.
One such method — the intValue() method — returns an int equal to the value of the
object, effectively "unwrapping" the Integer object:
int z = x + y.intValue(); // OK!
Note the format of the method call. The intValue() method is an instance method, because it
is called through an instance of the class — an Integer object. The syntax uses dot notation,
where the name of the object variable precedes the dot.
Some of Java's classes include only instance methods, some include only class methods, some
include both. The Integer class includes both instance methods and class methods. The class
methods provide useful services; however, they are not called through instances of the class.
But, this is not new. We met a class method of the Integer class earlier. The statement
int x = Integer.parseInt("1234");
converts the string "1234" into the integer 1,234 and assigns the result to the int variable x.
The method parseInt() is a class method. It is not called through an instance of the class.
Java Primer WrapperClasses-2 © Scott MacKenzie
Although dot notation is used above, the term "Integer." identifies the class where the method
is defined, rather than name of an Integer object. This is one of the trickier aspects of
distinguishing instance methods from class methods. For an instance method, the dot is preceded
by the name of an object variable. For a class method, the dot is preceded by the name of a class.
It is interesting that the parseInt() method accepts a String argument and returns an int.
Neither the argument nor the returned value is an Integer object. So, the earlier comment that
class methods "provide useful services" is quite true. They do not operate on instance variables;
they provide services that are of general use. The parseInt() method converts a String to
an int, and this is a useful service — one we have called upon in previous programs.
Another useful Integer class method is the toString() method. The following statement
String s = Integer.toString(1234);
converts the int constant 1,234 to a String object and returns a reference to the object. We
have already met this method through the following shorthand notation:
String s = "" + 1234;
In general, the data fields in objects are private and are only accessible through methods of the
class. However, class definitions sometimes include constants that are "public", and, therefore,
accessible anywhere the class is accessible. Java's wrapper classes include publicly defined
constants identifying the range for each type. For example, the Integer class has constants
called MIN_VALUE and MAX_VALUE equal to 0x80000000 and 0x7fffffff respectively. These
values are the hexadecimal equivalent of the most-negative and most-positive values represented
by 32-bit integers. The table of ranges shown earlier was obtained from a simple program called
FindRanges that prints these constants. The listing is given here in Figure 2.
1 public class FindRanges
2 {
3 public static void main(String[] args)
4 {
5 System.out.println("Integer range:");
6 System.out.println(" min: " + Integer.MIN_VALUE);
7 System.out.println(" max: " + Integer.MAX_VALUE);
8 System.out.println("Double range:");
9 System.out.println(" min: " + Double.MIN_VALUE);
10 System.out.println(" max: " + Double.MAX_VALUE);
11 System.out.println("Long range:");
12 System.out.println(" min: " + Long.MIN_VALUE);
13 System.out.println(" max: " + Long.MAX_VALUE);
14 System.out.println("Short range:");
15 System.out.println(" min: " + Short.MIN_VALUE);
16 System.out.println(" max: " + Short.MAX_VALUE);
17 System.out.println("Byte range:");
18 System.out.println(" min: " + Byte.MIN_VALUE);
19 System.out.println(" max: " + Byte.MAX_VALUE);
20 System.out.println("Float range:");
21 System.out.println(" min: " + Float.MIN_VALUE);
22 System.out.println(" max: " + Float.MAX_VALUE);
23 }
24 }
Figure 2. FindRanges.java
This program generates the following output:
Java Primer WrapperClasses-3 © Scott MacKenzie
Integer range:
min: -2147483648
max: 2147483647
Double range:
min: 4.9E-324
max: 1.7976931348623157E308
Long range:
min: -9223372036854775808
max: 9223372036854775807
Short range:
min: -32768
max: 32767
Byte range:
min: -128
max: 127
Float range:
min: 1.4E-45
max: 3.4028235E38
In the case of float and double, the minimum and maximum values are those closest to plus
or minus zero or plus or minus infinity, respectively.
The most common methods of the Integer wrapper class are summarized in Table 1. Similar
methods for the other wrapper classes are found in the Java API documentation.
Table 1. Methods of the Integer Wrapper Class
Method Purpose
Constructors
Integer(i) constructs an Integer object equivalent to the integer i
Integer(s) constructs an Integer object equivalent to the string s
Class Methods
parseInt(s) returns a signed decimal integer value equivalent to string s
toString(i) returns a new String object representing the integer i
Instance Methods
byteValue() returns the value of this Integer as a byte
doubleValue() returns the value of this Integer as an double
floatValue() returns the value of this Integer as a float
intValue() returns the value of this Integer as an int
longValue() returns the value of this Integer as a long
shortValue() returns the value of this Integer as a short
toString() returns a String object representing the value of this Integer
In the descriptions of the instance methods, the phrase "this Integer" refers to the instance
variable on which the method is acting. For example, if y is an Integer object variable, the
expression y.doubleValue() returns the value of "this Integer", or y, as a double.

More Related Content

What's hot

L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
teach4uin
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
Akshay soni
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
nurkhaledah
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
Nontawat Wongnuk
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
Raja Sekhar
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
Mumbai Academisc
 

What's hot (20)

L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
 
Java String
Java String Java String
Java String
 
Class method
Class methodClass method
Class method
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 

Similar to Wrapper classes

Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
SURBHI SAROHA
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
Padma Kannan
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
Shivam Singh
 
08review (1)
08review (1)08review (1)
08review (1)
IIUM
 
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
Classes,object and methods jav
Classes,object and methods javClasses,object and methods jav
Classes,object and methods jav
Padma Kannan
 
Java class
Java classJava class
Java class
Arati Gadgil
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
Gujarat Technological University
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
ishasharma835109
 
Generics collections
Generics collectionsGenerics collections
Generics collections
Yaswanth Babu Gummadivelli
 
Java.util
Java.utilJava.util
Java.util
Ramakrishna kapa
 

Similar to Wrapper classes (20)

Hemajava
HemajavaHemajava
Hemajava
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
08review (1)
08review (1)08review (1)
08review (1)
 
Object and class
Object and classObject and class
Object and class
 
Built-in Classes in JAVA
Built-in Classes in JAVABuilt-in Classes in JAVA
Built-in Classes in JAVA
 
Collections
CollectionsCollections
Collections
 
Classes,object and methods jav
Classes,object and methods javClasses,object and methods jav
Classes,object and methods jav
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Java class
Java classJava class
Java class
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Java.util
Java.utilJava.util
Java.util
 

More from simarsimmygrewal

C file
C fileC file
Java file
Java fileJava file
Java file
simarsimmygrewal
 
C file
C fileC file
C++ file
C++ fileC++ file
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
simarsimmygrewal
 
Handling inputs via io..continue
Handling inputs via io..continueHandling inputs via io..continue
Handling inputs via io..continue
simarsimmygrewal
 
Excception handling
Excception handlingExcception handling
Excception handling
simarsimmygrewal
 
Type casting
Type castingType casting
Type casting
simarsimmygrewal
 

More from simarsimmygrewal (9)

Java file
Java fileJava file
Java file
 
C file
C fileC file
C file
 
Java file
Java fileJava file
Java file
 
C file
C fileC file
C file
 
C++ file
C++ fileC++ file
C++ file
 
Handling inputs via scanner class
Handling inputs via scanner classHandling inputs via scanner class
Handling inputs via scanner class
 
Handling inputs via io..continue
Handling inputs via io..continueHandling inputs via io..continue
Handling inputs via io..continue
 
Excception handling
Excception handlingExcception handling
Excception handling
 
Type casting
Type castingType casting
Type casting
 

Recently uploaded

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 

Recently uploaded (20)

Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 

Wrapper classes

  • 1. Java Primer WrapperClasses-1 © Scott MacKenzie Wrapper Classes Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. So, there is an Integer class that holds an int variable, there is a Double class that holds a double variable, and so on. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs. The following discussion focuses on the Integer wrapper class, but applies in a general sense to all eight wrapper classes. Consult the Java API documentation for more details. The following two statements illustrate the difference between a primitive data type and an object of a wrapper class: int x = 25; Integer y = new Integer(33); The first statement declares an int variable named x and initializes it with the value 25. The second statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the object is assigned to the object variable y. The memory assignments from these two statements are visualized in Figure 1. (a) (b) 25 x y 33 Figure 1. Variables vs. objects (a) declaration and initialization of an int variable (b) instantiation of an Integer object Clearly x and y differ by more than their values: x is a variable that holds a value; y is an object variable that holds a reference to an object. As noted earlier, data fields in objects are not, in general, directly accessible. So, the following statement using x and y as declared above is not allowed: int z = x + y; // wrong! The data field in an Integer object is only accessible using the methods of the Integer class. One such method — the intValue() method — returns an int equal to the value of the object, effectively "unwrapping" the Integer object: int z = x + y.intValue(); // OK! Note the format of the method call. The intValue() method is an instance method, because it is called through an instance of the class — an Integer object. The syntax uses dot notation, where the name of the object variable precedes the dot. Some of Java's classes include only instance methods, some include only class methods, some include both. The Integer class includes both instance methods and class methods. The class methods provide useful services; however, they are not called through instances of the class. But, this is not new. We met a class method of the Integer class earlier. The statement int x = Integer.parseInt("1234"); converts the string "1234" into the integer 1,234 and assigns the result to the int variable x. The method parseInt() is a class method. It is not called through an instance of the class.
  • 2. Java Primer WrapperClasses-2 © Scott MacKenzie Although dot notation is used above, the term "Integer." identifies the class where the method is defined, rather than name of an Integer object. This is one of the trickier aspects of distinguishing instance methods from class methods. For an instance method, the dot is preceded by the name of an object variable. For a class method, the dot is preceded by the name of a class. It is interesting that the parseInt() method accepts a String argument and returns an int. Neither the argument nor the returned value is an Integer object. So, the earlier comment that class methods "provide useful services" is quite true. They do not operate on instance variables; they provide services that are of general use. The parseInt() method converts a String to an int, and this is a useful service — one we have called upon in previous programs. Another useful Integer class method is the toString() method. The following statement String s = Integer.toString(1234); converts the int constant 1,234 to a String object and returns a reference to the object. We have already met this method through the following shorthand notation: String s = "" + 1234; In general, the data fields in objects are private and are only accessible through methods of the class. However, class definitions sometimes include constants that are "public", and, therefore, accessible anywhere the class is accessible. Java's wrapper classes include publicly defined constants identifying the range for each type. For example, the Integer class has constants called MIN_VALUE and MAX_VALUE equal to 0x80000000 and 0x7fffffff respectively. These values are the hexadecimal equivalent of the most-negative and most-positive values represented by 32-bit integers. The table of ranges shown earlier was obtained from a simple program called FindRanges that prints these constants. The listing is given here in Figure 2. 1 public class FindRanges 2 { 3 public static void main(String[] args) 4 { 5 System.out.println("Integer range:"); 6 System.out.println(" min: " + Integer.MIN_VALUE); 7 System.out.println(" max: " + Integer.MAX_VALUE); 8 System.out.println("Double range:"); 9 System.out.println(" min: " + Double.MIN_VALUE); 10 System.out.println(" max: " + Double.MAX_VALUE); 11 System.out.println("Long range:"); 12 System.out.println(" min: " + Long.MIN_VALUE); 13 System.out.println(" max: " + Long.MAX_VALUE); 14 System.out.println("Short range:"); 15 System.out.println(" min: " + Short.MIN_VALUE); 16 System.out.println(" max: " + Short.MAX_VALUE); 17 System.out.println("Byte range:"); 18 System.out.println(" min: " + Byte.MIN_VALUE); 19 System.out.println(" max: " + Byte.MAX_VALUE); 20 System.out.println("Float range:"); 21 System.out.println(" min: " + Float.MIN_VALUE); 22 System.out.println(" max: " + Float.MAX_VALUE); 23 } 24 } Figure 2. FindRanges.java This program generates the following output:
  • 3. Java Primer WrapperClasses-3 © Scott MacKenzie Integer range: min: -2147483648 max: 2147483647 Double range: min: 4.9E-324 max: 1.7976931348623157E308 Long range: min: -9223372036854775808 max: 9223372036854775807 Short range: min: -32768 max: 32767 Byte range: min: -128 max: 127 Float range: min: 1.4E-45 max: 3.4028235E38 In the case of float and double, the minimum and maximum values are those closest to plus or minus zero or plus or minus infinity, respectively. The most common methods of the Integer wrapper class are summarized in Table 1. Similar methods for the other wrapper classes are found in the Java API documentation. Table 1. Methods of the Integer Wrapper Class Method Purpose Constructors Integer(i) constructs an Integer object equivalent to the integer i Integer(s) constructs an Integer object equivalent to the string s Class Methods parseInt(s) returns a signed decimal integer value equivalent to string s toString(i) returns a new String object representing the integer i Instance Methods byteValue() returns the value of this Integer as a byte doubleValue() returns the value of this Integer as an double floatValue() returns the value of this Integer as a float intValue() returns the value of this Integer as an int longValue() returns the value of this Integer as a long shortValue() returns the value of this Integer as a short toString() returns a String object representing the value of this Integer In the descriptions of the instance methods, the phrase "this Integer" refers to the instance variable on which the method is acting. For example, if y is an Integer object variable, the expression y.doubleValue() returns the value of "this Integer", or y, as a double.