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

JAVA-Notes-Unit-1_Part 2

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including key principles such as encapsulation, abstraction, inheritance, and polymorphism. It explains the significance of classes and objects, constructors, and methods, along with their applications in various software development areas. Additionally, it covers the types of constructors in Java and their roles in initializing objects.

Uploaded by

kishore0331
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JAVA-Notes-Unit-1_Part 2

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including key principles such as encapsulation, abstraction, inheritance, and polymorphism. It explains the significance of classes and objects, constructors, and methods, along with their applications in various software development areas. Additionally, it covers the types of constructors in Java and their roles in initializing objects.

Uploaded by

kishore0331
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Fundamentals of Object Oriented Programming PART-2


Object-Oriented Paradigm, Basic Concepts of Object Oriented Programming,
Applications of OOP. Concepts of classes, objects, constructors, methods, access
control, this keyword, garbage collection, overloading methods and constructors,
parameter passing, recursion, static keyword, nested and inner classes, Strings, Object
class.

Object-Oriented Paradigm
The object-oriented paradigm in Java is a programming model that uses objects
to represent and manipulate data. It's a widely used approach in software development.

Key concepts of Object-Oriented Programming


 Encapsulation
Wrapping up of data into a single unit i.e Bundles data and the methods place
it into a class. This protects data from being accessed by other classes.
 Abstraction
Showing the essential features and hiding their implementation details i.e
Exposes only the essential information of an object to the user, hiding their
implementation details.
 Inheritance
Acquire the properties from one class to other class i.e allows objects to
inherit properties and behaviors from other objects.
 Polymorphism
It means many forms i.e the ability of an object to take on multiple forms,
meaning a single method can behave differently depending on the object it is
called on, allowing you to treat objects of different types as if they were the
same type, as long as they share a common interface or inheritance
relationship; essentially, it enables a single action to be performed in different
ways depending on the context, making code more flexible and reusable.
Benefits of Object-Oriented Programming
 It enables developers to write modular, reusable, and maintainable code.
 It allows objects to interact with each other to create powerful applications.
 It helps developers create scalable Java applications.

B.Tech (CSE-DS)-II-II Sem Page 1


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Basic Concepts of Object Oriented Programming


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and maintenance
by following the basic principles of OOPs

 Object
 Class
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism

 Object: It represents real-world entities.


It has two characteristics (state and behavior). Some of the real-world objects
are book, mobile, table, computer, etc. An object is a variable of the type class, it is a
basic component of an object-oriented programming system. A class has
the methods and data members (attributes), these methods and data members are
accessed through an object. Thus, an object is an instance of a class.

An object mainly consists of:


1. State: It is represented by the attributes of an object. It also reflects the properties
of an object.

B.Tech (CSE-DS)-II-II Sem Page 2


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

2. Behavior: It is represented by the methods of an object. It also reflects the response


of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact with other
objects.
4. Method: A method is a collection of statements that perform some specific task
and return the result to the caller.

// create a Student class


public class Student
{
// Declaring attributes
String name;
int rollNo;
String section;

// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(name+ ", " + rollNo + ", " + section);
}

public static void main(String[] args)


{
// create student objects
Student st = new Student("Rahul", 6766, "B");

// print student details


st.printDetails();
}
}

B.Tech (CSE-DS)-II-II Sem Page 3


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

 Class: Blueprint of an objects or Collection of Objects

In object-oriented programming, a class is a blueprint from which individual


objects are created. In Java, everything is related to classes and objects. Each class has
its methods and attributes that can be accessed and manipulated through the objects.

class declaration can include the following components in order:

1. Modifiers: A class can be public or have default access


2. Class name: The class name should begin with the initial letter capitalized by
convention.
3. Body: The class body is surrounded by braces, { }.

// create a Student class


public class Student
{
// Declaring attributes
String name;
int rollNo;
String section;

// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}

B.Tech (CSE-DS)-II-II Sem Page 4


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(name+ ", " + rollNo + ", " + section);
}
}

 Encapsulation: Wrapping up of data into a single unit


In an object-oriented approach, encapsulation is a process of binding the data
members (attributes) and methods together. The encapsulation restricts direct access to
important data. The best example of the encapsulation concept is making a class where
the data members are private and methods are public to access through an object. In this
case, only methods can access those private data.
// create a Student class
public class Student
{
// Declaring private attributes
private String name;
private int rollNo;
private String section;

// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.println("Student Details: ");
System.out.println(this.name+ ", " + this.rollNo + ", " + section);
}

