Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
53 views

Core Java Unit 2

The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, and initialization of objects. It defines a class as a template for creating objects with common properties. An object is an instance of a class and has state, behavior, and identity. Methods provide reusability of code by encapsulating reusable tasks. Objects can be initialized through reference variables, methods, or constructors. The document provides examples to explain these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Core Java Unit 2

The document discusses key concepts in object-oriented programming in Java including classes, objects, methods, and initialization of objects. It defines a class as a template for creating objects with common properties. An object is an instance of a class and has state, behavior, and identity. Methods provide reusability of code by encapsulating reusable tasks. Objects can be initialized through reference variables, methods, or constructors. The document provides examples to explain these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

SWAMI VIVEKANAND COLLEGE OF COMPUTER SCIENCE

BCA SEM - VI

SUBJECT – 604 Core Java

Unit - 2

Unit – 2 Programming in Java


TOPIC – 1 Class, Object and Methods.
TOPIC – 2 Polymorphism: Method Overloading.
TOPIC – 3 Constructor: Concept of Constructor, Types of
Constructor, Constructor Overloading.
TOPIC – 4 Garbage Collection, Finalize() Method.
TOPIC – 5The ‘this’ keyword.
TOPIC – 6 ‘static’ and ‘final’ keyword.
TOPIC – 7 Access Control: Public, Private, Protected and Default.

Prepared By:-BhaveshMehta
(bdmehta3300@gmail.com)

1
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java

TOPIC – 1
Class, Object and Methods
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
 Nested class and interface
Core properties include the data types and methods that may be used by the object. All class
objects should have the basic class properties.
Classes are categories, and objects are items within each category.
Class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method,
with the static keyword.
The General Form of a Class:
classclsName
{
// instance variable declaration
type1 varName1 = value1;
type2 varName2 = value2;
:
typeNvarNameN = valueN;
// Methods
rType1 methodName1(mParams1)
{
// body of method
}
:
:
rTypeNmethodNameN(mParamsN)
{
// body of method
}
}
Example of a General Class
Class clsSample
{
// Variables
static intctr;
inti;

PREPARED BY: Bhavesh Mehta Page 2 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
int j;

// Methods
int addition()
{
ctr++;
returni + j;
}
Int NumberOfInstances()
{
return ctr;
}
}
Nested class(Inner Classes):
“When we create class within a class is known as nested or inner class.”
Java supports inner classes, which are classes that can be defined in any scope.
This means that a class can be defined as a member of another class, within a block of
statements.
An inner class's name is not visible outside its scope, except in a fully qualified name.
The ability to nested classes allows any top-level class to provide a package-style for a logically
related group of secondary top-level classes.
Program :-
class Outer
{
Intouter_x=100;
void test()
{
Inner inner = new Inner();
inner.display();
}
//this is an inner class
class Inner
{
void display()
{
System.out.println("outer x ="+outer_x); // 100
}
}
}
Class InnerClassDemo
{
public static void main(String args[])
{
Outer outr = new Outer();
outr.test();
}
}

Object:
An Entity that has state and behavior is known as an object.
For example, chair, bike, marker, pen, table, car etc.
PREPARED BY: Bhavesh Mehta Page 3 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
It can be physical or logical.
The example of logical object is banking system.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.
An object has three characteristics:
o State: represent data of an object. For example name of an object, colour etc.
o Behavior: represent the behavior (functionality) of an object such as deposit,
withdrawal etc..
o Identity: object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.

Declaring Objects:
You can create a class, you are creating a new data type. You can use this type of declare objects
of that type.
Obtaining of a class is a two step process.
First you must declare a variable of the class type. Second you must acquire an actual, physical
copy of the object and assign it to that variable.
You can do this using the new operator. The new operator dynamically allocates memory for
an object and returns a reference to it.
Syntax to declare an object :
Class_nameobject_variable = new class_name ();
Example :
class objdecl
{
class box
{
Int width, height, depth;
}
public static void main (String args[])
{
box b = new box();
}
}

Initialization of object in Java:


There are 3 ways to initialize object in Java.

