0% found this document useful (0 votes)
18 views123 pages

Java Unit 2

The document outlines the course content for a Java programming class focusing on Object-Oriented Programming concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It provides detailed explanations of defining classes, creating objects, adding variables, and using access modifiers, along with examples. Additionally, it covers methods, constructors, and their significance in Java programming.

Uploaded by

sanketraikar78
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)
18 views123 pages

Java Unit 2

The document outlines the course content for a Java programming class focusing on Object-Oriented Programming concepts such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It provides detailed explanations of defining classes, creating objects, adding variables, and using access modifiers, along with examples. Additionally, it covers methods, constructors, and their significance in Java programming.

Uploaded by

sanketraikar78
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/ 123

JAVA PROGRAMMING

B 2 1 D A 0 3 0 2 - A c a d e m i c Ye a r- 2 0 2 2 - 2 0 2 3 - s e m I I I O D D
Semester

BCA, School of CSA


MANJU.B
Assistant Professor
Course Content: UNIT 2
COURSE CONTENTS: UNIT 2:

Classes, Arrays, Strings and Vectors: ​

Classes, Objects and Methods: Introduction, Defining a Class, Adding Variables, Adding
Methods, Creating Objects, Accessing Class Members, Constructors, Methods
Overloading, Static Members, Nesting of Methods, Inheritance: Extending a
Class Overriding Methods, Final Variables and Methods, Finalizer methods, Abstract
Methods and Classes, Visibility Control. Arrays, Strings and Vectors: Arrays, One –
dimensional Arrays, Creating an Array, Two– dimensional Arrays, Strings,
Vectors, Wrapper Classes. ​

3
Topics to be learned from this class

 Introduction

 Defining a Class

 Adding Variables

4
Introduction
OOPs (Object-Oriented Programming System)

 Object-Oriented Programming is a methodology or


paradigm to design a program using classes and
objects. It simplifies software development and
maintenance by providing some concepts like:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

5
Inheritance

 When one object acquires all the properties and behaviors of a parent

object, it is known as inheritance.

 It provides code reusability.

 It is used to achieve runtime polymorphism.

6
Polymorphism

 If one task is performed in different ways, it is known as polymorphism.


 E.g 1. to convince the customer differently.
 to draw something.
 method overloading and method overriding to achieve polymorphism.

7
Abstraction

 Hiding internal details and showing functionality is known as abstraction.

 E.g: phone call, we don't know the internal processing.

 Use abstract class and interface to achieve abstraction.

8
Encapsulation

 Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
 A capsule, it is wrapped with different medicines.
 A java class is the example of encapsulation.
 Java bean is the fully encapsulated class because all the data members are private
here.

9
Classes in Java – Defining a class

 Collection of objects is called class.


 Class is defined by using “class” keyword in java.
 It is a logical entity. It can't be physical.
 A class can also be defined as a template or blueprint from which objects are created.
 A class is a group of objects which have common properties

A class in Java can contain:


Syntax :
 Fields class <class_name
Example:
class Student{
 Methods > int id; //field
 Constructors { public void
field;
 Blocks method;
getStudentData(); //
method
 Inner classes } }

10
DEFINING OBJECT​in java

Object can be defined as


 An object is a real-world entity.
 An Object can be defined as an instance of a
class.
 An object contains an address and takes up
some space in memory.
 The object is an entity which has state (data)
and behavior (function).
 Object can be created in java by using new
keyword followed by class name.

Example: table, fan, bike, pen, keyboard etc.

11
Object and Class Example

Defining a Student class.


class Student{
int id;
//field or data member or instance variable
String name;
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();
//creating an object of Student
//Printing values of the object
System.out.println(s1.id);
System.out.println(s1.name);
}
}
12
ADDING VARIABLES​

 A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time.

 It gets memory at runtime when an object or instance is created. That is why it is known
as an instance variable.

 A method is like a function which is used to expose the behavior of an object. (main
method)

 The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.

13
 Variables can be added inside the class called instance variable or inside the
method called (local variable). ​

 Variable can also be static variable called class variable​.

 Let's see a simple example, where we are having main() method in another class.​

 We can have multiple classes in different Java files or single Java file. ​

 If you define multiple classes in a single Java source file, it is a good idea
to save the file name with the class name which has main() method.​

14
EXAMPLE
class Student{ ​
int id; // instance variables​
String name; ​
int mobno; // adding instance variable​
} ​
class TestStudent1{ ​
public static void main(String args[]){ ​
int a=10; // adding local variable​
Student s1=new Student(); // object​
System.out.println(s1.id); ​
System.out.println(s1.name); ​
System.out.println(s1.mobno); ​
System.out.println(a); ​
} ​
} ​
15
TOPICS TO BE LEARNED FROM THIS CLASS​

 Creating Objects​

 Accessing Class Members

16
Creating Objects

 In Java, an object is created from a class.​

 Object is created by using new keyword followed by class name​

 The new keyword is used to allocate memory at runtime. ​

 All objects get memory in Heap memory area.​

 If object is created without reference variable is called anonymous object



 In the following example m1 is an object​

17
Example1:- ​
public class MyClass
{​
int x = 5; ​
public static void main(String[] args)
{​
MyClass m1 = new MyClass(); ​
System.out.println(m1.x); ​
}​
}​

18
INITIALIZING OBJECTS​

3 Ways to initialize object​

There are 3 ways to initialize object in Java.



 By reference variable​

 By method​

 By constructor​