B.Tech (CSE-DS)-II-II Sem Page 5


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

public static void main(String[] args)


{
// create student objects
Student st = new Student("Rahul", 6766, "B");

// print student details


st.printDetails();

}
}

 Abstraction: Showing the Essential Features and hiding their implementation details

In object-oriented programming, an abstraction is a technique of hiding internal


details and showing functionalities. The abstract classes and interfaces are used to
achieve abstraction in Java.

The real-world example of an abstraction is a Car, the internal details such as the
engine, process of starting a car, process of shifting gears, etc. are hidden from the
user, and features such as the start button, gears, display, break, etc are given to the
user. When we perform any action on these features, the internal process works.

abstract class Vehicle


{
public void startEngine()
{
System.out.println("Engine Started");
}
}

B.Tech (CSE-DS)-II-II Sem Page 6


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

public class Car extends Vehicle


{
private String color;
public Car(String color)
{
this.color = color;
}
public void printDetails()
{
System.out.println("Car color: " + this.color);
}
public static void main(String[] args)
{
Car car = new Car("White");
car.printDetails();
car.startEngine();
}
}

 Inheritance : Acquire the properties from one class to other class

In object-oriented programming, inheritance is a process by which we can reuse


the functionalities of existing classes to new classes.

We are achieving inheritance by using extends keyword. Inheritance is also


known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
 Superclass: The class whose features are inherited is known as superclass (also
known as base or parent class).

B.Tech (CSE-DS)-II-II Sem Page 7


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

 Subclass: The class that inherits the other class is known as subclass (also known
as derived or extended or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.

// base class for all students


class Person
{
String name;
Person(String name)
{
this.name = name;
}
}
// create a Student class
public class Student extends Person
{
// Declaring attributes
int rollNo;
String section;
// initialize attributes
Student(String name, int rollNo, String section)
{
super(name);
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(this.name+ ", " + this.rollNo + ", " + section);
}

B.Tech (CSE-DS)-II-II Sem Page 8


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

public static void main(String[] args)


{
// create student objects
Student st = new Student("Rohith", 6766, "B Sec");
// print student details
st.printDetails();
}
}

 Polymorphism

The term "polymorphism" means "many forms". In object-oriented


programming, polymorphism is useful when you want to create multiple forms with
the same name of a single entity.

Polymorphism in Java is mainly of 2 types as mentioned below:

1. Method Overloading
2. Method Overriding

1. Method Overloading: Also, known as compile-time polymorphism, is the


concept of Polymorphism where more than one method share the same name with
different signature (Parameters) in a class. The return type of these methods can or
cannot be same.
2. Method Overriding: Also, known as run-time polymorphism, is the concept of
Polymorphism where method in the child class has the same name, return-type
and parameters as in parent class. The child class provides the implementation in
the method already written in the parent class.

B.Tech (CSE-DS)-II-II Sem Page 9


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

// Method Overloading and Overriding


// Parent Class
class Parent
{
// Method Declared
public void m1()
{
System.out.println("Parent Method m1 executed");
}
// Method Overloading
public void m1(int a)
{
System.out.println("Parent Method m1 with parameter: " + a);
}
}

// Child Class
class Child extends Parent
{
// Method Overriding
public void m1(int a)
{
System.out.println("Child Method m1 with parameter: " + a);
}
}
// Main Method
class Poly
{
public static void main(String args[])
{
Parent p = new Parent();
p.m1();
p.m1(5);
Child c = new Child();
c.m1(4);
}
}

B.Tech (CSE-DS)-II-II Sem Page 10


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Applications of OOPs

Java is one of the most prominent programming languages that fully embrace the
OOP paradigm. The application of OOP in Java is extensive, spanning various types of
software, including desktop applications, web applications, enterprise software, mobile
apps, and games. Java's rich set of libraries, frameworks, and tools are built on OOP
principles, making it an ideal choice for developing scalable and maintainable
applications.

Application Area Description Examples


JavaFX, Swing
GUI Applications Creating graphical user interfaces. applications (e.g., desktop
apps)
Servlets, JSP, Spring
Building dynamic and interactive
Web Applications Framework-based
web applications.
applications
Structuring business logic and Banking systems, CRM
Enterprise Applications
data processing. systems
Developing applications for
Mobile Applications Android applications
mobile devices.
Developing applications for Java ME (Micro Edition)
Embedded Systems
embedded devices. applications
Developing systems that run on Java RMI, microservices
Distributed Systems
multiple networked computers. architectures
Simulation systems, games
Modeling real-world entities as
Real-World Modeling (e.g., flight simulators,
objects.
RPG games)

B.Tech (CSE-DS)-II-II Sem Page 11


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Java Constructors
Java constructors are special types of methods that are used to initialize
an object when it is created. It has the same name as its class and is syntactically
similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the


instance variables defined by the class or to perform any other start-up procedures
required to create a fully formed object.

All classes have constructors, whether you define one or not because Java
automatically provides a default constructor that initializes all member variables to
zero. However, once you define your constructor, the default constructor is no longer
used.
Rules for Creating Java Constructors
You must follow the below-given rules while creating Java constructors:
 The name of the constructors must be the same as the class name.
 Java constructors do not have a return type. Even do not use void as a return
type.
 There can be multiple constructors in the same class, this concept is known as
constructor overloading.
 The access modifiers can be used with the constructors, use if you want to
change the visibility/accessibility of constructors.
 Java provides a default constructor that is invoked during the time of object
creation. If you create any type of constructor, the default constructor (provided
by Java) is not invoked.
Creating a Java Constructor
To create a constructor in Java, simply write the constructor's name (that is the
same as the class name) followed by the brackets and then write the constructor's body
inside the curly braces ({}).
Syntax
class ClassName
{
ClassName()
{
Statements;
}
}