By reference variable
o 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.
o Example:
class Student{
int id;
PREPARED BY: Bhavesh Mehta Page 4 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
By method
o 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 state (data) of the
objects by invoking the displayInformation() method.
o Example:
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

By constructor
o We will learn in upcoming chapter.

Method:
In general, a method is a way to perform some task. Similarly, the method in Java is a collection
of instructions that performs a specific task.
It provides the reusability of code. We can also easily modify code using methods.
We write a method once and use it many times. We do not require to write code again and
again.
It also provides the easy modification and readability of code, just by adding or removing a
chunk of code.
The method is executed only when we call or invoke it.

PREPARED BY: Bhavesh Mehta Page 5 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header, as
we have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
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
subtraction of two numbers, the method name must be subtraction(). A method is invoked 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.
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.

Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()

PREPARED BY: Bhavesh Mehta Page 6 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
It is also possible that a method has the same name as another method name in the same class,
it is known as method overloading.

Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
o In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods.
o 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.
o Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
o When we call any of the predefined methods in our program, a series of codes related
to the corresponding method runs in the background that is already stored in the
library.
o Each and every predefined method is defined inside a class.
o Such as print() method is defined in the java.io.PrintStream class.
o It prints the statement that we write inside the method. For example, print("Java"), it
prints Java on the console.
User-defined Method
o The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.

Call a Method
o To call a method in Java, write the method's name followed by two parentheses () and
a semicolon;
o In the following example, myMethod() is used to print a text (the action), when it is
called:
o Example:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}

TOPIC – 2
Polymorphism: Method Overloading.
Introduction to polymorphism:
Polymorphism, which literally means “different forms”.
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
The most common use of polymorphism in OOP occurs when a parent class reference is used to
refer to a child class object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
PREPARED BY: Bhavesh Mehta Page 7 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the
object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
We can perform polymorphism in java by method overloading and method overriding.
There are two types of polymorphism in Java: compile-time polymorphism (Static
polymorphism) and runtime polymorphism (Dynamic Method Dispetch).
o Compile Time Polymorphism (Static Polymorphism):
o This type of polymorphism is achieved by creating multiple methods with the same
name in the same class, but with each one having different numbers of parameters or
parameters of different data types.
o In the example below, notice that the three methods have the same name, but each
accepts a different number of parameters or different data types:
class Multiplier {
static void Multiply(int a, int b)
{
System.out.println("Integer Multiplication, Result = "+ a*b);
}
// Method 2
static void Multiply(double a, double b)
{

System.out.println("double Multiplication, Result = "+ a*b);

}
// Method 3
static void Multiply(double a, double b, double c)
{
System.out.println("Three parameters, double Multiplication, Result = "+ a*b*c);

}
}
public class Main {
public static void main(String[] args) {
// using the first method
Multiplier.Multiply(3,5);
// using the second method
Multiplier.Multiply(3.5,5.1);
// using the third method
Multiplier.Multiply(3.6,5.2, 6.3);
}
}

o Run Time Polymorphism (Dynamic Method Dispatch):


o This type of polymorphism occurs when a child class has its own definition of one of
the member methods of the parent class. This is called method overriding. In most
cases, runtime polymorphism is associated with upcasting. This is when a parent class
points to an instance of the child’s class.
o Here’s an example:

PREPARED BY: Bhavesh Mehta Page 8 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
// Super Class
class Shape{
protected double length;
Shape(double length){
this.length = length;
}
void area(){
}
}
// Child class
class Square extends Shape{
//constructor
Square(double side){
super(side); // calling the super class constructor
}
//Overriding area() method
void area(){
System.out.println("Square Area = " + length*length);
}
}
// Child class
class Circle extends Shape{
//constructor
Circle(double radius){
super(radius); // calling the super class constructor
}
//Overriding area() method
void area(){
System.out.println("Circle Area = " + 3.14*length*length);;
}
}
public class Main {
public static void main(String[] args){
Shape shape = new Square(5.0);
// calling the area() method of the Square Class
shape.area();
shape = new Circle(5.0); // upcasting
// calling the area() method of the Circle Class
shape.area();
}
}
Advantage and Disadvantage of polymorphism
Advantage:
o It allows programmers to reuse, evaluate and execute the program, modules, forms
written once. In certain aspects, they can be repeated.
o You may use the odd variable name to stock variables of different types of data, such as
Int, Float, etc.).
o Polymorphism tends to reduce the pairing of multiple functionalities.
o Method overloading can be extended to builders that allow multiple ways of initializing
class objects. It helps you to identify several builders for managing various forms of
initializations.
PREPARED BY: Bhavesh Mehta Page 9 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
o Method overriding functions along with inheritance without the need for re-compilation
to allow code reuse of existing groups.
Disadvantage:
o One of the key drawbacks of polymorphism is that the implementation of polymorphism
in codes is complicated for developers.
o Polymorphism in run time will lead to the performance problem where the system has to
determine which process or variable to invoke so that the performance is effectively
diminished as decisions are taken at run time.
o The readability of the program is diminished by polymorphism. In order to define real
execution time, one has to recognize the program’s runtime actions.