19
1. Initialization through reference​

Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.​
class Student{ ​
int id; ​
String name; ​
} ​
class TestStudent2{ ​
public static void main(String args[]){ ​
Student s1=new Student(); ​
s1.id=101; ​
s1.name=“Raghav"; ​
System.out.println(s1.id+" "+s1.name); ​
} ​
} 20
2) Initialization through a method​
In this example, we are creating the two objects of Student class and initializing the value to these objects
by invoking the insertRecord method. Here, we are displaying the data of the objects by invoking
the displayInformation() method.​

class Student{ ​
class TestStudent4{ ​
int rollno; ​
public static void main(String args[])
String name; ​
{ ​
void insertRecord(int r, String n){ ​
Student s1=new Student(); ​
rollno=r; ​
Student s2=new Student(); ​
name=n; ​
s1.insertRecord(111,"Karan"); ​
} ​
s2.insertRecord(222,"Aryan"); ​
void displayInformation()​
s1.displayInformation(); ​
{​
s2.displayInformation(); ​
System.out.println(rollno+" "+name);​
} ​
} ​
}
}​

21
3) Initialization through a constructor : We will learn about constructors in Java later.​

ACCESSING CLASS MEMBERS​

 The fields and methods of a class are known as class members​.

 Class members can be accessed by using dot(.) operator​

 In the following example we are accessing insert() method


and calculateArea() method by using dot (.) operator​

22
class Rectangle class TestRectangle1
{ ​ { ​
int length; ​ public static void main(String args[])
int width; ​ {
void insert(int l, int w) Rectangle r1=new Rectangle(); ​
{ ​ Rectangle r2=new Rectangle(); ​
length=l; ​ r1.insert(11,5); ​
width=w; ​ r2.insert(3,15); ​
} ​ r1.calculateArea(); ​
void calculateArea() r2.calculateArea(); ​
{​ } ​
System.out.println(length*width);​ } ​
} ​
}​
23
TOPICS TO BE LEARNED FROM THIS CLASS

 Visibility Control

 Adding Methods

24
CLASSES, OBJECTS AND METHODS​

Visibility Control – Access Modifiers​

 Visibility control also known as access modifiers. It can be applied to the instance variables and methods
within a class.​

 The visibility 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 access modifiers:


1. Public
2. Private
3. Protected
4. default.​

25
1.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.
class A
Example: ​ {
public void display()
{
System.out.println("SoftwareTestingHelp!!");
}
}
class Main
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}
}
26
2. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.​
In this example, we have created two classes A and
Example: class A{
private int data=40; Simple. A class contains private data member and private
private void msg() method. We are accessing these private members from
{ outside the class, so there is a compile-time error.
System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

27
3. Protected: It is accessible within package and outside the package but through inheritance
only. The protected access ​modifier can be applied on the data member, method and
constructor. It can't be applied on the class. ​
package pack; In this example, we have created the two packages pack
public class A{ and mypack. The A class of pack package is public, so
protected void msg(){ can be accessed from outside the package. But msg
System.out.println("Hello");} method of this package is declared as protected, so it can
} be accessed from outside the class only through
//save by B.java inheritance.
package mypack;
import pack.*;

class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
} 28
4. 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. It provides more accessibility than private. But it is more restrictive than protected,
and public. class BaseClass
{
Example:​ void display() //no access modifier indicates default modifier
{
System.out.println("BaseClass::Display with 'dafault' scope");
}
}

class Main
{
public static void main(String args[])
{
//access class with default scope
BaseClass obj = new BaseClass();

obj.display(); //access class method with default scope


}
}
29
ACCESS MODIFIERS TABLE​

30
ADDING METHODS​

 A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation. ​

 It is used to achieve the reusability of code. ​

 We write a method once and use it many times, not require to write code again and
again. ​

 It also provides the easy modification and readability of code.​

 The method is executed only when we call or invoke it. ​

31
 The most important method in Java is the main() method.​

 Every method has a method signature and it is a part of the method declaration.

 Method signature includes method name and parameter list. ​

32
 Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.​

 Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for addition of two numbers, the method name must
be addition() or sum(). A method is invoked or called by its name.​

 Parameter List: It is the list of parameters separated by a comma and enclosed in


the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.​

33
 Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Types of Methods​
There are two types of methods in Java:​
1. Predefined Method​
2. User-defined Method​

34
User-defined Method​
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.​
How to Create a User-defined Method​
Let's create a user defined method that checks the number is even or odd. First, we will
define the method.​
public class Demo ​
{ public void msg(){ //user defined method​
System.out.print(“Hello”);​
}​
public static void main(String[] args) ​
{ ​
Demo d1=new Demo();​
d1.msg();​
} }​
35
Predefined Method​
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. ​
public class Demo ​
{ ​
public static void main(String[] args) ​
{ ​
// using the max() method of Math class ​
System.out.print("The maximum number is: " + Math.max(9,7)); ​
} ​
} ​

36
TOPICS TO BE LEARNED FROM THIS CLASS​

 Constructors​

 Constructor Overloading​

37
CONSTRUCTORS​

 It is a special type of method which is used to initialize the object.​

 Constructor is a block of codes similar to the method. ​

 It is called when an instance of the class is created. ​

 At the time of calling constructor, memory for the object is allocated.​

 At least one constructor will be invoked every time an object is created using the
new() keyword​.

 It calls a default constructor if there is no constructor available in the class.​

38
The rules for defining a constructor are.​

1. Constructor name must be the same as its class name

2. Constructor must have no explicit return type​

3. Constructor cannot be abstract, static and final

39
TYPES OF CONSTRUCTORS​

There are two types of constructors in Java:​

1. Default constructor (no-arg constructor)​


2. Parameterized constructor​

1) Java Default Constructor

 A constructor is called "Default Constructor" when it doesn't have any parameter.

 The default constructor is used to provide the default values to the object like 0,
null, etc..​