B.Tech (CSE-DS)-II-II Sem Page 12


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Types of Java Constructors

There are three different types of constructors in Java, we have listed them as follows:

1. Default Constructor
2. No-Args Constructor
3. Parameterized Constructor

1. Default Constructor

If you do not create any constructor in the class, Java provides a default
constructor that initializes the object.

public class cons


{
int num1;
int num2;

public static void main(String[] args)


{
// a default constructor will invoke here
cons obj = new cons();
// Printing the values
System.out.println("num1 : " + obj.num1);
System.out.println("num2 : " + obj.num2);
}
}

B.Tech (CSE-DS)-II-II Sem Page 13


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

2. No-Args (No Arguments) Constructor

As the name specifies, the No-argument constructor does not accept any
arguments. By using the No-Args constructor you can initialize the class data members
and perform various activities that you want on object creation.

public class cons


{
int num1;
int num2;
cons()
{
num1 = -1;
num2 = -1;
}
public static void main(String[] args)
{
// a default constructor will invoke here
cons obj = new cons();

// Printing the values


System.out.println("num1 : " + obj.num1);
System.out.println("num2 : " + obj.num2);
}
}

B.Tech (CSE-DS)-II-II Sem Page 14


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

3. Parameterized Constructor

A constructor with one or more arguments is called a parameterized constructor.

Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a method,
just declare them inside the parentheses after the constructor's name.

public class cons


{
int num1;
int num2;
// Creating parameterized constructor
cons(int a, int b)
{
num1 = a;
num2 = b;
}
public static void main(String[] args)
{
// Creating an object by passing the values
// to initialize the attributes.
// parameterized constructor will invoke
cons obj = new cons(10, 20);
// Printing the objects values
System.out.println("Display Values");
System.out.println("num1 : " + obj.num1);
System.out.println("num2 : " + obj.num2);
}
}

B.Tech (CSE-DS)-II-II Sem Page 15


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Constructor Overloading in Java

Constructor overloading means multiple constructors are defined with the same
signature with different parameter list in a class. When you have multiple constructors
with different parameters listed, then it will be known as constructor overloading.

// Example of Java Constructor Overloading


// Creating a Student Class
class Student
{
String name;
int age;
// no-args constructor
Student()
{
this.name = "Unknown";
this.age = 0;
}
// parameterized constructor having one parameter
Student(String name)
{
this.name = name;
this.age = 0;
}

// parameterized constructor having both parameters


Student(String name, int age)
{
this.name = name;
this.age = age;
}
public void printDetails()
{
System.out.println("Name : " + this.name);
System.out.println("Age : " + this.age);
}
}

B.Tech (CSE-DS)-II-II Sem Page 16


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

public class Overload