Difference between Polymorphism and Inheritance

Inheritance Polymorphism
Inheritance is one in which a new class Whereas polymorphism is what can be
(derived class) is formed that inherits characterized in different ways.
1 1
the characteristics from the current
class(base class).
Basically, it is used for lessons. Whereas functions or techniques are
2 2
simply implemented.
The principle of reusability is Polymorphism enables the object to
supported by inheritance and determine which function type is to be
3 3
decreases code length in object- enforced at both compile-time
oriented programming. (overloading) and run-time (overriding).
Inheritance may be an inheritance of Whereas-time polymorphism (overload)
4 pure, mixed, mixed, hierarchical and 4 as well as run-time polymorphism
multilevel. (overriding) can be compiled.
5 In pattern building, it is used. 5 Since it is also used in creating patterns.

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

Advantage of method overloading


o Method overloading increases the readability of the program.

Different ways to overload the method


o There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
 By 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
PREPARED BY: Bhavesh Mehta Page 10 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
 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));
}}
 By 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;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

TOPIC – 3
Constructor: Concept of Constructor, Types of Constructor, Constructor
Overloading.

Introduction to Constructor:
“A constructor is used to initialize the objects of its class.”
When you create an object, you typically want to initialize its member variables.
It is special because its name is the same as the class name.
The constructor is invoked automatically whenever an object of its associated class is
created.
It is called constructor because it construct the values of data member of the class.
The constructor is a special method you can implement in all your classes; it allows you
to initialize variables and perform any other operations when an object is created from
the class.

Characteristics of Constructor:
The constructor has always the same name as the class
If we don’t define any constructor than compiler automatically define it.
There is no return type define in the constructor.
There is no return statement require in the body of the constructor.
We can use “this” to call another constructor in the same class.
We can use “super” to call a constructor in a parent class.

Syntax
Following is the syntax of a constructor:
class ClassName

PREPARED BY: Bhavesh Mehta Page 11 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
{
ClassName()
{

}
}

Types of Constructor:
There are three types of constructors (1) Default (2) Parameterized (3) Copy
o Default constructor:
o A constructor is called "Default Constructor" when it doesn't have any parameter.
o If there is no constructor in a class, compiler automatically creates a default
constructor.
o This type of constructor is not visible in the program; it automatically creates without
definition and declaration in the class.
 Syntax of default constructor:
<class_name>(){}
 Example:
/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();
}
}
o Parameterized constructor:
o It contains parameters (or arguments) in the constructor definition and declaration.
More than one argument can also be passed through parameterized constructor in
Java.
 Syntax of default constructor:
<class_name>(<datatype><var1>,…….,<datatype><varN>){}
 Example:
class Rectangle
{
double length;
double breadth;

Rectangle()
{
length = 10;
breadth = 20;
}

Rectangle(double l, double b)
{
length = l;
breadth = b;
}
PREPARED BY: Bhavesh Mehta Page 12 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java

double calculateArea()
{return length*breadth;}
}

class Rectangle_Main {
public static void main(String[] args) {
double area;
Rectangle myrec = new Rectangle(41,56);
area = myrec.calculateArea();
System.out.println("The area of Rectangle: " +area);
}
}

o Copy constructor:
o A copy constructor is a special type constructor which creates an object using another
object of the same class. In return, it gives a copy of an already created object that is
copied.
 Syntax of default constructor:
<class_name>(<class name><Obj_var1>,…….,<class name><Obj_varN>){}
 Example:
class Rectangle
{
private double length;
private double breadth;

//constructor to initialize variables


Rectangle(double l, double b)
{
length = l;
breadth = b;
}

//copy constructor
Rectangle(Rectangle rect)
{
System.out.println("Copy Constructor Invoked!!");
length = rect.length;
breadth = rect.breadth;
}
//method to return area
double calculateArea()
{
return length*breadth;
}
}

class Rectangle_Main{

public static void main(String[] args)


{
PREPARED BY: Bhavesh Mehta Page 13 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
Rectangle rec1 = new Rectangle(10,20);
System.out.println("Area of the First Rectangle "+ rec1.calculateArea());

//passing the parameter to the copy constructor


Rectangle rec2 = new Rectangle(rec1);
System.out.println("Area of the Second Rectangle "+ rec2.calculateArea());
}
}

Difference between Java Constructor and Java Method:


Java Constructor Java Method
Name of a constructor is same name as Name of the method can
1 1
that of the class. be different from the class name.
2 Constructor has no return type. 2 Method must have a return type.
Constructors are invoked implicitly by Methods are invoked explicitly by
3 3
system. programmer.
Constructors are executed only when Methods are executed when
4 4
the object is created. we explicitly call it.

Constructor overloading:
“When we declare more than one constructor in a class is known as constructor
overloading or multiple constructor.”
Ex :-
// Multiple Constructor or constructor overloading
class Box
{
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob)
{
// pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// parameterized constructor
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// default constructor
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
PREPARED BY: Bhavesh Mehta Page 14 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
}
// parameterized constructor to assign same value to all the variables
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class ConstructorOver
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15); // 3 parameter constructor call
Box mybox2 = new Box(); //default constructor call
Box mycube = new Box(7); //1 parameterized constructor call
Box myclone = new Box(mybox1);// object as parameter constructor call
doublevol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);//3000.0

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);//-1.0

//get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);//343.0

//get volume of clone


vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);//3000.0
}
}

Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Volume of myclone is 3000.0

PREPARED BY: Bhavesh Mehta Page 15 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java

TOPIC – 4
Garbage Collection, Finalize () Method

Garbage Collection:
Garbage Collection in Java is a process by which the programs perform memory management
automatically.
The Garbage Collector(GC) finds the unused objects and deletes them to reclaim the memory.
In Java, dynamic memory allocation of objects is achieved using the new operator that uses
some memory and the memory remains allocated until there are references for the use of the
object.
When there are no references to an object, it is assumed to be no longer needed, and the
memory, occupied by the object can be reclaimed.
There is no explicit need to destroy an object as Java handles the de-allocation automatically.
The technique that accomplishes this is known as Garbage Collection. Programs that do not de-
allocate memory can eventually crash when there is no memory left in the system to allocate.
These programs are said to have memory leaks.
Garbage collection in Java happens automatically during the lifetime of the program,
eliminating the need to de-allocate memory and thereby avoiding memory leaks.
In C language, it is the programmer’s responsibility to de-allocate memory allocated
dynamically using free() function. This is where Java memory management leads.
Note: All objects are created in Heap Section of memory.

Example of Garbage Collector Mechanism in Java


Copy the following code into an editor.
class Student{
int a;
int b;

public void setData(intc,int d){


a=c;
b=d;
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.setData(1,2);
s2.setData(3,4);
s1.showData();
s2.showData();
//Student s3;
//s3=s2;
//s3.showData();
//s2=null;
//s3.showData();
//s3=null;
//s3.showData();
PREPARED BY: Bhavesh Mehta Page 16 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
}
}
Save, Compile and Run the code. As shown in the diagram, two objects and two reference
variables are created.

Uncomment line # 20,21,22. Save, compile & run the code.


As shown in the diagram below, two reference variables are pointing to the same object.

Uncomment line # 23 & 24. Compile, Save & Run the code
As show in diagram below, s2 becomes null, but s3 is still pointing to the object and is not
eligible for java garbage collection.

PREPARED BY: Bhavesh Mehta Page 17 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
Uncomment line # 25 & 26. Save, Compile & Run the Code
At this point there are no references pointing to the object and becomes eligible for garbage
collection. It will be removed from memory, and there is no way of retrieving it back.

