0% found this document useful (0 votes)
4 views

Wrapper Class

Uploaded by

gautam.e16534
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Wrapper Class

Uploaded by

gautam.e16534
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

DEPARTMENT OF COMPUTER SCIENCE

& ENGINEERING

Subject Name: PBLJ


Day: 2
Topics Covered: Access Modifiers, Packages, Wrapper classes, Boxing and
Unboxing

DISCOVER . LEARN . EMPOWER


These points related to Day wise topic should be included :
Prerequisites

• 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.

A class in Java can contain:


• Fields
• Methods
• Constructors
• Blocks (Instance Initialization Block (IIB), Static Initialization Block (SIB))
• Nested class and interface

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.

Example-- If fruit has been defined as a class, then the statement


fruit mango;
will create an object mango belonging to the class fruit.
5
Objects

• Oops uses object as fundamental Building Block Definitions.


• Objects are the basic run time entities in object oriented System.
• Every object is associated with Data and Functions which define
meaningful operations on an object.
• Object is a real world existing entity.
• Object is an instance of a particular class.

6
Accessing Class Members

• Accessing a data member depends on the access control of that data


member. If its public, then the data member can be easily accessed using
the direct member access (.) operator with the object of that class.
• If, the data member is defined as private or protected, then we cannot
access the data variables directly. Then we will have to create special
public member functions to access, use or initialize the private and
protected data members. These member functions are also
called Accessors and Mutator methods or getter and setter functions.

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");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);
obj.msg();
}
}
Default Example
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Protected Example
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

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

• The nested class, are classified in to two parts.


• Non-static nested classes − These are the non-static members of a class.
• Static nested classes − These are the static members of a class.

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

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

static int compare(double d1, double d2)


int compareTo(Double anotherDouble)
boolean equals(Object obj)
static double parseDouble(String s)
String toString()
static Double valueOf(String s)

Similar methods in java.lang.Float but with float or Float argument


Integer

Integer
Constructors

Integer(int value)
Integer(String s)

Constants (static)

MAX_VALUE Maximum positive value


MIN_VALUE Minimum positive value
TYPE The Class object for float or double
SIZE Number of bits used to represent int type
Integer
Methods in java.lang.Integer

int compareTo(Integer anotherInteger)


double doubleValue() // similarly intValue(), byteValue(), floatValue(),
shortValue()
boolean equals(Object obj)
static int parseInt(String s)
String toString()
static Integer valueOf(String s)
Character

Character
Constructors

Character(char ch)

Constants (static)

MAX_VALUE The largest character value


MIN_VALUE The smallest character value
TYPE The Class object for char
SIZE The number of bits used to represent a char value
Character

Methods in java.lang.Character

static boolean isDigit(char ch)


static boolean isLetter(char ch)
static boolean isLetterOrDigit(char ch)
static boolean isLowerCase(char ch)
static boolean isSpaceChar(char ch)
static boolean isUpperCase(char ch)
static boolean isWhitespace(char ch)
static char toLowerCase(char ch)
static char toUpperCase(char ch)
Boolean

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.

Wrapper class Example: Primitive to Wrapper


//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}}
Output:
20 20 20
20 20 20
29
Unboxing

• 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

System.out.println(a+" "+i+" "+j);


}}
Output:
30
333
Boxing and Unboxing

 Java allows primitive types and wrapper classes to be converted


automatically
 Converting a primitive value to a wrapper object is called Boxing
 The reverse conversion is called Unboxing
Boxing and Unboxing

class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb);
}
}

displays 100 100


Java Wrapper classes Example
//Java Program to convert all primitives into its corresponding
//wrapper objects and vice-versa
public class WrapperExample3{
public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
33
Boolean boolobj=b2;
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

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

You might also like