{
public static void main(String[] args)
{
Student st1 = new Student(); // invokes no-args constructor
Student st2 = new Student("Rahul"); // invokes parameterized constructor
Student st3 = new Student("Rohit", 25); // invokes parameterized constructor

// Printing details
System.out.println("------------");
System.out.println("std1 Details");
st1.printDetails();
System.out.println("------------");
System.out.println("std2 Details");
st2.printDetails();
System.out.println("------------");
System.out.println("std3 Details");
st3.printDetails();
}
}

B.Tech (CSE-DS)-II-II Sem Page 17


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Java Methods
Java Methods are blocks of code that perform a specific task. A method
allows us to reuse code, improving both efficiency and organization. All methods in
Java must belong to a class. Methods are similar to functions and expose the
behavior of objects.

Creating a Java Method

Syntax

AccessModifier returnType nameOfMethod (Parameter List)


{
// method body
}

The syntax shown above includes −

 AccessModifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.
 nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
 method body − The method body defines what the method does with the
statements.

Example to Create a Java Method

/** the snippet returns the minimum between two numbers */


public static int minFunction(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}

B.Tech (CSE-DS)-II-II Sem Page 18


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Calling a Java Method

For using a method, it should be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).

Example: Defining and Calling a Java Method

public class ExampleMinNumber


