Professional Documents
Culture Documents
Introduction
The invention of the computer, many programming techniques have been tried such as modular
programming, top-down programming, bottom-up programming and structured programming. The
objectives of these techniques to handle the increasing complexity of programs are reliable and
maintainable. Structured programming, like C became very popular and was the paradigm of the 1980s.
The structured approach failed to show the desired results in terms of bug-free, easy-to-maintain and
reusable programs. Object-Oriented programming is an approach to program organization and
development, which attempts to eliminate some of the pitfalls of conventional programming methods
by incorporating the best of structured programming features with several new concepts. C++ is a
procedural language with object-oriented extension, but Java, a pure object oriented language.
The objective of object-oriented approach is to eliminate some of the flaw encountered in the
procedural approach. OOP allows us to decompose a problem into a number of entities called objects
and then build data and functions around these entities. The organization of data and methods in object
as shown in the fig. 1.3.2.a.
Method Method
Dat
Method Method
The data of an object can be accessed by methods associated with object andmethod of one object can be
access the methods of other object.
Features of object-oriented paradigm are:
Emphasis is on data rather than procedure.
Programs are divided into objects.
Data structures are designed.
Methods that operate on the data of an object are tied together in the data structure.
Data hidden and cannot be accessed by external functions.
Objects may communicate with each other through methods.
New data and methods can be added easily.
Employs bottom-up approach in program design.
Object-oriented programming is an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and function that can be used as
templates for creating copies of such modules on demand.
1
Basic Concepts of OOPS
The basic concepts of OOPS, which form the heart of Java language as follow as:
1. Objects
Objects are basic runtime entities in an object-oriented system. They may represent person, a
place, a table of data or any data item that the program must handle.
They may also represent user-defined data types such as vectors and lists. Objects take up space in the
memory and have an associated address like a structure in C.
When a program is executed, the object interacts by sending messages to one another. For
example ‘customer’ and ’account’ are two objects in a banking system, then the customer object send a
message to the account object requesting for balance. Each object has data and code to manipulate the
data. Fig. 1.3.3.a shows a notation to represent an object.
OBJECT: Student
DATA: Name
Reg.No.
Marks
METHODS: Total
Average
Fig.1.3.3.a Representation of an object
2.Classes
The entire set of data and code of an object can be made a user defined data type with the help of a
class. In fact, objects are variables of type class. Once a class has been defined, we can create any number of
objects based on that class. A class has collection of objects of similar type. For example circle, square,
rectangle and ellipse are members of the class shape.
4.Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another class.
For example, the B.C.A., (Computer Applications) is a part of the class Department Computer science,
which is again a part of the class College. Inheritance properties are as shown in Fig.1.3.3.b. In OOP, the
concept of inheritance provides the idea of reusability. We can add additional features to an existing
classwithout modifying it.
2
College
Attributes:
Computer
Science Dept.
Computer
Attributes: Applications Dept.
------------
Attributes:
------------
B.Sc(CS) M.Sc(CS)
Attributes: Attributes:
------------ ------------ B.C.A M.C.A
Attributes: Attributes:
Polymorphism is the ability to take more than one form. An operation may
exhibit different behavior in different instances. The behavior depends upon the data
types of data used in the operation. For example, consider the operation of addition with
two numbers will generate summation and with two String would produce a third string by
concatenation. Fig. 1.3.3.c that shows
the single method name can be used to handle different number and different types ofarguments.
Addition
Add()
Summation Concatenation
Add(Integer) Add(String)
Fig.1.3.3.c Polymorphism
6.Dynamic Binding
Binding refers to linking of a procedure call to the code executed in response tothe call.
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at runtime.
7.Message communication
An Object-oriented program consists of set objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic
3
steps:
Creating classes that define objects and behavior.
Creating objects from class definitions.
Establishing communication among object.
Objects communicate with one another by sending and receiving information as shown inFig.1.3.3.d.
Object
Object Object
Object Object
Student.averageMarks (Reg.No)
Benefits Of OOP
OOP offers several benefits to both the program designer and the user.
Through inheritance, we can eliminate redundant code and extend the use exiting classes.
We can build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This leads to saving of development time
and higher productivity.
It is possible to have multiple objects to coexist without any interference.
It is possible to map objects in the problem domain to those objects in the program
It is easy to partition the work in a project based on objects.
The data-centered design approach enables us to capture more details of a model in an
implementable form
Object-oriented systems can be easily upgraded from small to large systems.
Message passing techniques for communication between objects make the interfacedescription
with external systems much simpler.
Software complexity can be easily managed.
4
Applications Of OOP
The promising areas for application of OOP include:
Real-time systems
Simulation and modeling
Object-oriented databases
Hypertext, hypermedia and expert text
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAD/CAM System
5
CONSTRUCTOR
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if your
class doesn't have any.
<class_name>(){}
6
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
7
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
8
Finalizer
finalize() method in Java is a method of the Object class that is used to perform cleanup activity
before destroying any object. It is called by Garbage collector before destroying the objects from memory.
finalize() method is called by default for every object before its deletion. This method helps Garbage
Collector to close all the resources used by the object and helps JVM in-memory optimization.
finalize() method in Java is used to release all the resources used by the object before it is
deleted/destroyed by the Garbage collector. finalize is not a reserved keyword, it's a method. Once the clean-
up activity is done by the finalize() method, garbage collector immediately destroys the Java object. Java
Virtual Machine(JVM) permits invoking of finalize() method only once per object. Once object is finalized
JVM sets a flag in the object header to say that it has been finalized, and won't finalize it again. If user tries
to use finalize() method for the same object twice, JVM ignores it.
Using the access modifiers we can set the scope or accessibility of these classes, methods,
constructors, and other members.
JAVA has two types of modifiers: access modifiers and non-access modifiers.
What are Access Modifiers?
Access modifiers are keywords that can be used to control the visibility of fields, methods, and constructors
in a class. The four access modifiers in Java are public, protected, default, and private.
Private: We can access the private modifier only within the same class and not from outside the
class.
Default: We can access the default modifier only within the same package and not from outside the
package. And also, if we do not specify any access modifier it will automatically consider it as
default.
Protected: We can access the protected modifier within the same package and also from outside the
package with the help of the child class. If we do not make the child class, we cannot access it from
outside the package. So inheritance is a must for accessing it from outside the package.
Public: We can access the public modifier from anywhere. We can access public modifiers from
within the class as well as from outside the class and also within the package and outside the
package.
9
Let us see which all members of Java can be assigned with the access modifiers:
Now let us understand the scope of these access modifiers with the help of a table:
When the methods or data members are prefixed with a private access modifier, the visibility of these
methods and data members are restricted so, they can be accessed only within the same class where
they have been declared, they will not be visible to the outside world.
If we have another class from the same package still, we will not be able to access these methods or data
members. So usually, we keep the class variables and methods as private, which are intended to be used
inside the same class where declared.
10
Public Access Modifier
It is a keyword. If a class member like variable, method, or data members are prefixed with a public
access modifier, then they can be accessed from anywhere inside the program. That is, they can be
accessed within the same class as well as from outside the different classes.
It also includes access within the same package and also from outside the package. The members like
variables, methods, and other data members can be accessed globally.
Using public access modifiers we can provide access to the members most simply. There are no
restrictions on public access modifier members. Hence, it has the widest accessibility or visibility
scope as compared to the rest of the access modifiers.
Access within within outsidepackagebysubclass outside
Modifier class package only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
11
OBJECTS AND CLASSES IN JAVA
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity
only.
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
o
What is a class in Java?
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:
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
12
EX: class Rectangle
{
int length;
int width;
voidgetData(intx,inty)
{
length=x;
width=y;
}
}
Creating an Object in Java
This is the most popular way to create an object in Java. A new operator is also followed by a call to
constructor which initializes the new object. While we create an object it occupies space in the heap.
Syntax
class_name object_name = new class_name()
Example: Rectanglerect1;//declare
rect1=newRectangle();//instantiate
Method Declaration
A class with only data fields has no life. Methods are declared inside the body of the
class but immediately after the declaration of instance variables.
The general form of a method declaration is
Type methodname(parameter-list)
{
method-body;
}
13
INBUILT CLASSES LIKE STRING
The string represents a sequence of characters in Java by using a character array. The
java.lang.String class is used to create a string object.
Example:
char chararray[ ] =newchar[3];
chararray[ ]= ‘H’;
chararray[ ]=‘a’;
chararray []=‘i’;
In Java strings are class objects and implanted using two classes, namely
String and StringBuffer. A Java string is an instantiated object of the String class.
The String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable
strings. Because String objects are immutable they can be shared. For example:
The class String includes methods for examining individual characters of the sequence, for
comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all
characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version
specified by the Character class.
The Java language provides special support for the string concatenation operator ( + ), and for
conversion of other objects to strings. String concatenation is implemented through
the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through
the method toString, defined by Object and inherited by all classes in Java. For additional information on
string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.
14
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause
a NullPointerException to be thrown.
A String represents a string in the UTF-16 format in which supplementary characters are represented
by surrogate pairs (see the section Unicode Character Representations in the Character class for more
information). Index values refer to char code units, so a supplementary character uses two positions in
a String.
The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to
those for dealing with Unicode code units (i.e., char values).
15
STRINGBUFFER CLASS
StringBuffer is a peer class of String that provides much of the functionality of strings. The string
represents fixed-length, immutable character sequences while StringBuffer represents growable and
writable character sequences. StringBuffer may have characters and substrings inserted in the middle or
appended to the end. It will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.
StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.
1) append() method
The append() method concatenates the given argument with this string.
2) insert() method
The insert() method inserts the given string with this string at the given position.
3) replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex-1.
4) delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex-1.
5) reverse() method
The reverse() method of StringBuilder class reverses the current string.
6) capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.
2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer.
StringBuffer s = new StringBuffer(20);
3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation.
StringBuffer s = new StringBuffer("GeeksforGeeks");
16
Methods of StringBuffer class
Methods Action Performed
append() Used to add text at the end of the existing text.
length() The length of a StringBuffer can be found by the length( ) method
capacity() the total allocated capacity can be found by the capacity( ) method
charAt() This method returns the char value in this sequence at the specified index.
delete() Deletes a sequence of characters from the invoking object
deleteCharAt() Deletes the character at the index specified by loc
ensureCapacity() Ensures capacity is at least equals to the given minimum.
insert() Inserts text at the specified index position
length() Returns length of the string
reverse() Reverse the characters within a StringBuffer object
replace() Replace one set of characters with another set inside a StringBuffer object
Note: Besides that, all the methods that are used in the String class can also be used. These auxiliary
17
JAVA FILES
In Java, a File is an abstract data type. A named location used to store related information is known
as a File. There are several File Operations like creating a new File, getting information about File,
writing into a File, reading from a File and deleting a File.
Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.
Stream:
A series of data is referred to as a stream. In Java, Stream is classified into two types, i.e., Byte
Stream and Character Stream.
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte stream is a process in
which an input is provided and executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling process with a character stream is
a process in which an input is provided and executed with the character data.
18
list() String[] The list() method is used to get an array of the
9.
files available in the directory.
mkdir() Boolean The mkdir() method is used for creating a new
10.
directory.
File Operations
Create a File
Create a File operation is performed to create a new file. We use the createNewFile() method of file.
The createNewFile() method returns true when it successfully creates a new file and returns false when the
file already exists.
Write to a File
The next operation which we can perform on a file is "writing into a file". In order to write data into a file,
we will use the FileWriter class and its write() method together. We need to close the stream using
the close() method to retrieve the allocated resources.
Delete a File
The next operation which we can perform on a file is "deleting a file". In order to delete a file, we will use
the delete() method of the file. We don't need to close the stream using the close() method because for
deleting a file, we neither use the FileWriter class nor the Scanner class.
19
THIS KEYWORD IN JAVA
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.
20
6) this keyword can be used to return current class instance
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).
21