SlideShare une entreprise Scribd logo
1  sur  20
Wrapper Classes
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 2
Problem with Primitives
 Java is an object-oriented language. Means, everything in
Java is an object
 But, how about primitives?
 Primitives cannot participate in the object activities, such as
 Returned from a method as an object
 Adding to a Collection of objects
 As a solution to this problem, Java allows you to include the
primitives in the family of objects by using Wrapper classes
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 3
Creating Wrapper Classes
 For to each primitive data type in Java there is
corresponding wrapper class
 This class encapsulates a single value for the primitive
data type
 The wrapper object of a wrapper class can be created
in one of two ways:
 By instantiating the wrapper class with the new operator
 By invoking a static method on the wrapper class
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 4
Primitive Types and Wrapper Classes
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 5
Creating Wrapper Classes with new Operator
 Obviously, you can always pass the corresponding primitive data
type as an argument to a wrapper class constructor
 You can also pass a String as an argument to any wrapper class
constructor except Character
 The Character constructor only takes the obvious argument: char
 You can pass double as an argument to the Float constructor but
not vice versa
 All the wrapper classes except Boolean and Character are
subclasses of an abstract class called Number
 Boolean and Character are derived directly from the Object class
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 6
Another way of Creating Wrappers
 The wrapped value in a wrapper class cannot be modified
 To wrap another value, you need to create another object
 Wrappers are immutable
 There will be situations in your program when you really don’t
need a new instance of the wrapper class
 but you still want to wrap a primitive
 In this case, use the static method valueOf()
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 7
Using Static Method valueOf()
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 8
 The valueOf() method in the Character class accepts only
char as an argument
 Any other wrapper class will accept either the corresponding
primitive type or String as an argument
 The valueOf() method in the integer number wrapper classes
(Byte, Short, Integer, and Long) also accepts two arguments
together:
 A String
 A radix, where radix is the base
 For example, a decimal is radix 10 and a binary is radix 2
Using Static Method valueOf()
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 9
 A storage capability without the retrieval capability is not of much use
 Once we store a primitive in a wrapper object, often you will want to
retrieve the stored primitive at a later time
 All the number wrapper classes (Byte, Short, Integer, Long, Float, and
Double) have the which can retrieve byte, short, int, long, float, or
double
 This is because all of these classes are subclasses of the Number
class
 It means you can store one primitive type in a wrapper and retrieve
another one
 So you can use the wrappers as a conversion machine
Extracting Wrapped Values
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 10
Methods to extract values
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 11
 We can use Wrappers for converting the type without
creating the Wrapper
 There is an appropriate static method in every wrapper class
 For example, all the wrapper classes except Character offer
a static method that has the following signature:
static <type> parse<Type>(String s)
 Ex: static int parseInt (String s)
 Each of these methods parses the string passed in as a
parameter and returns the corresponding primitive type
Instant use of Wrapper Classes
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 12
Methods to Convert Strings to Primitives
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 13
 Wrapper classes are used for two main purposes
 To store a primitive type in an object so that it can participate in
object-like operations
 To convert one primitive type into another
 However, as we have seen, you do this conversion between
primitives and objects manually
 If Java is a truly object-oriented language, why do we have to
manually wrap the primitives into objects
 why is the process not made automated? Well, that is exactly what
autoboxing offers
Wrapper Classes
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 14
 Boxing and unboxing make using wrapper classes more convenient
 In the old, pre-Java 5 days, if you wanted to make a wrapper, unwrap it,
use it, and then rewrap it, you might do something like this:
Integer y = new Integer(567); // make it
int x = y.intValue(); // unwrap it
x++; // use it
y = new Integer(x); // re-wrap it
System.out.println("y = " + i); // print it
 Now, with new and improved Java 5 you can say
Integer y = new Integer(567); // make it
y++; // unwrap it, increment it,
// rewrap it
System.out.println("y = " + i); // print it
Boxing and Unboxing
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 15
 The Intention of the equals() method is to determine whether
two instances of a given class are "meaningfully equivalent"
 This definition is intentionally subjective
 it's up to the creator of the class to determine what
"equivalent" means for objects of the class
 For all wrapper classes, two objects are equal if they are of
the same type and have the same value
Boxing, == and .equals()
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 16
 Widening, Var-Args and Auto-Boxing make method overloadig a
little tricky
 When a class has overloaded methods, the compiler's jobs is to
