Wrapper Class
Wrapper Class
& ENGINEERING
• Basic Java Syntax: Familiarity with Java's basic syntax, including variable declaration, loops, and conditionals.
• Object-Oriented Programming (OOP) Concepts: Understanding of classes, objects, inheritance, and polymorphism.
• Basic Data Types: Knowledge of primitive data types and their usage in Java.
Objectives
• Understand and apply Java's access modifiers to control the visibility and accessibility of classes, methods, and variables.
• Learn the purpose and usage of packages in Java for organizing and modularizing code.
• Understand the concept and necessity of wrapper classes for working with primitive data types as objects.
• Comprehend the processes of boxing (converting primitives to wrapper objects) and unboxing (converting wrapper objects back to
primitives) and recognize their automatic occurrences in Java.
Outcomes
• Use public, protected, default (package-private), and private access modifiers to enhance encapsulation and security in Java programs.
• Organize Java classes into packages and effectively import and utilize classes from different packages, promoting code modularity and
organization.
• Convert between primitive data types and their corresponding wrapper classes, utilizing wrapper class methods for data parsing,
conversion, and manipulation.
• Implement and identify both explicit and implicit boxing and unboxing in Java programs, understanding their performance implications
and avoiding common pitfalls. 2
Class:
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.
3
What
A class is user defined data
type defined in JAVA using
keyword class followed by Why
the name of class. The A class in JAVA is the building
body of class is defined block, that leads to Object-
inside the curly brackets Oriented programming. It is a
and terminated by a user-defined data type, which
semicolon at the end. holds its own data members and
member functions, which can be
accessed and used by creating an
instance of that class.
Class
• A class is user defined data type which consists of two sections, a private and a
protected section that holds data and a public section that holds the interface
operations.
• A class definition is a process of naming a class and data variables, and methods
or interface operations of the class.
• Once a class has been defined, we can create any number of objects belonging to
that class.
• A class is collection of objects of similar type.
6
Accessing Class Members
7
ACCESS MODIFIERS
• The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.
• There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
Access within class within outside outside
Modifier package package by package
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private Example
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
Nested Classes
• In Java, just like methods, variables of a class too can have another class as its
member. Writing a class within another is allowed in Java. The class written within is
called the nested class, and the class that holds the inner class is called the outer
class.
Syntax
• Following is the syntax to write a nested class. Here, the class Outer_Demo is the
outer class and the class Inner_Demo is the nested class.
class Outer_Demo
{
class Inner_Demo {
}
}
13
Types Of Nested Classes
14
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Local Inner Class
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System.out.println(data);}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}
Wrapper Classes
Primitive data types are not used as objects in Java
However, many Java methods require the use of objects as arguments. For example, the
add(object) method in the ArrayList
Java offers a convenient way to incorporate, or wrap, a primitive data type into an object.
Corresponding class is called a Wrapper Class
For example, wrapping int into the Integer class, and wrapping double into the Double class
Most wrapper class names for a primitive type are the same as the primitive data type name with
the first letter capitalized. The exceptions are Integer and Character.
Java provides Boolean, Character, Double, Float, Byte, Short, Integer, and Long wrapper classes for
primitive data types
These classes are grouped in the java.lang package.
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
19
Use of Wrapper classes in Java
• Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc. Let
us see the different scenarios, where we need to use the wrapper classes.
• Change the value in Method: Java supports only call by value. So, if we
pass a primitive value, it will not change the original value. But, if we convert
the primitive value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects
through the wrapper classes.
• Synchronization: Java synchronization works with objects in Multithreading.
• java.util package: The java.util package provides the utility classes to deal
with objects.
• Collection Framework: Java collection framework works with objects only.
All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects
only.
20
Inheritance Hierarchy of Wrapper Classes
Double and Float
Constructors
Double(double num)
Double(String str) throws NumberFormatException
Float(double num)
Float(float num)
Float(String str) throws NumberFormatException
Double and Float
Methods in java.lang.Double
Integer
Constructors
Integer(int value)
Integer(String s)
Constants (static)
Character
Constructors
Character(char ch)
Constants (static)
Methods in java.lang.Character
Boolean
Constructors
Boolean(boolean boolValue)
Boolean(String boolString)
Methods in java.lang.Boolean
int compareTo(Boolean b)
boolean equals(Object boolObj)
static boolean parseBoolean(String str)
String toString( )
static Boolean valueOf(String boolString)
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte,
char to Character,
int to Integer, long to Long, float to Float, boolean to Boolean,double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into objects.
• The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
• Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb);
}
}
34
Output:
---Printing object values---
//Printing primitives Byte object: 10
System.out.println("---Printing primitive values---"); Short object: 20
Integer object: 30
System.out.println("byte value: "+bytevalue); Long object: 40
System.out.println("short value: "+shortvalue); Float object: 50.0
Double object: 60.0
System.out.println("int value: "+intvalue); Character object: a
System.out.println("long value: "+longvalue); Boolean object: true
---Printing primitive values---
System.out.println("float value: "+floatvalue); byte value: 10
System.out.println("double value: "+doublevalue); short value: 20
System.out.println("char value: "+charvalue); int value: 30
long value: 40
System.out.println("boolean value: "+boolvalue); float value: 50.0
}} double value: 60.0
char value: a
boolean value: true
35
Placement Related Questions:
• What are access modifiers in Java, and how do they contribute to encapsulation?
• Explain the differences between public, protected, default (package-private), and
private access modifiers with examples.
• What is a package in Java, and what benefits does it provide in organizing code?
• How do you create and use a package in Java? Can you provide an example?
• Describe what wrapper classes are and why they are necessary in Java.
• List the wrapper classes corresponding to Java's primitive data types and explain one
use case for a wrapper class.
• What is boxing in Java? Provide an example to illustrate this concept.
• What is unboxing in Java? Provide an example to illustrate this concept.
• What are the potential performance issues associated with boxing and unboxing? How
can they be mitigated?
• Discuss how packages and access modifiers together can help in designing a well-
structured and secure Java application.
36
Worksheets
• https://www.hackerrank.com/challenges/java-string-reverse/
problem
• https://leetcode.com/problems/count-primes/
• https://tests.mettl.com/authenticateKey/36c4ef58
• https://leetcode.com/problems/find-the-index-of-the-first-
occurrence-in-a-string/description/
• https://leetcode.com/problems/move-zeroes/
• https://leetcode.com/problems/delete-leaves-with-a-given-
value/?envType=daily-question&envId=2024-05-17
• https://leetcode.com/problems/jump-game-ii/description/
• https://leetcode.com/problems/reverse-words-in-a-string/
description/
37
REFERENCES
TEXT BOOKS
T1 Core Java Volume I – Fundamentals
.
T2 Effective Java
REFERENCE BOOKS
R1 “java- The Complete Reference”, Tata McGraw-Hill 2003, New Delhi.
R2 Bjarne Stroustrup: “The JAVA Programming Language” (4th Edition).
Addison-Wesley.
Websites:
1.https://www.javatpoint.com/java-tutorial
2.https://www.tutorialspoint.com/java/index.htm
3.https://www.geeksforgeeks.org/java/
38