40
Example of default constructor​.
//Java Program to create and call a default constructor ​
class Bike1
{ ​
//creating a default constructor ​
Bike1()
{
System.out.println("Bike is created");
} ​
//main method ​
public static void main(String args[])
{ ​
//calling a default constructor ​
Bike1 b=new Bike1(); ​
} ​
} ​
41
Example of default constructor that public static void main(String args[])
displays the default values​ { ​
// //creating objects ​
Let us see another example of default construc Student3 s1=new Student3(); ​
tor ​ Student3 s2=new Student3(); ​
//which displays the default values ​ //displaying values of the object ​
class Student3 s1.display(); ​
{ ​ s2.display(); ​
int id; ​ } ​
String name; ​ } ​
//method to display the value of id and name ​
void display()
{
System.out.println(id+" "+name);
} ​
42
2. Parameterized Constructor​

java Parameterized Constructor​


A constructor which has a specific number of parameters is called a parameterized
constructor.​

Why use the parameterized constructor?​



The parameterized constructor is used to provide different values to objects.

Example of parameterized constructor​.

In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.​

43
Example of Parameterized Constructor​
class Student4
{ ​ public static void main(String args[])
int id; ​ { ​
String name; ​ //creating objects and passing values ​
//creating a parameterized constructor ​ Student4 s1 = new Student4(); ​
Student4(int i,String n) Student4 s2 = new Student4(222,"Aryan"); ​
{ ​ //
id = i; ​ calling method to display the values of object ​
name = n; ​ s1.display(); ​
} ​ s2.display(); ​
//method to display the values ​ } ​
void display() } ​
{
System.out.println(id+" "+name);
}​
44
Constructor Overloading in Java​

 A constructor is just like a method but without return type. ​

 Constructor can also be overloaded like Java methods.​

 Constructor overloading in Java is a technique of having more than one constructor


with ​different parameter lists. ​

 They are arranged in a way that each constructor performs a different task. ​

 They are differentiated by the compiler by the number of parameters in the list and
their types.​

45
Example of Constructor Overloading​
class Student5
{ ​ void display()
int id; ​ {​
String name; ​ System.out.println(id+" "+name+" "+age);​
int age; ​ } ​
//creating two arg constructor ​ ​
Student5(int i,String n) public static void main(String args[])
{ ​ { ​
id = i; ​ Student5 s1 = new Student5(111,"Karan"); ​
name = n; ​ Student5 s2 = new Student5(222,"Aryan",25); ​
}​ s1.display(); ​
//creating three arg constructor ​ s2.display(); ​
Student5(int i,String n,int a) } ​
{ ​ } ​
id = i; ​
name = n; ​
age=a; ​
} ​
46
TOPICS TO BE LEARNED FROM THIS CLASS​

Methods Overloading​

47
Methods Overloading​

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. ​

If we have to perform only one operation, having same name of the methods increases the
readability of the program. ​

Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as
other programmers to understand the behavior of the method because its name differs. ​
So, we perform method overloading to figure out the program quickly.​

48
ADVANTAGE OF METHOD OVERLOADING​

1.Method overloading increases the readability of the program.​


2.Different ways to overload the method​
3.There are two ways to overload the method in java​
4.By changing number of arguments​
5.By changing the data type​
6.In java, Method Overloading is not possible by changing the return type
of the method only.​

49
1) Method Overloading: changing no of arguments​

In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.​
In this example, we are creating static methods so that we don't need to create instance for calling
methods.​
class Adder
{ ​
static int add(int a,int b){return a+b;} ​
static int add(int a,int b,int c){return a+b+c;} ​
} ​
class TestOverloading1{ ​
public static void main(String[] args){ ​
System.out.println(Adder.add(11,11)); ​
System.out.println(Adder.add(11,11,11)); ​
}} ​

50
2) Method Overloading: changing data type of arguments​

In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.​
class Adder{ ​
static int add(int a, int b){return a+b;} ​
Output:​
static double add(double a, double b){return a+b;} ​
22​
} ​
24.9
class TestOverloading2{ ​
public static void main(String[] args){ ​
System.out.println(Adder.add(11,11)); ​
System.out.println(Adder.add(12.3,12.6)); ​
}} ​

51
Why Method Overloading is not possible by changing the return type of method only?​
In java, method overloading is not possible by changing the return type of the method only because of
ambiguity. Let's see how ambiguity may occur:​
class Adder{ ​
static int add(int a,int b){return a+b;} ​
static double add(int a,int b){return a+b;} ​
} ​
class TestOverloading3{ ​
public static void main(String[] args){ ​
System.out.println(Adder.add(11,11));//ambiguity ​
}} ​
Output:​
Compile Time Error: method add(int,int) is already defined in class Adder​
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be
called?​
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time
error if you declare the same method having same parameters.​

52
TOPICS TO BE LEARNED FROM THIS CLASS​

Static Members, Nesting of Methods​

53
Static Members​
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.​

The static keyword can be used with methods, fields, classes (inner/nested), blocks.​
Static Methods −
• we can create a static method by using the keyword static.
• Static methods can access only static fields, methods.
• To access static methods there is no need to instantiate the class, you can do it just
using the class name as​shown in the below example​
public class MyClass { ​
public static void sample(){​
System.out.println("Hello"); ​
}​
public static void main(String args[]){​
MyClass.sample(); ​
}​ 54
STATIC FIELDS​

•You can create a static field by using the keyword static.​


•Static variables are also called class variables​
•The static fields have the same value in all the instances of
the class. ​
•These are created and initialized when the class is loaded for
the first time. ​
•Just like static methods you can access static fields using the
class name (without instantiation).​
public class MyClass { ​
public static int data = 20; ​
public static void main(String args[]){​
System.out.println(MyClass.data); ​
}​
}​
​ 55
STATIC BLOCKS​

•These are a block of codes with a static keyword. ​


• In general, these are used to initialize the static members. ​
• JVM executes static blocks before the main method at the time of class loading.​
public class MyClass { ​
static{ ​
System.out.println("Hello this is a static block"); ​
}​
public static void main(String args[]){​
System.out.println("This is main method"); ​
}​
}​
Output​
Hello this is a static block This is main method​
56
NESTING OF METHODS​