determine which method to use whenever it finds an invocation for
the overloaded method
Auto-Boxing and Overloading
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 17
class AddBoxing
{
static void go(Integer x)
{
System.out.println("Integer");
}
static void go(long x)
{
System.out.println("long");
}
public static void main(String [] args)
{
int i = 5;
go(i); // which go() will be invoked?
}
}
Overloading with Boxing and Widening
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 18
class AddVarargs
{
static void go(int x, int y)
{
System.out.println("int,int");
}
static void go(byte... x)
{
System.out.println("byte... ");
}
public static void main(String[] args)
{
byte b = 5;
go(b,b); // which go() will be invoked?
}
}
Overloading with Var-Args and Widening
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 19
 Even though each invocation will require some sort of
conversion, the compiler will choose the older style
before it chooses the newer style
 This keeps the existing code more robust.
 So far we've seen that
 Widening beats boxing
 Widening beats var-args
 Does does boxing beat var-args?
Reason
10/02/13 RENAISSANCE SOFTLABS (P) LTD. 20
class BoxOrVararg
{
static void go(Byte x, Byte y)
{
System.out.println("Byte, Byte");
}
static void go(byte... x)
{
System.out.println("byte... ");
}
public static void main(String [] args)
{
byte b = 5;
go(b,b); // which go() will be invoked?
}
}
Overloading with Var-Args and Boxing

Contenu connexe

Tendances (20)

I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods EncapsulationOCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Finalize() method
Finalize() methodFinalize() method
Finalize() method
 
Java basic
Java basicJava basic
Java basic
 
Java IO
Java IOJava IO
Java IO
 
String in java
String in javaString in java
String in java
 
Java arrays
Java arraysJava arrays
Java arrays
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
File handling
File handlingFile handling
File handling
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
 

Similaire à wrapper classes

Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsEo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Container Classes
Container ClassesContainer Classes
Container Classesadil raja
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming LanguageYLTO
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic classifis
 
Java assignment help
Java assignment helpJava assignment help
Java assignment helpJacob William
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer ProgrammingInocentshuja Ahmad
 

Similaire à wrapper classes (20)

Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Java 06
Java 06Java 06
Java 06
 
Java mcq
Java mcqJava mcq
Java mcq
 
Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsEo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Container Classes
Container ClassesContainer Classes
Container Classes
 
3 jf h-linearequations
3  jf h-linearequations3  jf h-linearequations
3 jf h-linearequations
 
Java basics
Java basicsJava basics
Java basics
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Future Programming Language
Future Programming LanguageFuture Programming Language
Future Programming Language
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
slides 01.ppt
slides 01.pptslides 01.ppt
slides 01.ppt
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 

Plus de Rajesh Roky

File splitter and joiner
File splitter and joinerFile splitter and joiner
File splitter and joinerRajesh Roky
 
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILEINTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILERajesh Roky
 
The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...Rajesh Roky
 
File Splitter Table of contents
File Splitter Table of contents File Splitter Table of contents
File Splitter Table of contents Rajesh Roky
 
FILE SPLITTER AND JOINER
FILE SPLITTER AND JOINERFILE SPLITTER AND JOINER
FILE SPLITTER AND JOINERRajesh Roky
 
Rainbow technology-ppt
Rainbow technology-pptRainbow technology-ppt
Rainbow technology-pptRajesh Roky
 

Plus de Rajesh Roky (8)

11. jdbc
11. jdbc11. jdbc
11. jdbc
 
Servlet
ServletServlet
Servlet
 
File splitter and joiner
File splitter and joinerFile splitter and joiner
File splitter and joiner
 
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILEINTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
INTEGRATED SHOPPING ASSISTANCE WITH FREDGE AND MOBILE
 