The mechanism to release memory automatically which is occupied by an object is known as


Garbage Collection (GC).
Java takes a different approach; it handles deallocation for you automatically.
The technique that accomplishes this is called garbage collection.
a. It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
b. Java allows you to create as many objects as you want and you never have to worry about
destroying them.
You can ask the garbage collector to run at any time by calling system’s gc method :
System.gc( );

finalize( ) method:
The mechanism to destroy reference file or external resources which are used in your program,
is known as finalize( ) method.
Sometimes an object will need to perform some action when it is destroyed.
For example, if an object is holding some non-Java resource such as a file handle or window
character font, then you might want to make sure these resources are freed before an object is
destroyed.
To handle such situations, Java provides a mechanism called finalization.
By using finalization, you can define specific actions that will occur when an object is just about
to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize ( ) method.
Inside the finalize( ) method you will specify those actions that must be performed before an
object is destroyed(before gc called).
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
It is important to understand that finalize ( ) is only called just prior to garbage collection.

How does the finalize() Method Work with Garbage Collection?


PREPARED BY: Bhavesh Mehta Page 18 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
As explained earlier, JVM calls the garbage collector to delete unreferenced objects. After
determining the objects that have no links or references, it calls the finalize() method which
will perform the clean activity and the garbage collector destroys the object.
Let's see a code to understand this:
public class Demo
{
public static void main(String[] args)
{
String a = "Hello World!";
a = null; // unreferencing string object
}
}

In the above program, when the String object a holds value Hello World! it has a reference to an
object of the String class. But, when it holds a null value it does not have any reference. Hence,
it is eligible for garbage collection. The garbage collector calls finalize() method to perform
clean-up before destroying the object.

When to Use finalize() Method in Java?


Garbage collection is done automatically in Java which is handled by JVM, and it uses finalize
method in Java for releasing the resources of the object, that has to be destroyed.
finalize() method gets called only once by GC, if an exception is thrown by finalizing method or
the object revives itself from finalize(), the garbage collector will not call the finalize() method
again.
It's not guaranteed if the finalized method will be called or not, or when it will be called.
Relying completely on finalization to release resources is not recommended.
There are other ways to release the used resources in Java like the close() method in case of file
handling or destroy() method. But, the issue with these methods is they don't work
automatically, we have to call them manually every time.
In such cases, to improve the chances of performing clean-up activity, we can
use finalize() method in final block. finally block will execute finalize() method even though the
user has used close() method manually.
We can use finalize() method to release all the resources used by the object, in finally block by
overriding finalize() method. An example of overriding finalize method is given in the next
section of this article.

Final vs Finally vsfinalize() in Java


Java has 3 different keywords used in different scenarios final, finally, and finalize. These are
different keywords with completely different functionalities. Let's understand their uses and
differences:
final finally finalize
finally block is used in Java
final is a keyword and Exception Handling to execute
finalize() is the method in Java.
access modifier in Java. the mandatory piece of code
after try-catch blocks.
final access modifier is finally block executes whether finalize() method is used to
used to apply restrictions an exception occurs or not. It is perform clean-up processing just
on the variables, methods, primarily used to close before an object is garbage
and classes. resources. collected.

PREPARED BY: Bhavesh Mehta Page 19 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
final finally finalize
It is used with variables, It is with the try-catch block in
It is used with objects.
methods, and classes. exception handling.
Once declared, the final finalize method performs the
finally block cleans up all the
variable becomes constant cleaning with respect to the object
resources used in the try block.
and can't be modified. before its destruction.
finally block executes as soon
as the execution of try-
final is executed only when finalize method is executed just
catch block is completed
we call it. before the object is destroyed.
without depending on the
exception.

When to Use finalize() Method in Java?


Garbage collection is done automatically in Java which is handled by JVM, and it uses finalize
method in Java for releasing the resources of the object, that has to be destroyed.
finalize() method gets called only once by GC, if an exception is thrown by finalizing method or
the object revives itself from finalize(), the garbage collector will not call the finalize() method
again.
It's not guaranteed if the finalized method will be called or not, or when it will be called.
Relying completely on finalization to release resources is not recommended.
There are other ways to release the used resources in Java like the close() method in case of file
handling or destroy() method. But, the issue with these methods is they don't work
automatically, we have to call them manually every time.
In such cases, to improve the chances of performing clean-up activity, we can use finalize() m