 Nesting of Methods means method within method.​


 Java does not support “directly” nested methods. ​
 Many functional programming languages support method within method.

There are two methods to achieve nesting of methods​


1. Method 1 (Using anonymous subclasses)​
2. Method 2 (Using local classes)​

57
METHOD 1 (USING ANONYMOUS SUBCLASSES)​

•It is an inner class without a name and for which only a single object is created. ​
•An anonymous inner class can be useful when making an instance of an object with
certain “extras” such as overloading methods of a class or interface, without having
to actually subclass a class.​
•Anonymous inner classes are useful in writing implementation classes for listener
interfaces in graphics programming.​

58
EXAMPLE - ANONYMOUS INNER CLASS
Class a
{
public void show()
{
System.out.println(“nested class”);
}
}
Class anonumous
{
Public static void main(String args[])
{
a obj=new a()
{
public void show()
{
System.out.println(“this is anonyomous
class”);
}};
obj.show();
}}
59
METHOD 2 : USING LOCAL CLASSES​
•We can also implement a method inside a local class. ​
• A class created inside a method is called local inner class. ​
• To invoke the method of local inner class, we must instantiate the class inside method.​
/ Java program implements method inside
method ​ new Local().fun(); ​
public class method2 { ​ }​
public static void main(String[] args) ​

{​
// function have implementation of another ​ Display(); ​
// function inside local class ​ }​
void Display() ​ }​
{​
// local class ​
class Local { ​
void fun() ​
{​
System.out.println(“Hello"); ​
}​
60
}​
TOPICS TO BE LEARNED FROM THIS CLASS​

 INHERITANCE​

 TYPES OF INHERITANCE​

61
INHERITANCE​
Inheritance: Extending a Class​

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).​
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.​
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.​
Why use inheritance in java​
For Method Overriding (so runtime polymorphism can be achieved).​
For Code Reusability.​
62
Terms used in Inheritance

1. Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.

2. Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.​

3. Super Class/Parent Class: Super class is the class from where a subclass
inherits the features. It is also called a base class or a parent class.​

4. Reusability: As the name specifies, reusability is a mechanism


which facilitates you to reuse the fields and methods of the existing
class when you create a new class. You can use the same fields and methods
already defined in the previous class.​
63
INHERITANCE : SYNTAX ​

class A  The extends keyword indicates that we are making a new class
{ that derives from an existing class. ​
​//methods and fields  The meaning of "extends" is to increase the functionality.​
} ​  The relationship between the two classes is Programmer IS-
class B Extends A A Employee. ​
{ ​  It means that Programmer is a type of Employee.​

//methods and fields


} ​

64
Example of INHERITANCE​

class Employee
{ ​ Output​
float salary=40000; ​ Programmer salary is:40000.0 ​
} ​ Bonus of programmer is:10000 ​
class Programmer extends Employee
{ ​
int bonus=10000; ​
public static void main(String args[])
{ ​
Programmer p=new Programmer(); ​
System.out.println("Programmer salary is:"+p.salary); ​
System.out.println("Bonus of Programmer is:"+p.bonus); ​
} ​
} ​
65
TYPES OF INHERITANCE​

On the basis of class, there can be three types of inheritance in java:



1.Single Inheritance​
2.Multilevel Inheritance ​
3.Hierarchical Inheritance.​

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.​

Note: Multiple inheritance is not supported in Java through class.​

66
class Animal
1.Single Inheritance​ { ​
void eat()
{
•When a single class is derived from System.out.println("eating...");
a single parent class, it is } ​
called Single inheritance. ​ } ​
• The subclass class acquires the data class Dog extends Animal
members and variables of super class​ { ​
•It is the simplest form of all inheritances. ​ void bark()
{
System.out.println("barking...");
} ​
} ​
class SingleDemo
{ ​
public static void main(String args[])
{ ​
Dog d=new Dog(); ​
d.bark(); ​
d.eat(); ​
}​
} ​ 67
2.Multilevel Inheritance ​
class Dept{ ​
•When there is a chain of inheritance, it is void deptData(){System.out.println(“CS
known as multilevel inheritance. ​ Dept");} ​
• In Multilevel Inheritance, a derived class will } ​
be inheriting a base class and as well as the derived class class Emp extends Dept{ ​
also act as the base class to other class.​ void empData()
{System.out.println(“Abhilash");}​
} ​
class Salary extends Emp{ ​
void salData(){System.out.println(“50000");} ​
} ​
class MultiLevelDemo{ ​
public static void main(String args[]){ ​
Salary s1=new Salary(); ​
s1.salData(); s1.empData(); s1.deptData()​
}} ​

68
3.Hierarchical Inheritance.​

Class Animal{ ​
•When two or more classes inherits a single void eat(){System.out.println("eating...");} ​
class, it is known } ​
as hierarchical inheritance. ​ class Dog extends Animal{ ​
void bark(){System.out.println("barking..."); } ​
}​
class Cat extends Animal{ ​
void meow(){System.out.println("meowing...");} ​
} ​
class HierarchicalDemo{ ​
public static void main(String args[]){ ​
Dog d=new Dog(); Cat c=new Cat(); ​
d.bark(); d.eat();​
c.meow(); c.eat(); ​
}} ​

69
TOPICS TO BE LEARNED FROM THIS CLASS​

Overriding Methods​

70
Overriding Methods​

If subclass (child class) has the same method as


declared in the parent class, it is known as method
overriding in Java.​

•When a method in a subclass has the same name,


same parameters or signature, and same return type as a
method in its super-class, then the method in the
subclass is said to override the method in the super-
class.​
•The main advantage of method overriding is that the
class can give its own specific implementation
to a inherited method without even modifying the
parent class code.​
•Method overriding is possible only through inheritance​
•Method overriding is used for runtime polymorphism​

71
RULES FOR OVERRIDING METHODS

•The method must have the same name as in the parent class​.

•The method must have the same parameter as in the parent class.

•There must be an IS-A relationship (inheritance).​

72
Overriding Methods - Example of method overriding​

The name and parameter of the method are the same, and there is IS-A relationship between the classes, so
there is method overriding.​
//Creating a child class ​
/
Java Program to illustrate the use of Java Method O class Bike2 extends Vehicle
verriding ​ { ​
//Creating a parent class. ​ //defining the same method as in ​
the parent class ​
class Vehicle void run()
{ ​ {System.out.println("Bike is running safely");} ​
//defining a method ​ ​
void run() public static void main(String args[]){ ​
{ Bike2 obj = new Bike2();//creating object ​
System.out.println("Vehicle is running"); obj.run();//calling method ​
} ​ } ​
} ​ } ​
73
Another example of Java Method Overriding​

Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7%, and 9% rate of interest.

74
// class AXIS extends Bank{ ​
Java Program to demonstrate the real scenario int getRateOfInterest(){return 9;} ​
of Java Method Overriding ​ } ​
// //Test class to create objects and call the methods ​
where three classes are overriding the method class Test2{ ​
of a parent class. ​ public static void main(String args[]){ ​
//Creating a parent class. ​ SBI s=new SBI(); ​
class Bank{ ​ ICICI i=new ICICI(); ​
int getRateOfInterest(){return 0;} ​ AXIS a=new AXIS(); ​
} ​ System.out.println("SBI Rate of Interest: "+s.getRateOfIn
//Creating child classes. ​ terest()); ​
class SBI extends Bank{ ​ System.out.println("ICICI Rate of Interest: "+i.getRateOf
int getRateOfInterest(){return 8;} ​ Interest()); ​
} ​ System.out.println("AXIS Rate of Interest: "+a.getRateOf
class ICICI extends Bank{ ​ Interest()); ​
int getRateOfInterest(){return 7;} ​ } ​
} ​ } ​

75
Difference between method overloading and method overriding ​

No.​ Method Overloading​ Method Overriding​


1)​ Method overloading is used to increase Method overriding is used to provide the
the readability of the program.​ specific implementation of the method that is already
provided by its super class.​
2)​ Method overloading is performed within class.​ Method overriding occurs in two classes that have IS-
A (inheritance) relationship.​
3)​ In case of method overloading, parameter In case of method overriding, parameter must be same.​
must be different.​
4)​ Method overloading is the example Method overriding is the example of run
of compile time polymorphism.​ time polymorphism.​
5)​ In java, method overloading can't be Return type must be same in method overriding.​
performed by changing return type of the
method only. Return type can be same or
different in method overloading. But you must
have to change the parameter.​

76
TOPICS TO BE LEARNED FROM THIS CLASS​

Final Variables and Methods, Finalize Method​

77
FINAL VARIABLES AND METHODS, FINALIZER METHOD​

Final Keyword In Java​

The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:​
1.variable​
2.method​
3.class​
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.​

78
1) Java final variable: If you make any variable as final, you cannot change the value of
final variable(It will be constant).​
There is a final variable speed limit, we are going to change the value of this variable, but
It can't be changed ​
because final variable once assigned a value can never be changed.​
class Bike9{ ​
final int speedlimit=90;//final variable ​
void run(){ ​
speedlimit=400; ​
} ​
public static void main(String args[]){ ​
Bike9 obj=new Bike9(); ​
obj.run(); ​
} ​
}//end of class Output: Compile Time Error​

79
2) Java final method​
If you make any method as final, you cannot override it.​
class Bike{ ​
final void run(){System.out.println("running");} ​
} ​
class Honda extends Bike{ ​
void run(){System.out.println("running safely with 100kmph");} ​
public static void main(String args[]){ ​
Honda honda= new Honda(); ​
honda.run(); ​
} ​
}

Output: Compile Time Error​

80
3) Java final class​