{
public static void main(String[] args)
{
int a = 11;
int b = 6;
ExampleMinNumber obj=new ExampleMinNumber();
int c=obj.min(a,b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public int min(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

Output

B.Tech (CSE-DS)-II-II Sem Page 19


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Java Methods Overloading


When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from overriding. In
overriding, a method has the same method name, type, number of parameters, etc.

public class Overloading


{
public static void main(String[] args)
{
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = min(a, b);
// same function name with different parameters
double result2 = min(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int min(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double min(double n1, double n2)
{
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

B.Tech (CSE-DS)-II-II Sem Page 20


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Parameter Passing Techniques


Parameter passing in Java refers to the mechanism of transferring data between
methods. Java supports two types of parameters passing techniques
1. Pass-by-value (or) Call-by-value
2. Pass-by-reference (or) Call-by-reference.
1. Pass-by-value (or) Call-by-value
In pass-by-value technique, the actual parameters in the method call
are copied to the dummy parameters in the method definition. So, whatever changes
are performed on the dummy parameters, they are not reflected on the actual
parameters as the changes you make are done to the copies and to the originals.
class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
System.out.println("After swapping value of x is "+x+" value of y is "+y);
}
}

B.Tech (CSE-DS)-II-II Sem Page 21


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

class Swap
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj.a, obj.b);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}

Although values of x and y are interchanged, those changes are not reflected
on a and b. Memory representation of variables is shown in below figure:

B.Tech (CSE-DS)-II-II Sem Page 22


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

2. Pass-by-reference (or) Call-by-reference


In pass-by-reference technique, reference (address) of the actual parameters are
passed to the dummy parameters in the method definition. So, whatever changes are
performed on the dummy parameters, they are reflected on the actual parameters too as
both references point to same memory locations containing the original values.

class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class Swap
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}

B.Tech (CSE-DS)-II-II Sem Page 23


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

The changes performed inside the method swap are reflected on a and b as we
have passed the reference obj into ref which also points to the same memory locations
as obj. Memory representation of variables is shown in below figure:

Note: In Java, parameters of primitive types are passed by value which is same as pass-
by-value and parameters of reference types are also passed by value (the reference is
copied) which is same as pass-by-reference. So, in Java all parameters are passed by
value only.

Access Control in Java


Access control in Java is a fundamental concept that determines what parts of a
program can be accessed and manipulated by which parts of the program. Java
provides access control mechanisms to help developers create secure and maintainable
software.

Access Control in Java refers to the mechanism used to restrict or allow access
to certain parts of a Java program, such as classes, methods, and variables. Java’s
access control mechanism promotes code encapsulation, and information hiding, and
reduces the likelihood of errors and security vulnerabilities in the program. It is
implemented by using access control modifiers, which are keywords placed before the
declaration of the class member.

B.Tech (CSE-DS)-II-II Sem Page 24


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

There are four access control modifiers in Java

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.

2. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.

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

outside
Access within outside
within class package by
Modifier package package
subclass only

Public Y Y Y Y

Private Y N N N

Protected Y Y Y N

Default Y Y N N

this Keyword
In Java, ‘this’ is a reference variable that refers to the current class object. It can
be used to call current class methods and fields, to pass an instance of the current class
as a parameter, and to differentiate between the local and instance variables. Using
“this” reference can improve code readability and reduce naming conflicts.

B.Tech (CSE-DS)-II-II Sem Page 25


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Usage of ‘this’ keyword

1. Using the ‘this’ keyword to refer to current class instance variables.

2. Using this() to invoke the current class constructor

3. Using ‘this’ keyword to return the current class instance

4. Using ‘this’ keyword as the method parameter

5. Using ‘this’ keyword to invoke the current class method

6. Using ‘this’ keyword as an argument in the constructor call

1. Using ‘this’ keyword to refer to current class instance variables

// using 'this' keyword to refer current class instance variables


class Test
{
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}

void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}

public static void main(String[] args)


{
Test object = new Test(10, 20);
object.display();
}
}

B.Tech (CSE-DS)-II-II Sem Page 26


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

2. Using this() to invoke current class constructor


// Java code for using this() to
// invoke current class constructor
class Test
{
int a;
int b;
// Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}
public static void main(String[] args)
{
Test object = new Test();
}
}

B.Tech (CSE-DS)-II-II Sem Page 27


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

3. Using ‘this’ keyword to return the current class instance


// Java code for using 'this' keyword
// to return the current class instance
class Test
{
int a;
int b;
// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that returns current class instance
Test get()
{
return this;
}
// Displaying value of variables a and b
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test();
object.get().display();
}
}

B.Tech (CSE-DS)-II-II Sem Page 28


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

4. Using ‘this’ keyword as a method parameter


// Java code for using 'this'
// keyword as method parameter
class Test
{
int a;
int b;

// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that receives 'this' keyword as parameter
void display(Test obj)
{
System.out.println("a = " + obj.a+ " b = " + obj.b);
}

// Method that returns current class instance


void get()
{
display(this);
}
// main function
public static void main(String[] args)
{
Test object = new Test();
object.get();
}
}

B.Tech (CSE-DS)-II-II Sem Page 29


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

5. Using ‘this’ keyword to invoke the current class method


// Java code for using this to invoke current class method
class Test
{
void display()
{
// calling function show()
this.show();
System.out.println("Inside display method");
}
void show()
{
System.out.println("Inside show method");
}
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}

B.Tech (CSE-DS)-II-II Sem Page 30


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

6. Using ‘this’ keyword as an argument in the constructor call


// Java code for using this as an argument in constructor call
// Class with object of Class B as its data member
class A
{
B obj;
// Parameterized constructor with object of B as a parameter
A(B obj)
{
this.obj = obj;
// calling display method of class B
obj.display();
}
}
class B
{
int x = 5;
// Default Constructor that create an object of A
// with passing this as an argument in the constructor
B()
{
A obj = new A(this);
}
// method to show value of x
void display()
{
System.out.println("Value of x in Class B : " + x);
}
public static void main(String[] args)
{
B obj = new B();
}
}

B.Tech (CSE-DS)-II-II Sem Page 31


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

static Keyword

The static keyword in Java is used for memory management. The static
keyword belongs to the class rather than an instance of the class.

The static can be used as:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

Characteristics of Static Keyword

1. Belongs to the class: When a member is declared as static, it is associated with the
class rather than with instances of the class.
2. Accessed without creating an instance: Since static members are associated with the
class itself, they can be accessed using the class name, without needing to create an
instance of the class. For example, ClassName.staticMethod().
3. Shared among all instances: Since there is only one copy of a static member per
class, it is shared among all instances of the class. This can be useful for maintaining
common data or behavior across all instances.
4. Can access other static members directly: static members can directly access
other static members of the same class, but they cannot directly access non-static
(instance) members. This is because static members exist independently of any
particular instance.
5. Initialization: static variables are initialized only once, at the start of the execution,
before the initialization of any instance variables. They are initialized in the order
they are declared.
6. Used for utility methods and constants: static methods are commonly used for
utility methods that perform a task related to the class, but do not require any
instance-specific data. static variables are often used for constants that are shared
among all instances of the class.

B.Tech (CSE-DS)-II-II Sem Page 32


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