TOPIC – 5
The ‘this’ keyword.

Introduction:
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter).
If you omit the keyword in the example above, the output would be "0" instead of "5".
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of “this” keyword in java


Here is given the 6 usage of java this keyword.
o this can be used to refer current class instance variable.

PREPARED BY: Bhavesh Mehta Page 20 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
 The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
 Understanding the problem without this keyword
 Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
 In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
 Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
PREPARED BY: Bhavesh Mehta Page 21 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
s1.display();
s2.display();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0

o this can be used to invoke current class method (implicitly)


 You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method. Let's see the example

o this() can be used to invoke current class constructor.


 The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor. In other words, it is used for constructor chaining.
 Calling default constructor from parameterized constructor:
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello a
10

o this can be passed as an argument in the method call.


 The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
PREPARED BY: Bhavesh Mehta Page 22 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
method is invoked

o this can be passed as argument in the constructor call.


 We can pass the this keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
1.

o this can be used to return the current class instance from the method.
 We can return this keyword as an statement from the method. In such case, return type of
the method must be the class type (non-primitive). Let's see the example:
 Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
 Example
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}

PREPARED BY: Bhavesh Mehta Page 23 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

TOPIC – 6
‘static’ and ‘final’ keyword.

Static Keyword:
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.
The static can be:
o Variable (also known as a class variable)
o Method (also known as a class method)
o Block
o Nested class
 Java static variable
o If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
 The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
o It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
o Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and
name, so instance data member is good in such case. Here, "college" refers to the
common property of all objects. If we make it static, this field will get the memory only
once.
Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}

PREPARED BY: Bhavesh Mehta Page 24 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS

 Java static method


o If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
o Example of static method
o //Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
PREPARED BY: Bhavesh Mehta Page 25 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

 Java static block


Is used to initialize the static data member.
It is executed before the main method at the time of class loading.
Example of static block
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main

 nested class
o A static class is a class that is created inside a class, is called a static nested class in Java.
It cannot access non-static data members and methods. It can be accessed by outer class
name.
 It can access static data members of the outer class, including private.
 The static nested class cannot access non-static (instance) data members or
o Java static nested class example with instance method
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
PREPARED BY: Bhavesh Mehta Page 26 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
o In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of the Outer class
because the nested class is static and static properties, methods, or classes can be
accessed without an object.

Final Keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
 variable
 method
 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.
 Java final variable
o If you make any variable as final, you cannot change the value of final variable(It will be
constant).
o Example of final variable
 There is a final variable speedlimit, 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
 Java final method
o If you make any method as final, you cannot override it.
o Example of final method
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();
PREPARED BY: Bhavesh Mehta Page 27 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
honda.run();
}
}
Output: Compile Time Error
 Java final class
o If you make any class as final, you cannot extend it.
o Example of final class
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

TOPIC – 7
Access Control: Public, Private, Protected and Default.

Access Modifier or Control:


There are two types of modifiers in Java: access modifiers and non-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:
 Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
 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.
 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.
 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.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
 Private
o The private access modifier is accessible only within the class.
o Simple example of private access modifier
 In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

PREPARED BY: Bhavesh Mehta Page 28 /30


SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core 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
}
}
 Default
o If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
o Example of default access modifier
 In this example, we have created two packages pack and mypack. We are accessing
the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.
//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
o The protected access modifier is accessible within package and outside the package but
through inheritance only.
o The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
o It provides more accessibility than the default modifer.
o Example of protected access modifier
 In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg
method of this package is declared as protected, so it can be accessed from outside
the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.*;

class B extends A{
PREPARED BY: Bhavesh Mehta Page 29 /30
SHREE ADARSH BCA COLLEGE – HADADAD
BCA SEM - VI Unit-2 604- Core Java
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output: Hello

 Public
o The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
o Example of public access modifier
//save by A.java

public class A{
public 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();
obj.msg();
}
}
Output: Hello

PREPARED BY: Bhavesh Mehta Page 30 /30

You might also like