If you make any class as final, you cannot extend it.​


final class Bike{} ​
class Honda1 extends Bike
{ ​
void run()
{
System.out.println("running safely with 100kmph");
} ​
public static void main(String args[])
{ ​
Honda1 honda= new Honda1(); ​
honda.run(); ​
} ​
}​
Output: Compile Time Error​

81
FINAL VARIABLES AND METHODS, FINALIZER METHOD​

Finalize Method - Java Object finalize() Method​

Java Object finalize() Method​


Finalize() is the method of Object class. This method is called just before an object is garbage collected. ​
finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory ​
Leaks.​
In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime ​
unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were ​
using free() function in C language and delete() in C++. But, in java it is performed automatically. ​
So, java provides better memory management.​
-----------​
Syntax : ​
protected void finalize() throws Throwable ​
Note: throws Throwable - the Exception is raised by this method​

82
Finalize Method - Example​

public class JavafinalizeExample1 { ​


public static void main(String[] args) ​
{ ​
JavafinalizeExample1 obj = new JavafinalizeExample1(); ​
System.out.println(obj.hashCode()); ​
obj = null; ​
// calling garbage collector ​
System.gc(); ​
System.out.println("end of garbage collection"); ​ Output​
} ​ 2018699554 ​
@Override ​ end of garbage collection ​
protected void finalize() ​ finalize method called ​
{ ​
System.out.println("finalize method called"); ​
} } ​