 Static variables
When a variable is declared as static, then a single copy of the variable is created
and shared among all objects at the class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables:
 We can create static variables at the class level only.
 static block and static variables are executed in the order they are present in a
program.
 Static methods
When a method is declared with the static keyword, it is known as the static
method. The most common example of a static method is the main( ) method. As
discussed above, any static member can be accessed before any objects of its class are
created, and without reference to any object. Methods declared as static have several
restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
 Static blocks
If you need to do the computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
public class StaticEx
{
public static int count = 0;
public int id;
// static block
static
{
System.out.println("Inside static block");
}
public StaticEx()
{
count++;
id = count;
}

B.Tech (CSE-DS)-II-II Sem Page 33


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

public static void printCount()


{
System.out.println("Number of instances: " + count);
}

public void printId()


{
System.out.println("Instance ID: " + id);
}

public static void main(String[] args)


{
StaticEx s1 = new StaticEx();
StaticEx s2 = new StaticEx();
s1.printId();
s2.printId();
StaticEx.printCount();
}
}

 Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-
level class with a static modifier but can declare nested classes as static. Such types of
classes are called Nested static classes. Nested static class doesn’t need a reference of
Outer class. In this case, a static class cannot access non-static members of the Outer
class.

B.Tech (CSE-DS)-II-II Sem Page 34


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

// A java program to demonstrate use of static keyword with Classes


import java.io.*;
public class StClass
{
private static String str = "Welcome to VJIT";

// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
StClass.MyNestedClass obj = new StClass.MyNestedClass();
obj.disp();
}
}

B.Tech (CSE-DS)-II-II Sem Page 35


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

nested and inner classes

Nested Classes in Java


In Java, it is possible to define a class within another class, such classes are
known as nested classes.

 The scope of a nested class is bounded by the scope of its enclosing class.

 A nested class has access to the members, including private members, of the
class in which it is nested. But the enclosing class does not have access to the
member of the nested class.

 A nested class is also a member of its enclosing class.

 As a member of its enclosing class, a nested class can be


declared private, public, protected, or package-private (default).

 Nested classes are divided into two categories:

1. static nested class: Nested classes that are declared static are called static
nested classes.

2. inner class: An inner class is a non-static nested class.

Syntax:

class OuterClass

...

class NestedClass

...

B.Tech (CSE-DS)-II-II Sem Page 36


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

// A java program to demonstrate use of static keyword with Classes


import java.io.*;
public class StClass
{
private static String str = "Welcome to VJIT";

// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
StClass.MyNestedClass obj = new StClass.MyNestedClass();
obj.disp();
}
}

B.Tech (CSE-DS)-II-II Sem Page 37


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Inner classes
To instantiate an inner class, you must first instantiate the outer class. Syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

// accessing inner class & outer class

class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access a private member of the outer class
System.out.println("outer_private = "+ outer_private);
}
}
}
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}

B.Tech (CSE-DS)-II-II Sem Page 38


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Recursion in Java
Recursion in Java is a process in which a method calls itself continuously. A
method that calls itself is called a recursive method. A few Java recursion examples
are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph, etc.

Program to find Factorial of a Number


import java.util.Scanner;
public class Factorial
{
public static int fact(int n)
{
if (n != 0) // ending condition
return n * fact(n - 1); // recursive call
else
return 1;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// Prompt user for the number to find factorial
System.out.print("Enter the number to find factorial: ");
int num = sc.nextInt();
int fact=fact(num);
System.out.println("Factorial of the number "+num+" is "+fact);
}
}

B.Tech (CSE-DS)-II-II Sem Page 39


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Garbage Collection in Java


Garbage Collection in Java is an automatic memory management process that
helps Java programs run efficiently. Java programs compile to bytecode that can be
run on a Java Virtual Machine (JVM). When Java programs run on the
JVM, objects in the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.

The garbage collector automatically finds and removes objects that are no
longer needed, freeing up memory in the heap. It runs in the background as a daemon
thread, helping to manage memory efficiently without requiring the programmer’s
constant attention.

Ways to Request JVM to Run Garbage Collection

 Once an object is eligible for garbage collection, it may not be destroyed


immediately. The garbage collector runs at the JVM’s discretion, and you cannot
predict when it will occur.
 We can also request JVM to run Garbage Collector. There are two ways to do it
o Using System.gc(): This static method requests the JVM to perform
garbage collection.
o Using Runtime.getRuntime().gc(): This method also requests garbage
collection through the Runtime class.

B.Tech (CSE-DS)-II-II Sem Page 40


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Strings
A String in Java is a sequence of characters that can be used to store and
manipulate text data and it is basically an array of characters that are stored in a
sequence of memory locations.

All the strings in Java are immutable in nature, i.e. once the string is created we
can’t change it.

1. String s="VJIT";
2. char[] ch={'H','y','d','e','r','a','b','a','d'};
String s=new String(ch);