The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...The main purpose of the project is to manage the supermarket efficiently (rep...
The main purpose of the project is to manage the supermarket efficiently (rep...
 
File Splitter Table of contents
File Splitter Table of contents File Splitter Table of contents
File Splitter Table of contents
 
FILE SPLITTER AND JOINER
FILE SPLITTER AND JOINERFILE SPLITTER AND JOINER
FILE SPLITTER AND JOINER
 
Rainbow technology-ppt
Rainbow technology-pptRainbow technology-ppt
Rainbow technology-ppt
 

Dernier

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 

Dernier (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

wrapper classes

  • 2. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 2 Problem with Primitives  Java is an object-oriented language. Means, everything in Java is an object  But, how about primitives?  Primitives cannot participate in the object activities, such as  Returned from a method as an object  Adding to a Collection of objects  As a solution to this problem, Java allows you to include the primitives in the family of objects by using Wrapper classes
  • 3. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 3 Creating Wrapper Classes  For to each primitive data type in Java there is corresponding wrapper class  This class encapsulates a single value for the primitive data type  The wrapper object of a wrapper class can be created in one of two ways:  By instantiating the wrapper class with the new operator  By invoking a static method on the wrapper class
  • 4. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 4 Primitive Types and Wrapper Classes
  • 5. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 5 Creating Wrapper Classes with new Operator  Obviously, you can always pass the corresponding primitive data type as an argument to a wrapper class constructor  You can also pass a String as an argument to any wrapper class constructor except Character  The Character constructor only takes the obvious argument: char  You can pass double as an argument to the Float constructor but not vice versa  All the wrapper classes except Boolean and Character are subclasses of an abstract class called Number  Boolean and Character are derived directly from the Object class
  • 6. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 6 Another way of Creating Wrappers  The wrapped value in a wrapper class cannot be modified  To wrap another value, you need to create another object  Wrappers are immutable  There will be situations in your program when you really don’t need a new instance of the wrapper class  but you still want to wrap a primitive  In this case, use the static method valueOf()
  • 7. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 7 Using Static Method valueOf()
  • 8. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 8  The valueOf() method in the Character class accepts only char as an argument  Any other wrapper class will accept either the corresponding primitive type or String as an argument  The valueOf() method in the integer number wrapper classes (Byte, Short, Integer, and Long) also accepts two arguments together:  A String  A radix, where radix is the base  For example, a decimal is radix 10 and a binary is radix 2 Using Static Method valueOf()
  • 9. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 9  A storage capability without the retrieval capability is not of much use  Once we store a primitive in a wrapper object, often you will want to retrieve the stored primitive at a later time  All the number wrapper classes (Byte, Short, Integer, Long, Float, and Double) have the which can retrieve byte, short, int, long, float, or double  This is because all of these classes are subclasses of the Number class  It means you can store one primitive type in a wrapper and retrieve another one  So you can use the wrappers as a conversion machine Extracting Wrapped Values
  • 10. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 10 Methods to extract values
  • 11. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 11  We can use Wrappers for converting the type without creating the Wrapper  There is an appropriate static method in every wrapper class  For example, all the wrapper classes except Character offer a static method that has the following signature: static <type> parse<Type>(String s)  Ex: static int parseInt (String s)  Each of these methods parses the string passed in as a parameter and returns the corresponding primitive type Instant use of Wrapper Classes
  • 12. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 12 Methods to Convert Strings to Primitives
  • 13. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 13  Wrapper classes are used for two main purposes  To store a primitive type in an object so that it can participate in object-like operations  To convert one primitive type into another  However, as we have seen, you do this conversion between primitives and objects manually  If Java is a truly object-oriented language, why do we have to manually wrap the primitives into objects  why is the process not made automated? Well, that is exactly what autoboxing offers Wrapper Classes
  • 14. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 14  Boxing and unboxing make using wrapper classes more convenient  In the old, pre-Java 5 days, if you wanted to make a wrapper, unwrap it, use it, and then rewrap it, you might do something like this: Integer y = new Integer(567); // make it int x = y.intValue(); // unwrap it x++; // use it y = new Integer(x); // re-wrap it System.out.println("y = " + i); // print it  Now, with new and improved Java 5 you can say Integer y = new Integer(567); // make it y++; // unwrap it, increment it, // rewrap it System.out.println("y = " + i); // print it Boxing and Unboxing
  • 15. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 15  The Intention of the equals() method is to determine whether two instances of a given class are "meaningfully equivalent"  This definition is intentionally subjective  it's up to the creator of the class to determine what "equivalent" means for objects of the class  For all wrapper classes, two objects are equal if they are of the same type and have the same value Boxing, == and .equals()
  • 16. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 16  Widening, Var-Args and Auto-Boxing make method overloadig a little tricky  When a class has overloaded methods, the compiler's jobs is to determine which method to use whenever it finds an invocation for the overloaded method Auto-Boxing and Overloading
  • 17. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 17 class AddBoxing { static void go(Integer x) { System.out.println("Integer"); } static void go(long x) { System.out.println("long"); } public static void main(String [] args) { int i = 5; go(i); // which go() will be invoked? } } Overloading with Boxing and Widening
  • 18. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 18 class AddVarargs { static void go(int x, int y) { System.out.println("int,int"); } static void go(byte... x) { System.out.println("byte... "); } public static void main(String[] args) { byte b = 5; go(b,b); // which go() will be invoked? } } Overloading with Var-Args and Widening
  • 19. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 19  Even though each invocation will require some sort of conversion, the compiler will choose the older style before it chooses the newer style  This keeps the existing code more robust.  So far we've seen that  Widening beats boxing  Widening beats var-args  Does does boxing beat var-args? Reason
  • 20. 10/02/13 RENAISSANCE SOFTLABS (P) LTD. 20 class BoxOrVararg { static void go(Byte x, Byte y) { System.out.println("Byte, Byte"); } static void go(byte... x) { System.out.println("byte... "); } public static void main(String [] args) { byte b = 5; go(b,b); // which go() will be invoked? } } Overloading with Var-Args and Boxing