83
TOPICS TO BE LEARNED FROM THIS CLASS​

ABSTRACT METHODS AND CLASSES​

84
CLASSES, OBJECTS AND METHODS​
Abstract class in Java​

A class which is declared as abstract is known as


an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.​
Points to Remember​
1.An abstract class must be declared with an abstract
keyword.​
2.It can have abstract and non-abstract methods.​
3.It cannot be instantiated.​
4.It can have constructors and static methods also.​
5.It can have final methods which will force the
subclass not to change the body of the method.

85
Example of Abstract class that has an abstract abstract class Bike
{ ​
abstract void run(); ​
A method which is declared as abstract and does } ​
not have implementation is known as an abstract
method.​ class Honda4 extends Bike
Example of abstract method​ { ​
abstract void printStatus();// void run()
no method body and abstract ​ {System.out.println("running safely");
​ } ​
Example of Abstract class that has an abstract public static void main(String args[])
method​ { ​
In this example, Bike is an abstract class that Bike obj = new Honda4(); ​
contains only one abstract method run. Its obj.run(); ​
implementation is provided by the Honda class.​ } ​
} ​
Output: running safely​

86
Understanding the real scenario of Abstract class​

In this example, Shape is the abstract class, and its implementation is provided by the
Rectangle and Circle classes.​
Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.​
A factory method is a method that returns the instance of the class. We will learn about the
factory method later.​
In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.​
File: TestAbstraction1.java​
abstract class Shape
{ ​
abstract void draw(); ​
} ​

87
//In real scenario, implementation is provided by others i.e. unknown by end user ​
class Rectangle extends Shape{ ​
void draw()
{
System.out.println("drawing rectangle");} ​
} ​
class Circle1 extends Shape{ ​
void draw(){System.out.println("drawing circle");} ​
} ​
//In real scenario, method is called by programmer or user ​
class TestAbstraction1{ ​
public static void main(String args[])
{ ​
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method ​
s.draw(); ​
} }

Output: drawing circle


88
Abstract class having constructor, data member and methods​

An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.​
File: TestAbstraction2.java​
//Example of an abstract class that has abstract and non-abstract methods ​
abstract class Bike{ ​
Bike(){System.out.println("bike is created");} ​
abstract void run(); ​
void changeGear(){System.out.println("gear changed");} ​
} ​
//Creating a Child class which inherits Abstract class ​
class Honda extends Bike{ ​
void run(){System.out.println("running safely..");} ​
} ​

89
//Creating a Test class which calls abstract and non-abstract methods ​
class TestAbstraction2
{ ​
public static void main(String args[])
{ ​
Bike obj = new Honda(); ​
obj.run(); ​
obj.changeGear(); ​
} ​
} ​

Output:​
bike is created ​
running safely.. ​
gear changed​
90
TOPICS TO BE LEARNED FROM THIS CLASS​

Arrays, Strings & Vectors: Creating Arrays,


One Dimensional Arrays

91
ARRAYS

•Normally, an array is a collection of similar type of elements which have a


contiguous memory location. ​
•Java array is an object which contains elements of a similar data type. ​
•The elements of an array are stored in a contiguous memory location. ​
•We can store only a fixed set of elements in an array.​
•Array is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on. ​

92
•It is a data structure where we store similar elements. ​
•Unlike C/C++, we can get the length of the array using the length member.​
•In Java, array is an object of a dynamically generated class. ​
•Java array inherits the Object class,and implements the Serializable as well as Cloneable
interfaces. ​
• In Java, we can store primitive values or objects in an array.​
•We can create single dimensional or multi dimensional arrays. ​
Advantages​
•Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.​
•Random access: We can get any data located at an index position.​
Disadvantages​
•Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. ​
•To solve this problem, collection framework is used, which grows automatically.​
93
TYPES OF ARRAYS​

There are two types in arrays.​


1.Single Dimensional Array or One Dimensional Array ​
2.Multidimensional Array​

1.Single Dimensional Array or One Dimensional Array ​

•One dimensional array will have only one index point to store values​
•If the data is linear, we can use the One Dimensional Array. ​

94
Syntax to Declare an Array in Java​

dataType[] arr; (or) dataType arr[]; ​


Instantiation of an Array in Java​
arrayRefVar=new datatype[size]; ​
//Java Program to illustrate how to declare, instantiate, initialize
and traverse the Java array. ​
class Testarray{ ​
public static void main(String args[]){ ​
int a[]=new int[5]; //declaration and instantiation ​
a[0]=10; //initialization ​
a[1]=20; ​
a[2]=70; ​
a[3]=40; ​
for(int i=0;i<a.length;i++) //length is the property of array ​
System.out.println(a[i]); ​
}} ​ 95
Declaration, Instantiation and Initialization of Java Array​

We can declare, instantiate and initialize the java array together by:​
int a[]={80,30,40,50}; //declaration, instantiation and initialization

Let's see the simple example to print this array.​
//
Java Program to illustrate the use of declaration, instantiation and initialization of Java
array in a single line ​
class Testarray1{ ​
public static void main(String args[])
{ ​
int a[]={80,30,40,50}; //declaration, instantiation and initialization ​
for(int i=0;i<a.length;i++) //length is the property of array ​
System.out.println(a[i]); //printing array elements​
}} ​
96

ARRAY USING FOR-EACH LOOP​

•We can also print the Java array using for-