In Java, string is an object that represents a sequence of characters. The


java.lang.String class is used to create a string object.

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.

String s="welcome";

2) By new keyword

String s=new String("Welcome");

B.Tech (CSE-DS)-II-II Sem Page 41


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Java String class methods

The java.lang.String class provides many useful methods to perform operations on


sequence of char values.

S.No. Method Description


1. int length() It returns string length
It returns char value for the
2. char charAt(int index)
particular index
It returns substring for given begin
3. String substring(int beginIndex)
index.
String substring(int beginIndex, int It returns substring for given begin
4.
endIndex) index and end index.
It checks the equality of string with
5. boolean equals(Object another)
the given object.
6. boolean isEmpty() It checks if string is empty.
7. String concat(String str) It concatenates the specified string.
It replaces all occurrences of the
8. String replace(char old, char new)
specified char value.
9. String toLowerCase() It returns a string in lowercase.
10. String toUpperCase() It returns a string in uppercase.
It removes beginning and ending
11. String trim()
spaces of this string.

B.Tech (CSE-DS)-II-II Sem Page 42


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

class Strings
{
public static void main(String[] args)
{

// create a string
String s = "Hello! World";
System.out.println("String: " + s);

// get the length of string


int len = s.length();
System.out.println("Length: " + len);

//display char at position


String myStr = "VJIT";
char result = myStr.charAt(2);
System.out.println(result);

// create first string


String first = "Java ";
System.out.println("First String: " + first);
// create second string
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joined = first.concat(second);
System.out.println("Joined String: " + joined);

//substring
String st = "Hello, World!";
System.out.println(st.substring(7, 12));

// create 3 strings
String s1 = "java programming";
String s2 = "java programming";
String s3 = "python programming";

B.Tech (CSE-DS)-II-II Sem Page 43


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

// compare first and second strings


boolean result1 = s1.equals(s2);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = s1.equals(s3);
System.out.println("Strings first and third are not equal: " + result2);

//Replace
String st1 = "Hello";
System.out.println(st1.replace('l', 'p'));
String txt = "Hello World";

//convert upper or lower case


System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());

//trim
String str = " Java World! ";
System.out.println(str);
System.out.println(str.trim());
}
}

B.Tech (CSE-DS)-II-II Sem Page 44


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

Object class
Object class is the base class for all classes in Java. The Object class resides
within the java.lang package. It serves as a foundation for all classes, directly or
indirectly. If a class doesn't extend any other class, it's a direct child of Object; if it
extends another class, it's indirectly derived. Consequently, all Java classes inherit the
methods of the Object class.

Object Class Methods

B.Tech (CSE-DS)-II-II Sem Page 45


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

S.No. Method Name Description

1. This method returns a string


String toString()
representation of the object.

2. This method returns a hash code value for


int hashCode()
the object.

3. This method indicates whether some


boolean equals(Object obj)
other object is "equal to" this one.

4. This method returns the runtime class of


Class<?> getClass()
this Object.

This method creates and returns a copy of


5. protected Object clone()
this object.

This method is called by the garbage


collector on an object when garbage
6. protected void finalize()
collection determines that there are no
more references to the object.

This method causes the current thread to


wait until another thread invokes the
7. void wait()
notify() method or the notifyAll() method
for this object.

This method wakes up a single thread


8. void notify()
that is waiting on this object's monitor.

This method wakes up all threads that are


9. void notifyAll()
waiting on this object's monitor.

B.Tech (CSE-DS)-II-II Sem Page 46


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

import java.util.*;

public class ObjEx implements Cloneable


{
int stno;

ObjEx(int stno)
{
this.stno=stno;
}

public static void main(String args[])


{
ObjEx obj = new ObjEx(6766);

// Below two statements are equivalent


System.out.println("To String:"+obj.toString());
System.out.println("Object:"+obj);
//hashcode
System.out.println("Hash Code:"+obj.hashCode());
//getclass
Object s = new String("Hi");
Class c = s.getClass();
//for the String
System.out.println("Class of Object s is : " + c.getName());
//clone
try
{
ObjEx obj2 = (ObjEx)obj.clone();
System.out.print("Student No:"+obj2.stno);
}
catch (Exception e)
{
System.out.println(e);
}
}
}

B.Tech (CSE-DS)-II-II Sem Page 47


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I

B.Tech (CSE-DS)-II-II Sem Page 48

You might also like