each loop. ​ Java Program to print the array elem
•The Java for-each loop prints the array ents using for-each loop ​
elements one by one.​ class ForEachArray{ ​
•It holds an array element in a variable, then public static void main(String args[]
executes the body of the loop.​ ){ ​
•The syntax of the for-each loop is given int a[]={33,3,4,5}; ​
below:​ for(int x:a) ​
for(datatype variable : array){ ​ System.out.println(x); ​
//body of the loop ​ }​
} ​ } ​

97
PASSING ARRAY TO A METHOD​
•We can pass the array to method as a parameter so that we can reuse the same logic
on any array. ​
class PassArray{ ​
static void min(int arr[]){ ​
int min=arr[0]; ​
for(int i=1;i<arr.length;i++) ​
if(min>arr[i]) ​
min=arr[i]; ​
System.out.println(min); ​
} ​
public static void main(String args[]){ ​
int a[]={33,3,4,5};//declaring and initializing an array ​
min(a);//passing array to method ​
}}
98
TWO DIMENSIONAL ARRAYS​

•The Two Dimensional Array is nothing but an Array of Arrays. ​


•In Two Dimensional Array, data stored in row and columns, and we can access the record
using both the row index and column index (like an Excel File).​
•To work with multi-level data, we have to use the Multi-Dimensional Array. ​
•Two Dimensional Array is the simplest form of Multi-Dimensional Array.​
•Java uses zero-based indexing, that is indexing of arrays will starts with 0.​

•Syntax:​
a[row_index][column_index]​

•For Example: ​
int[][] a = new int[3][4]; //array with 3 rows and 4 columns​

99
Two Dimensional Arrays - Example​

java Program to illustrate the use of two dimensional array ​


class Testarray3{ ​
public static void main(String args[]){ ​
//declaring and initializing 2D array ​
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; ​
//printing 2D array ​
for(int i=0;i<3;i++){ ​
for(int j=0;j<3;j++){ ​
Output:​
System.out.print(arr[i][j]+" "); ​
} ​ 123​
System.out.println(); ​ 245​
4 4 5​
} ​
}} ​

10
0
System.out.println(“Array B”);​
//Java Program to add 2 arrays ​
for(int i=0;i<3;i++){ ​
class Testarray4{ ​
for(int j=0;j<3;j++){ ​
public static void main(String args[]){ ​
System.out.println(b[i][j]+" "); ​
//declaring and initializing 2D array ​
} ​
int a[][]={{1,2,3},{2,4,5},{4,4,5}}; ​
System.out.println(); ​
int b[][]={{1,2,3},{4,5,6},{7,8,9}}; ​
} ​
System.out.println(“Array A”);​
System.out.println(“Sum of Array”);​
for(int i=0;i<3;i++){ ​
for(int i=0;i<3;i++){ ​
for(int j=0;j<3;j++){ ​
for(int j=0;j<3;j++){ ​
System.out.println(a[i][j]+" "); ​
System.out.println(a[i][j]+b[i][j]); ​
} ​
} ​
System.out.println(); ​
System.out.println(); ​
} ​
} }}

10
1
Jagged Array in Java​

It is an array of arrays with different number for (int i=0; i<arr.length; i++) ​
of columns.​ for(int j=0; j<arr[i].length; j++) ​
//Java Program to illustrate the jagged array ​ arr[i][j] = count++; ​
class TestJaggedArray{ ​ ​
public static void main(String[] args){ ​ //printing the data of a jagged array ​
// for (int i=0; i<arr.length; i++){ ​
declaring a 2D array with odd columns int for (int j=0; j<arr[i].length; j++){ ​
arr[][] = new int[3][]; ​ System.out.print(arr[i][j]+" "); ​
arr[0] = new int[3]; ​ } ​
arr[1] = new int[4]; ​ System.out.println();//new line ​
arr[2] = new int[2]; ​ } ​
//initializing a jagged array ​ } ​
int count = 0; ​ } ​

10
2
Strings​

10
3
Create String object: By string literal​

Generally, String is a sequence of characters. ​


But in Java, string is an object that represents a sequence of characters. ​
The java.lang.String class is used to create a string object.​
How to create a string object?​
There are two ways to create String object:​
1.By string literal​
2.By new keyword​
1) String Literal: Java String literal is created by using double quotes.​
For Example: String s="welcome"; ​
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in ​
the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string
instance ​
is created and placed in the pool. For example:​
String s1="Welcome"; ​
String s2="Welcome";//It doesn't create a new instance ​

10
4
In the above example, only one object will be created.
Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool, that is why it will
create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.​

Note: String objects are stored in a special memory
area known as the "string constant pool".​
Why Java uses the concept of String literal?​
To make Java more memory efficient (because no new
objects are created if it exists already in the string
constant pool).​

10
5
2) By new keyword​
String s=new String("Welcome");//creates two objects and one reference variable ​
In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s will
refer to the object in a heap (non-pool).​

public class StringExample


{ ​
public static void main(String args[]){ ​
String s1="java";//creating string by java string literal ​
String s2=new String(“programming"); //creating java string by new keyword ​
System.out.println(s1); ​
System.out.println(s2); ​
}

10
6
Java String class methods​

The java.lang.String class provides many useful methods to perform operations on sequence of
char values.​
No.​ Method​ Description​
1​ char charAt(int index)​ returns char value for the particular index​
2​ int length()​ returns string length​
3​ String substring(int beginIndex)​ returns substring for given begin index.​
4​ String substring(int beginIndex, int endIndex)​ returns substring for given begin index and end index.​

5​ boolean contains(CharSequence s)​ returns true or false after matching the sequence of char value.​

6​ static String join(CharSequence delimiter, CharSe returns a joined string.​


quence... elements)

7​ boolean equals(Object another)​ checks the equality of string with the given object.​

10
7
8​ String concat(String str)​ concatenates the specified string.​

9​ String replace(char old, char new)​ replaces all occurrences of the specified char value.​

10​ static String equalsIgnoreCase(String another)​ compares another string. It doesn't check case.​

11​ String[] split(String regex)​ returns a split string matching regex.​

12​ int indexOf(int ch)​ returns the specified char value index.​

13​ String toLowerCase()​ returns a string in lowercase.​

14​ String toUpperCase()​ returns a string in uppercase.​

15​ String trim()​ removes beginning and ending spaces of this string.​

10
8
Write a java program to implement few string operations (methods)​
import java.util.*;​
class StringOperation​
{​
public static void main(String[] args)​
{​
String str1=“Hello“;​
String str2=“Welcome";​
System.out.println(“Str1 length is :"+str1.length());​
System.out.println(“Str2 length is :"+str2.length());​
System.out.println("The concatenation is :"+str1.concat(“ System.out.println("Replacing ‘H' with ‘T' in
"+str2));​ str1 : "+str1.replace(‘H',‘T')); ​
System.out.println("The first character of " +str1+" ​
is: "+str1.charAt(0));​ }​
System.out.println("The uppercase of " +str1+" }​
is: "+str1.toUpperCase());​
System.out.println("The lowercase of " +str1+"
is: "+str1.toLowerCase());​
System.out.println("The “l" occurs at position in str2 :
" +str.indexOf(‘c’));​

​ 10
​ 9
Vectors​

11
0
Vectors in java​

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store
n-number of elements in it as there is no size limit. It is a part of Java Collection framework
since Java 1.2. It is found in the java.util package and implements the List interface.
It is similar to the ArrayList, but with two differences-​
•Vector is synchronized.​
•Java Vector contains many legacy methods that are not the part of a collections framework.​
Java Vector class Declaration​
public class Vector<E> ​
extends Object<E> ​
implements List<E>, Cloneable, Serializable

11
1
Java Vector Methods​
The following are the list of Vector class methods:​

SN​ Method​ Description​


1​ add()​ It is used to append the specified element in the given vector.​
2​ addAll()​ It is used to append all of the elements in the specified collection to the end of this Vector.​
3​ addElement()​ It is used to append the specified component to the end of this vector. It increases the
vector size by one.​
4​ capacity()​ It is used to get the current capacity of this vector.​
5​ clear()​ It is used to delete all of the elements from this vector.​
6​ contains()​ It returns true if the vector contains the specified element.​
7​ elementAt()​ It is used to get the component at the specified index.​
8​ firstElement()​ It is used to get the first component of the vector.​
9​ get()​ It is used to get an element at the specified position in the vector.​
10​ insertElementAt()​ It is used to insert the specified object as a component in the given vector at the
specified index.​
11​ isEmpty()​ It is used to check if this vector has no components.​
12​ iterator()​ It is used to get an iterator over the elements in the list in proper sequence.​

11
2
13​ lastElement()​ It is used to get the last component of the vector.​

14​ remove()​ It is used to remove the specified element from the vector. If the vector does not
contain the element, it is unchanged.​
15​ removeAll()​ It is used to delete all the elements from the vector that are present in the
specified collection.​
16​ removeAllElements()​ It is used to remove all elements from the vector and set the size of the vector to zero.​

17​ removeElement()​ It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.​
18​ removeElementAt()​ It is used to delete the component at the specified index.​

19​ replaceAll()​ It is used to replace each element of the list with the result of applying the operator
to that element.​
20​ set()​ It is used to replace the element at the specified position in the vector with the
specified element.​
21​ setElementAt()​ It is used to set the component at the specified index of the vector to the
specified object.​
22​ setSize()​ It is used to set the size of the given vector.​

23​ size()​ It is used to get the number of components in the given vector.​

24​ sort()​ It is used to sort the list according to the order induced by the specified Comparator.​

11
3
import java.util.*; ​
public class VectorExample { ​
public static void main(String args[]) { ​
Vector<String> vec = new Vector<String>(); //Create a vector ​
vec.add("Tiger"); ​
vec.add("Lion"); //Adding elements using add() method of List ​
vec.add("Dog"); ​
vec.add("Elephant"); ​
vec.addElement("Rat");
//Adding elements using addElement() method of Vector ​
vec.addElement("Cat"); ​
vec.addElement("Deer"); ​
System.out.println("Elements are: "+vec); ​
} ​
}

Output: Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]​
11
4
Wrapper Classes

11
5
Wrapper Classes​

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.​
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-
versa unboxing.​

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.​
​ 11
​ 6
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:​

Primitive Type​ Wrapper class​

boolean​ Boolean​
char​ Character​
byte​ Byte​
short​ Short​
int​ Integer​
long​ Long​
float​ Float​
double​ Double​

11
7
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[]){ ​
int a=20; //Converting int into Integer ​
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​

11
8
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:​
333

11
9
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; ​
12
0
Integer intobj=i; Long longobj=l; ​
Float floatobj=f; Double doubleobj=d; ​
Character charobj=c; 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 doublevalu
e=doubleobj; char charvalue=charobj; boolean boolvalue=boolobj;

12
1
//Printing primitives ​
System.out.println("---Printing primitive values---"); ​
System.out.println("byte value: "+bytevalue); System.out.println("short valu
e: "+shortvalue); ​
System.out.println("int value: "+intvalue); ​
System.out.println("long value: "+longvalue); System.out.println("float valu
e: "+floatvalue); System.out.println("double value: "+doublevalue); ​
System.out.println("char value: "+charvalue); System.out.println("boolean v
alue: "+boolvalue); ​
}} ​

12
2

You might also like