Java New Complete Notes NEP With Programs - Processed

Download as pdf or txt
Download as pdf or txt
You are on page 1of 172

Object Oriented Concepts using Java

UNIT – 1
Introduction to JAVA
OBJECT ORIENTED PROGRAMMING (OOP) :-
The major motivating factor in the invention of object oriented is to remove some of the
flaws encountered in the procedural oriented approach. Object oriented programming
treats data as a critical element in the program development and does not allow it to flow
freely around the system. It ties data more closely to the functions that operate on it, and
protects it from accidental modifications from outside functions.
Object oriented programming allows a decomposition of a problem into a number
entity called objects and then builds data and functions around these objects. The data of an
object can be accessed only by the functions associated with that object. However, functions
of one object can access the functions of other objects.

Organization of data and functions in object oriented programming


The object oriented programming can be defined as an “approach that provides a
way of modularising programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on demand ".
Thus, an object is considered to be a partitioned area of computer memory that stores data
and set of operations that can access that data. Since the memory partitions are independent,
the objects can be used in a variety of different programs without modifications.

Some characteristics of Object Oriented Programming are :-


1) Emphasis is on data rather than procedures or algorithms.
2) Programs are divided into what are known as objects.
3) Data structures are designed such that characterise the objects.
4) Functions that operate on the data are tied together in the data structure.
5) Data is hidden and cannot be accessed by external functions.
6) Objects may communicate with each other through functions.
7) New data and functions can be easily added whenever necessary.
8) Follows bottom-up approach in program design.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 3 of 215


Object Oriented Concepts using Java
Advantages/Benefits of Object Oriented Programming over Procedure Oriented
Programming: -
1. Reusability: In OOP’s programs functions and modules that are written by a user can
be reused by other users without any modification.
2. Inheritance: Through this we can eliminate redundant code and extend the use of
existing classes.
3. Data Hiding: The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.
4. Reduced complexity of a problem: The given problem can be viewed as a collection of
different objects. Each object is responsible for a specific task. The problem is solved by
interfacing the objects. This technique reduces the complexity of the program design.
5. Easy to maintain and Upgrade: OOP makes it easy to maintain and modify existing
code as new objects can be created with small differences to existing ones.
6. Message Passing: The technique of message communication between objects makes
the interface with external systems easier.
7. Modifiability: it is easy to make minor changes in the data representation or the
procedures in an OO program. Changes inside a class do not affect any other part of a
program, since the only public interface that the external world has to a class is through
the use of methods;

CONCEPTS OF OOP’S
The prime purpose of Java programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming
languages.
The core of the pure object-oriented programming is to create an object, in code, that
has certain properties and methods. While designing Java modules, we try to see whole
world in the form of objects. For example, a car is an object, which has certain properties
such as color, number of doors, and the like. It also has certain methods such as accelerate,
brake, and so on.
There are a few principle concepts that form the foundation of object-oriented
programming:
1. Object.
2. Classes.
3. Inheritance.
4. Data Abstraction.
5. Data Encapsulation.
6. Polymorphism.
7. Dynamic Binding.
8. Message Passing

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 4 of 215


Object Oriented Concepts using Java

Message
Dynamic Passing
Binding

OBJECT:
Any real world entity which can have some characteristics or which can perform
some work is called as Object. Object is the basic unit of object-oriented programming.
Objects are identified by its unique name. An object represents a particular instance of a
class. There can be more than one instance of a class. Each instance of a class can hold its
own relevant data.

An Object is a collection of data members and associated member functions also


known as methods.
Object is used for run the class or invokes the class. So many objects can create for a single
class. Objects are the basic run-time entities in an object oriented system. They may
represent a person, a place or any item that the program has to handle.
Example: Man, Table, Bank Account, Bird, Car etc..,

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 5 of 215


Object Oriented Concepts using Java
CLASS:
Classes are data types based on which objects are created. Objects with similar
properties and methods are grouped together to form a Class. Thus a Class represents a set
of individual objects. Characteristics of an object are represented in a class as Properties. The
actions that can be performed by objects become functions of the class and are referred to as
Methods.

For example consider we have a Class of Cars under which Santro Xing, Alto and Wagener
represents individual Objects. In this context each Car Object will have its own, Model, Year
of Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class
and the associated actions i.e., object functions like Start, Move, and Stop form the Methods
of Car Class.
No memory is allocated when a class is created. Memory is allocated only when an object is
created, i.e., when an instance of a class is created.

DATA ABSTRACTION:
Data abstraction refers to providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program
without presenting the details.
Data abstraction is a programming (and design) technique that relies on the
separation of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and DVD
players, BUT you do not know its internal details, that is, you do not know how it receives
signals over the air or through a cable, how it translates them, and finally displays them on
the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 6 of 215


Object Oriented Concepts using Java
DATA ENCAPSULATION OR DATA/INFORMATION HIDING OR SECURITY:
Encapsulation is an Object Oriented Programming concept. Encapsulation is a
process of binding or wrapping the data and the codes that operates on the data into a single
entity. This keeps the data safe from outside interface and misuse. One way to think about
encapsulation is as a protective wrapper that prevents code and data from being arbitrarily
accessed by other code defined outside the wrapper. Data encapsulation led to the
important OOP concept of data hiding.

Example:
TV operation
It is encapsulated with cover and we can operate with remote and no need to
open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the
things in TV.

INHERITANCE OR REUSABILITY
The mechanism that allows us to extend the definition of a class without making any
physical changes to the existing class is inheritance.
Inheritance lets you create new classes from existing class. Any new class that you create
from an existing class is called derived class; existing class is called base class.

The inheritance relationship enables a derived class to inherit features from its base
class. Furthermore, the derived class can add new features of its own. Therefore, rather than
create completely new classes from scratch, you can take advantage of inheritance and
reduce software complexity.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 7 of 215


Object Oriented Concepts using Java
TYPES OF INHERITANCE
Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
one base class.

Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
multiple base classes. But java does not support multiple inheritance.

Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit


from one base class.

Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class
for other classes.

Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 8 of 215


Object Oriented Concepts using Java
POLYMORPHISM
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an
object (or reference) to assume (be replaced by) or become many different forms of object.
Example: function overloading, function overriding, virtual functions.

Example1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.

Example2:
Below is a simple example of the above concept of polymorphism:
6 + 10
The above refers to integer addition.
The same + operator can also be used for floating point addition:
7.15 + 3.78

TYPES OF POLYMORPHISM
There are two types of polymorphism one is compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is functions and operators
overloading. Runtime time polymorphism is done using inheritance and virtual functions.
Here are some ways how we implement polymorphism in Object Oriented programming
languages.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 9 of 215


Object Oriented Concepts using Java
Compile time polymorphism -> Function Overloading
Run time polymorphism -> Interface and abstract methods, Virtual member functions.

Compile Time Polymorphism:


The compiler is able to select the appropriate function for a particular call at compile-
time itself. This is known as compile-time polymorphism. The compile-time polymorphism
is implemented with templates.

 Method/Function overloading

METHOD/FUNCTION OVERLOADING
Using a single function name to perform different types of tasks is known as function
overloading. Using the concept of function overloading, design a family of functions with one
function name but with different argument lists. The function would perform different
operations depending on the argument list in the function call. The correct function to be
invoked is determined by checking the number and type of the arguments but not on the
function type.

Run-time:
The appropriate member function could be selected while the programming is
running. This is known as run-time polymorphism. The run-time polymorphism is
implemented with inheritance.
 Method/Function overriding

METHOD/FUNCTION OVERRIDING
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
 In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.

DYNAMIC BINDING
Binding refers connecting the function call to a function definition/implementation.
Or It is a link between the function call and function definition.
Types of Binding
 Static Binding.
 Dynamic Binding.

STATIC BINDING:
By default, matching of function call with the correct function definition happens at
compile time. This is called static binding or early binding or compile-time binding. Static
binding is achieved using function overloading and operator overloading. Even though

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 10 of 215


Object Oriented Concepts using Java
there are two or more functions with same name, compiler uniquely identifies each function
depending on the parameters passed to those functions.

DYNAMIC BINDING:
Java provides facility to specify that the compiler should match function calls with
the correct definition at the run time; this is called dynamic binding or late binding or run-
time binding. Dynamic binding is achieved using virtual functions. Base class pointer points
to derived class object. And a function is declared virtual in base class, then the matching
function is identified at run-time using virtual table entry.

MESSAGE PASSING
Message passing nothing but sending and receiving of information by the objects
same as people exchange information. So this helps in building systems that simulate real
life. Following are the basic steps in message passing.
 Creating classes that define objects and its behaviour.
 Creating objects from class definitions
 Establishing communication among objects

In OOPs, Message Passing involves specifying the name of objects, the name of the function,
and the information to be sent.
For example: student.mark (name). Here student is object, mark is message, and name is
information.

APPLICATIONS OF OOP:
Applications of OOP are beginning to gain importance in many areas. The most
important application is user interface design. Real business systems are more complex and
contain many attributes and methods, but OOP applications can simplify a complex
problem.
1. User interface design such as windows, menu.
2. Real Time Systems
3. Simulation and Modeling
4. Object oriented databases
5. AI and Expert System
6. Neural Networks and parallel programming
7. Decision support and office automation system
8. Computer animation
9. To design Compiler
10. To access relational data base
11. To develop administrative tools and system tools
12. To develop computer games

DIFFERENCE BETWEEN ABSTRACTION AND ENCAPSULATION: -

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 11 of 215


Object Oriented Concepts using Java

ABSTRACTION ENCAPSULATION

1. Abstraction solves the problem in the 1. Encapsulation solves the problem in the
design level. implementation level.

2. Abstraction is used for hiding the 2. Encapsulation means hiding the code
unwanted data and giving relevant data. and data into a single unit to protect the
data from outside world.

3. Abstraction lets you focus on what the 3. Encapsulation means hiding the
object does instead of how it does it internal details or mechanics of how an
object does something.

4. Abstraction- Outer layout, used in 4. Encapsulation- Inner layout, used in


terms of design. terms of implementation.
For Example:- For Example:- Inner Implementation
Outer Look of a Mobile Phone, like it has detail of a Mobile Phone, how keypad
a display screen and keypad buttons to button and Display Screen are connect
dial a number. with each other using circuits.

Introduction to Java
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.

History of Java
The history of Java is very interesting. Java was originally designed for interactive
television, but it was to advanced technology for the digital cable television industry at the
time.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries
like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 12 of 215


Object Oriented Concepts using Java
7) Why had they chose the name Java for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic,
lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It
is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of
coffee nearby his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc. Each
new version adds new features in Java.
Java Version History
Many java versions have been released till now. The current stable release of Java is Java SE
18.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (22 April 2022)

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 13 of 215


Object Oriented Concepts using Java

Features of Java
1. Compiled and Interpreted
2. Platform Independent and Portable
3. Object-Oriented
4. Robust and Secured
5. Distributed
6. Simple, Small and Familiar
7. Multithreaded & Interactive
8. High Performance
9. Dynamic & Extensible
10. Scalability and Performance

Compiled and Interpreted


Java has both Compiled and Interpreter Feature Program of java is First Compiled
and Then it is must to Interpret it .First of all The Program of java is Compiled then after
Compilation it creates Bytes Codes rather than Machine Language.
Then After Bytes Codes are Converted into the Machine Language is Converted into the
Machine Language with the help of the Interpreter So For Executing the java Program First
of all it is necessary to Compile it then it must be Interpreter

Platform Independent & Portable


Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be Write-Once, Run-Anywhere language
(WORA also known as Platform Independent) language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provides
security. Any machine with Java Runtime Environment can run Java Programs.

Here the MyFirstProgram.class generated on any machine(OS) can be run on any other
machine having same or different OS. This is why we call java is a platform independent
language.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 14 of 215


Object Oriented Concepts using Java
As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform-independent bytecode can be
taken to any platform for execution makes java portable.

Object Oriented
We Know that is purely OOP Language that is all the Code of the java Language is Written
into the classes and Objects So For This feature java is Most Popular Language because it
also Supports Code Reusability, Maintainability etc. Java is not pure object oriented
language because it supports primitive data types (byte, int, float etc) which are not objects.

Robust & Secured


 Robust simply means strong.
 Java uses strong memory management.
 There is lack of pointers that avoids security problem.
 There is automatic garbage collection in java.
 There is exception handling and type checking mechanism in java.
Java is secure because it has features like automatic memory management, no explicit
pointer, bytecode verifier etc that enhances the security of java programs. As java does not
have concept of pointer and provides the automatic memory management, it reduces the
chances of memory leak. Bytecode verifier ensures that .class files are not edited explicitly,
any external edit fails the program to run. Also java program runs in a separate java virtual
machine which enhances it's security. These features together makes java one of the most
secured language.

Distributed
Java is also called a distributed language. This means java programs running on one
machine can easily access the resources (files, java objects etc) of other machine on
internet/network. Java provides class libraries for high-level support of networking. We
can also say, same or different applications running on different JVM on different machines
can interact with each other for sharing data over the internet. RMI and EJB are mostly used
for distributed programming.

Simple, Small & Familiar


The Java program is easy to build and implement when compared to languages
like C and C++ because most of the concepts in these languages that people felt were difficult or
confusing have been eliminated in Java. Removed many confusing and/or rarely-used features

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 15 of 215


Object Oriented Concepts using Java
e.g., explicit pointers, operator overloading etc. Also, the concepts in C and C++ that
programmers have enjoyed are included in Java.

Multi-threaded & Interactive


 A thread is like a separate program, executing concurrently.
 We can write Java programs that deal with many tasks at once by defining multiple
threads.
 The main advantage of multi-threading is that it doesn't occupy memory for each
thread.
 It shares a common memory area.
 Threads are important for multi-media, Web applications etc.
 The java runtimes comes with tools that support multiprocess synchronization and
construct smoothly running interactive systems.

High Performance
Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those methods that are called
making applications to execute faster.

Dynamic & Extensible


Java being completely object-oriented gives us the flexibility to add classes, new
methods to existing classes and even create new classes through sub-classes. Java even
supports functions written in other languages such as C, C++ which are referred to as
native methods. This facility enables the programmers to use the efficient functions
available in these languages. Native methods are linked dynamically at runtime.

Scalability and Performance


J2SE 5.0 assures a significant increase in scalability and performance by improving
the startup time and reducing the amount of memory used in java 2 runtime environment.

C vs C++ vs Java
The languages are based on each other but still, they are different in design and
philosophy. The following table describes the major differences between C, C++, and Java.
It will help you to select which language you have to learn.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 16 of 215


Object Oriented Concepts using Java
S.N. Basis C C++ Java
The Java
The C++ language
The C language is programming
1 Origin is based on the C
based on BCPL. language is based on
language.
both C and C++.
It is an object- It is a pure object-
Programming It is a procedural oriented oriented
2
Pattern language. programming programming
language. language.
It also uses the
It uses the top-down It uses the bottom-
3 Approach bottom-up
approach. up approach.
approach.
It is a static It is also a static It is a dynamic
Dynamic or
4 programming programming programming
Static
language. language. language.
Code The code is executed The code is The code is executed
5
Execution directly. executed directly. by the JVM.
It is platform-
Platform It is platform It is platform
6 independent because
Dependency dependent. dependent.
of byte code.
Java uses both
It also uses a
It uses a compiler compiler and
compiler only to
only to translate the interpreter and it is
7 Translator translate the code
code into machine also known as an
into machine
language. interpreted
language.
language.
File It generates the .exe, It generates .exe It generates .class
8
Generation and .bak, files. file. file.
There There There
Number of
9 are 32 keywords in are 60 keywords in are 52 keywords in
Keyword
the C language. the C++ language. the Java language.
Source File The source file has a The source file has The source file has a
10
Extension .c extension. a .cpp extension. .java extension.
Java does not
Pointer It also supports support the pointer
11 It supports pointer.
Concept pointer. concept because of
security.
It also supports
Union and It supports union It does not support
union and
12 Structure and structure data union and structure
structure data
Datatype types. data types.
types.
It uses pre-
It uses pre-processor
processor It does not use
Pre-processor directives such as
13 directives such as directives but uses
Directives #include, #define,
#include, #define, packages.
etc.
#header, etc.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 17 of 215


Object Oriented Concepts using Java
It does not support It supports both
Constructor/ It supports
14 constructor and constructor and
Destructor constructors only.
destructor. destructor.
It supports
Exception It does not support It also supports
15 exception
Handling exception handling. exception handling.
handling.
It uses the calloc(),
It uses new and
malloc(), free(), and It uses a garbage
Memory delete operator to
16 realloc() methods to collector to manage
Management manage the
manage the the memory.
memory.
memory.
Method and
It does not support Only method
operator
17 Overloading the overloading overloading can be
overloading can be
concept. achieved.
achieved.
goto It supports the goto It also supports the It does not support
18
Statement statement. goto statement. the goto statements.
It is used to develop
It is widely used to It is widely used web applications,
19 Used for develop drivers and for system mobile applications,
operating systems. programming. and windows
applications.
An array can
be declared
An array should be
without
declared with size. An array should be
20 Array Size declaring the
For example, int declared with size.
size. For
num[10].
example, int
num[].

Is Java a pure object-oriented programming language?


Object oriented programming (OOP) language uses an object-oriented
programming technique that binds related data and functions into an object and encourages
reuse of these objects within the same and other programs. Many languages are Object
Oriented and there are seven qualities to be satisfied for a programming language to be
pure Object Oriented. They are:
 Encapsulation/Data Hiding
 Inheritance
 Polymorphism
 Abstraction
 All predefined types are objects
 All operations are performed by sending messages to objects
 All user-defined types are objects.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 18 of 215


Object Oriented Concepts using Java
Java is pure object oriented or not?
There are lot of arguments around whether Java is purely object oriented or not. Java is not
a pure OOP language due to two reasons:

 The first reason is that the Object oriented programming language should only have
objects whereas java contains 8 primitive data types like char, boolean, byte, short,
int, long, float, double which are not objects. These primitive data types can be used
without the use of any object. (Eg. int x=10; System.out.print(x.toString());)

 The second reason related to the static keyword. In pure object oriented language,
we should access everything by message passing (through objects). But java contains
static variables and methods which can be accessed directly without using objects.
That means, when we declare a class as 'static' then it can be referenced without the
use of an object.

Java Virtual Machine


As we know that, all programming language compilers convert the source code to
machine code. Same job done by Java Compiler to run a Java program, but the difference is
that Java compiler convert the source code into Intermediate code is called as bytecode. This
machine is called the Java Virtual machine and it exits only inside the computer memory.

Following figure shows the process of compilation.

The Virtual machine code is not machine specific. The machine specific code is generated
by Java interpreter by acting as an intermediary between the virtual machine and real
machines as shown above diagram.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 19 of 215


Object Oriented Concepts using Java
Java Object Framework act as the intermediary between the user programs and the virtual
machine which in turn act as the intermediary between the operating system and the Java
Object Framework.

Fig : Layers of Interaction for Java programs


Java Environment
Java environment includes a number of development tools, classes and methods. The
development tools are part of the system known as Java Development Kit (JDK) and the
classes and methods are part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).
Java Development kit (JDK) – The JDK comes with a set of tools that are used for
developing and running Java program. It includes:
1. Appletviewer ( It is used for viewing the applet)
2. javac (It is a Java Compiler)
3. java (It is a java interpreter)
4. javap (Java disassembler, which convert byte code into program description)
5. javah (It is for java C header files)
6. javadoc (It is for creating HTML document)
7. jdb (It is Java debugger)

For compiling and running the program, we have to use following commands:

a) javac (Java compiler) In java, we can use any text editor for writing program and
then save that program with “.java” extension. Java compiler is a platform independent. Java
compiler convert the source code or program in bytecode and interpreter convert “.java”
file in “.class” file. Syntax: C:\javac filename.java If my filename is “abc.java” then the
syntax will be

C:\javac abc.java

b) java (Java Interpreter) As the Java compiler compiles the source code into the Java
bytecode. In the same way, the Java interpreter converts or translates the bytecode into the
machine-understandable format i.e. machine code, after that the machine code interacts
with the operating system. Java interpreter is a platform dependent.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 20 of 215
Object Oriented Concepts using Java

C:\java ab

Overview of Java
Java is a general purpose, object oriented programming language

Java programs are divided in to two parts


 Stand-alone program
 Web applets

Stand-alone program
 Stand-alone programs are simple programs
 They written in java to carry out certain tasks on a standalone local computer

Web Applications or Applets or Internet Applications


 Web applets small type of Java programs
 They developed for internet applications
 These programs are called Applet programs
 Applet programs can be executed through the use of Internet
 These applet programs contains an different file with an extension of HTML
 An applet can run within a web browser

Two ways of using Java

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is
currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 21 of 215


Object Oriented Concepts using Java
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

Structure of Java Program

Documentation Section
It is used to improve the readability of the program. It consists of comments in Java
that include basic information such as the method’s usage or functionality to make it easier
for the programmer to understand it while reviewing or debugging the code. A Java
comment is not necessarily limited to a confined space, it can appear anywhere in the code.
The compiler ignores these comments during the time of execution and is solely meant for
improving the readability of the Java program.
There are three types of comments that Java supports
 Single line Comment
 Multi-line Comment
 Documentation Comment
Let us look at an example to understand how we can use the above-mentioned comments in
a Java program.
// a single line comment is declared like this
/* a multi-line comment is declared like this
and can have multiple lines as a comment */
/** a documentation comment starts with a delimiter and ends with */

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 22 of 215


Object Oriented Concepts using Java
Package Statement
There is a provision in Java that allows you to declare your classes in a collection called
package. There can be only one package statement in a Java program and it has to be at the
beginning of the code before any class or interface declaration. This statement is optional, for
example, take a look at the statement below.
package student;

This statement declares that all the classes and interfaces defined in this source file are a part
of the student package. Only one package can be declared in the source file.

Import Statement
Many predefined classes are stored in packages in Java, an import statement is used
to refer to the classes stored in other packages. An import statement is always written after
the package statement but it has to be before any class declaration.
We can import a specific class or classes in an import statement. Take a look at the example
to understand how to import statement works in Java.

import java.util.Date; //imports the date class


import java.applet.*; //imports all the classes from the java applet package

Interface Section
This section is used to specify an interface in Java. It is an optional section which is
mainly used to implement multiple inheritances in Java. An interface is a lot similar to a class
in Java but it contains only constants and method declarations.
An interface cannot be instantiated but it can be implemented by classes or extended by other
interfaces.

interface stack
{
void push(int item);
void pop();
}
Class Definition
A Java program may contain several class definitions, classes are an essential part of
any Java program. It defines the information about the user-defined classes in a program.
A class is a collection of variables and methods that operate on the fields. Every program in
Java will have at least one class with the main method.

Main Method Class


The main method is from where the execution actually starts and follows the order
specified for the following statements.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 23 of 215


Object Oriented Concepts using Java
Let’s take a look at a sample program to understand how it is structured.
public class Example
{
//main method declaration
public static void main (String[] args)
{
System.out.println("hello world");
}}

Let’s analyse the above program line by line to understand how it works.

public class Example


This creates a class called Example. You should make sure that the class name starts
with a capital letter, and the public word means it is accessible from any other classes.

Comments
To improve the readability, we can use comments to define a specific note or
functionality of methods, etc for the programmer.

Braces
The curly brackets are used to group all the commands together. To make sure that
the commands belong to a class or a method.

public static void main


 When the main method is declared public, it means that it can be used outside of this
class as well.
 The word static means that we want to access a method without making its objects. As
we call the main method without creating any objects.
 The word void indicates that it does not return any value. The main is declared as void
because it does not return any value.
 Main is the method, which is an essential part of any Java program.

String[] args
It is an array where each element is a string, which is named as args. If you run the
Java code through a console, you can pass the input parameter. The main() takes it as an
input.
System.out.println();
The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the PrintWriter class. The method println prints the text
on the screen with a new line. All Java statements end with a semicolon.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 24 of 215


Object Oriented Concepts using Java
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods, and instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.

Implementing a Java program


Implementing involves three steps

1. Creating the program


2. Compiling the program
3. Running the program

Creating & Running the program


Step1: Java programs can be created by using any text editor or in notepad

Step2: The Java programs are store with the extension of mainclassname.java

Step3: After creating the programs has been compiled

Step4: For compiling programs always use javac filename.java in the command prompt

Step5: Then run the program java filename


For running programs use statement java program name

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 25 of 215


Object Oriented Concepts using Java
JAVA TOKENS:
 A token is the smallest element of a program that is meaningful to the compiler.
 These tokens define the structure of the Java language.
 While submit a Java program to the Java compiler, the compiler scans the text and
extracts individual tokens.
Java tokens can be broken into five categories:
1. Identifiers
2. Keywords
3. Literals
4. Operators
5. Separators

The Java compiler also recognizes and subsequently removes comments and whitespaces.

Example:
public class Hello
{
public static void main(String args[])
{
System.out.println(“Welcome in Java”); //print welcome in java
}
}

In above Example,
 The source code contains tokens such as public, class, Hello, {, public, static, void,
main, (, String, [], args, {, System, out, println(, “welcome in Java”, }, }.
 The resulting tokens· are compiled into Java bytecodes that is capable of being run
from within an interpreted java environment.
 Token are useful for compiler to detect errors.
 When tokens are not arranged in a particular sequence, the compiler generates an
error message.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 26 of 215


Object Oriented Concepts using Java
Identifiers:
 Identifiers are tokens that represent names.
 These names can be assigned to variables, methods, and classes to uniquely identify
them to the compiler.

Identifiers are,
 Sequence of Uppercase letters(A to Z)
 Sequence of Lowercase letters (a to z)
 Numbers (0 to 9)
 Underscore (_)
 Dollar Symbol ($)

Rules of Identifiers or Variables


1. Should be single word. That is spaces are not allowed.
Example: mangoprice is valid but mango price is not valid.
2. Should start with a letter (alphabet) or underscore or $ symbol.
Example: price, _price and $price are valid identifiers.
3. Should not be a keyword of Java as keyword carries special meaning to the compiler.
Example: class or void etc.
4. Should not start with a digit but digit can be in the middle or at the end.
Example: 5mangoescost is not valid and mango5cost and mangocost5 are valid.
5. Length of an identifier in Java can be of 65,535 characters and all are significant.
6. Identifiers are case-sensitive. That is both mango and Mango are treated differently.
7. Can contain all uppercase letters or lowercase letters or a mixture.

Valid and invalid Java identifiers.

Valid Invalid

HelloWorld Hello World (uses a space)

Hi_JAVA Hi JAVA! (uses a space and punctuation mark)

value3 3value(begins with a number)

Tall short (this is a Java keyword)

$age #age (does not begin with any other symbol except _ $ )

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 27 of 215


Object Oriented Concepts using Java
Keywords or Reserved Words or Predefined words
Keywords are pre-defined, reserved words used in Java programming that have
special meanings to the compiler. In Java, we have 53 such reserved words, out of which 48
are in use and 2 are reserved but not in use and 3 are reserved literals.
For example:
int score;
Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed
two's complement integer).

You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are
part of the Java programming language syntax. Here is the complete list of all keywords in
Java programming.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 28 of 215


Object Oriented Concepts using Java
Constants or Literals
Constants in java are fixed values those are not changed during the execution of
program java supports several types of Constants those are :

JAVA
CONSTANTS

Non-Numeric or
NUMERIC
CHARACTER
CONSTANTS CONSTANTS

SINGLE
INTEGER REAL/FLOAT STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS CONSTANTS

Integer constants
 An integer constant refers to a sequence of digits. It includes,
1. Decimal integer
2. Octal integer
3. Hexadecimal integer

1. Decimal Integer
 It consists of a set of digits, 0 through 9, preceded by an optional minus sign.
 Valid examples of integer constants are, 123, -321, 0 ,654321
 Embedded spaces, commas & non-digit characters are not permitted b/w
digits.

For eg: 15 750, 20,00 , $1000


2. Octal integer
 It consists of any combination of digits from the set 0 through 7, with a leading
0.

eg: 037 , 0, 0435, 0551


3. Hexadecimal integer
 A sequence of digits preceded by 0x or 0X is considered as hexadecimal
integers.
 It may also include alphabets A through F or a through f.
 A letter A through F represents the numbers 10 through 15.
E.g. 0X2, 0X9F, 0xbcd 0x

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 29 of 215


Object Oriented Concepts using Java
Real constants
 Quantities are represented by numbers containing fractional part like 17.678.
 Such numbers are called real/floating point constants.

E.g. 0.0083, -0.75, 435.36


 It is possible that the number may not have digits before the decimal point or digit
after the decimal points.

E.g. 215.0, .95 , -.71


 A real numbers may also be expressed in exponential or scientific notation.
(E.g.) the value 215.65 may be written as 2.156e2 in exponential notation. e2 means
multiply by 10power2. The general form is,

Mantissa e exponent

Character constants
Single Character constants
 A single character constant or simply character constant contains a single character
enclosed within a pair of single quote marks.
 The characters may be alphabets, digits, special characters and blank spaces.

Eg: ‘x’ , ‘A’ , ‘5’, ‘;’, ‘ ‘


 The character constant ‘5’ is not the same as the number 5. The last constant is a blank
space.

String constants
 A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.

Eg: “hello java” “2013” “welcome” “#$%....!” “3+2” “x"

EXAMPLE PROGRAM:

class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 30 of 215


Object Oriented Concepts using Java
Declaring constant in Java
In Java, to declare any variable as constant, we use static and final modifiers. It is also
known as non-access modifiers. According to the Java naming convention the identifier
name must be in capital letters.

Static and Final Modifiers


o The purpose to use the static modifier is to manage the memory.
o It also allows the variable to be available without loading any instance of the class in
which it is defined.
o The final modifier represents that the value of the variable cannot be changed. It also
makes the primitive data type immutable or unchangeable.

The syntax to declare a constant is as follows:


54.9M
884
Hello Java Program for Beginners

1. static final datatype identifier_name=value;

For example, price is a variable that we want to make constant.

2. static final double PRICE=432.78;

Where static and final are the non-access modifiers. The double is the data type and PRICE
is the identifier name in which the value 432.78 is assigned.

In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.

Here a question arises that why we use both static and final modifiers to declare a
constant?

If we declare a variable as static, all the objects of the class (in which constant is defined)
will be able to access the variable and can be changed its value. To overcome this problem,
we use the final modifier with a static modifier.

When the variable defined as final, the multiple instances of the same constant value will
be created for every different object, which is not desirable.

When we use static and final modifiers together, the variable remains static and can be
initialized once. Therefore, to declare a variable as constant, we use both static and final
modifiers. It shares a common memory location for all objects of its containing class.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 31 of 215


Object Oriented Concepts using Java
DATA TYPES:
 Every variable in java has a data type.
 Data types specify the size and type of values that can be stored.
 Java language is rich in its data types.
 Primitive types are also called as intrinsic or built-in types.
 Derived data types are also known as reference types.
 Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory.

There are two data types available in Java −


 Primitive Data Types or Intrinsic or Built-in types.
 Reference/Non-Primitive/User Defined Types

Primitive Data Types


 The primitive data types are the predefined data types of Java. They specify the size
and type of any standard values.
 There are eight primitive datatypes supported by Java.
 Primitive datatypes are predefined by the language and named by a keyword.
 Let us now look into the eight primitive data types in detail

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 32 of 215


Object Oriented Concepts using Java
byte
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50

short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 33 of 215


Object Oriented Concepts using Java
Example Program:
class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0

long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L
float
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f
double
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values, generally
the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4
boolean
 boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example: boolean one = true
char
 char data type is a single 16-bit Unicode character

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 34 of 215


Object Oriented Concepts using Java
 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'

Data Size Default Description


Type (Bytes) Value
byte 1 0 Stores whole numbers from -128 to 127
short 2 0 Stores whole numbers from -32,768 to 32,767
int 4 0 Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 0 Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 0.0f Stores fractional numbers. Sufficient for storing 6 to 7 decimal
digits
double 8 0.0f Stores fractional numbers. Sufficient for storing 15 decimal
digits
boolean 1 bit False Stores true or false values
char 2 null Stores a single character/letter or ASCII values

Reference Datatypes or Object data types or User defined data types


 These are also referred to as Non-primitive or Reference Data Type. They are so-
called because they refer to any particular objects. Unlike the primitive data types,
the non-primitive ones are created by the users in Java. Examples include arrays,
strings, classes, interfaces etc. When the reference variables will be stored, the variable
will be stored in the stack and the original object will be stored in the heap.
 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that
cannot be changed. For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any
compatible type.
 Example: Animal animal = new Animal("giraffe");

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 35 of 215


Object Oriented Concepts using Java
VARIABLE
Variable is a value, which changes during the execution of the program. Variable is
name of reserved area allocated in memory. In other words, it is a name of memory location.
It is a combination of "vary + able" that means its value can be changed.

Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in the memory.

E.g. int data=50; //Here data is variable


Types of Variable
There are three types of variables in java:
o Local variable
o Instance variable
o Static variable

Local Variables
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 There is no default value for local variables, so local variables should be declared
and an initial value should be assigned before the first use.
Example
class Functionoverloading
{
public void add(int x, int y)
{
int sum; //local variables
sum=x+y;
System.out.println(sum);
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 36 of 215


Object Oriented Concepts using Java
public void add(double a, double b)
{
double total; //local variables
total=a+b;
System.out.println(total);
}
}

class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10.40,10.30);
}
}
Output:

Instance Variables
 Instance variables are declared in a class, but outside a method, constructor or any
block.
 When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
 Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
 Instance variables can be accessed directly by calling the variable name inside the
class.
import java.io.*;
public class Employee
{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;

// the name variable is assigned in the constructor.


public Employee (String empName)
{

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 37 of 215


Object Oriented Concepts using Java

name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal)
{
salary = empSal;
}
// this method prints the employee details.
public void printEmp()
{
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[])


{
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This will produce the following result −
Output
name : Ransika
salary :1000.0

Class/Static Variables
 Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
 Static variables can be accessed by calling with the class
name ClassName.VariableName.
Example
/* Program with class variable that is available for all instances of a class. Use static
variable declaration. Observe the changes that occur in the object’s member variable
values.*/

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 38 of 215


Object Oriented Concepts using Java

class StaticDemo
{
static int count=0; //static variable declaration
public void increment()
{
count++;
}
public static void main(String args[])
{
StaticDemo obj1=new StaticDemo ();
StaticDemo obj2=new StaticDemo ();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:

Operators
An operator is a special symbol that tells the compiler to perform a specific
mathematical or logical operation on one or more operands where an operand can be an
expression. An operation is an action(s) performed on one or more operands that evaluates
mathematical expressions or change the data.

There are many types of operators in java, which are given below:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 39 of 215


Object Oriented Concepts using Java
Unary Operator
Unary operators are the types that need only one operand to perform any operation
like increment, decrement, negation, etc.

Operator Description Example

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as Java arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

Example:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Output: 21

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 40 of 215


Object Oriented Concepts using Java
Relational Operators are a bunch of binary operators used to check for relations between
two operands, including equality, greater than, less than, etc. They return a boolean result
after the comparison and are extensively used in looping statements as well as conditional
if-else statements and so on.

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

Example
public class Test
{
public static void main(String args[])
{
int a = 10,b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 41 of 215


Object Oriented Concepts using Java
Logical Operators:
These operators are used to perform logical “AND”, “OR” and “NOT” operation,
i.e. the function similar to AND gate and OR gate in digital electronics. They are used to
combine two or more conditions/constraints or to complement the evaluation of the
original condition under particular consideration.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

Bitwise Operators:
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.).

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 42 of 215


Object Oriented Concepts using Java
Assignment Operators:
These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable, and the right side operand of the assignment operator
is a value. The value on the right side must be of the same data type of the operand on the
left side.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

Java Ternary Operator


Java ternary operator is the only conditional operator that takes three operands. It is
a one-liner replacement for the if-then-else statement and is used a lot in Java programming.
We can use the ternary operator in place of if-else conditions or even switch conditions using
nested ternary operators. The ternary operator (conditional operator) is shorthand for the if-
then-else statement.

Syntax:
variable = Expression ? expression1 : expression2

Here's how it works.


If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 43 of 215


Object Oriented Concepts using Java
Let's see an example of a ternary operator.
class Java
{
public static void main(String[] args)
{
int februaryDays = 29;
String result;

// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output
Leap year
In the above example, we have used the ternary operator to check if the year is a leap year
or not.

Other operators
Besides these operators, there are other additional operators in Java.

Java instanceof Operator


The instanceof operator checks whether an object is an instanceof a particular class.
For example,
class Main
{
public static void main(String[] args)
{
String str = "Programiz";
boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Output
Is str an object of String? true
Here, str is an instance of the String class. Hence, the instanceof operator returns true.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 44 of 215


Object Oriented Concepts using Java
Special Operators
The following operators are known as Java special operators.

Operator Description

, Comma Operator allows multiple expressions to be evaluated as single


statement.

instanceof checks if the object is an instance of given type

New creates an instance (object)

Yield Checks what is returned in a generator by the generator's iterator.

Expressions
 Expressions are a combination of variables, constants & operators arranged as per
the syntax of the language.
 Java can handle any complex mathematical expressions.

Algebraic expression Java expression


Ab-c A*b-c
(m+n)(x+y) (m+n)*(x+y)
Ab/c A*b/c
3x2+2x+1 3*x*x+2*x+1

Evaluation of expression:
 Expressions are evaluated using an assignment statement of the form
Variable=expression;
 Variable is any valid java variable name.
 When the statement is encountered, the expression is evaluated first & the result then
replaces the previous value of the variable on the left-hand side.

Ex:
X=a*b-c;
Y=b/c*a;
Z=a-b/c + d;
 The blank spaces around an operator are optional & it is added only to improve
readability.
 The variables a, b, c, d must be defined before they are used in the expression.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 45 of 215


Object Oriented Concepts using Java
Operator Precedence

Example:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2); //expression
}
}
Output:
21

Java Control Statement


Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides statements
that can be used to control the flow of Java code. Such statements are called control flow
statements. It is one of the fundamental features of Java, which provides a smooth flow of
program.

Control Statements can be divided into three categories, namely


 Selection statements or Branching or Decision Making
 Iteration statements or Looing or Iterative
 Jump statements

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 46 of 215


Object Oriented Concepts using Java

Selection statements or Branching or Decision Making


 Selection statement is also called as Decision-making statements because it provides
the decision-making capabilities to the statements.
 In selection statement, there are two types:
1. if statement
2. Switch statement.
Java if statement
The Java if statement is used to test the condition. It checks Boolean
condition: true or false. There are various types of if statement in java.

o if statement
o if-else statement
o Nested if-else statement
o if-else-if ladder

if Statement or One way Branching


The Java if statement tests the condition. It
executes the if block if condition is true.

Syntax:
if(condition)
{
//code to be executed
}
Example:
public class IfExample
{
public static void main(String[] arg)
{

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 47 of 215


Object Oriented Concepts using Java
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
} }
Output:
Age is greater than 18

if-else Statement or Two way branching


The Java if-else statement also tests the condition. It executes the if block if condition
is true otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example:
/* Program to assign two integer values to X and
Y. Using the ‘if’ statement the output of the
program should display a message whether X is
greater than Y.*/
class Largest
{
public static void main(String...args)
{
int x=51;
int y=5;
if(x>y)
{
System.out.println("Largest is x = "+x);
}
else
{
System.out.println("Largest is y = "+y);
}
}}
Output:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 48 of 215


Object Oriented Concepts using Java
Nested if – else statement
The Nested if-else statement executes one if or else if statement inside another if or
else if statement.

Syntax:
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
}

Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 49 of 215


Object Oriented Concepts using Java
if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 50 of 215


Object Oriented Concepts using Java
Example:
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

Output:
C grade

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 51 of 215


Object Oriented Concepts using Java
Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 52 of 215


Object Oriented Concepts using Java
Example:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Output: 20

Iteration Statement:

 The process of repeatedly executing a statements and is called as looping. The


statements may be executed multiple times (from zero to infinite number).
 If a loop executing continuous then it is called as Infinite loop. Looping is also called
as iterations.
 In Iteration statement, there are three types of operation:
1. for loop
2. while loop
3. do-while loop
Simple for Loop
The simple for loop is same as C/C++. We
can initialize variable, check condition and
increment/decrement value.

Syntax:
for(initialization;condition;incr/decr)
{
//code to be executed
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 53 of 215


Object Oriented Concepts using Java
Example:
/* Program to accept a number and find whether the number is Prime or not.*/

import java.util.*;
class Prime
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no");
int n = sc.nextInt();
int i=1,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}

if(c==2)
{
System.out.println(n+" is a PRIME no");
}
else
{
System.out.println(n+" is a NOT a prime no");
}
}
}
Output:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 54 of 215


Object Oriented Concepts using Java
While Loop
The Java while loop is used to iterate a
part of the program several times. If the
number of iteration is not fixed, it is
recommended to use while loop.

Syntax:
while(condition)
{
//code to be executed
}

Example:
/* Program to list the factorial of the
numbers 1 to 10. To calculate the factorial
value, use while loop.*/

public class Factorial


{
public static void main(String[] args)
{
// declare variables
int count=1;
long fact = 1;
// Find factorial from 1 to 10
System.out.printf("%4s%30s\n", "Number", "Factorials");
while(count <=10)
{
fact *= count;
System.out.print("%4d%,30d\n", count, fact);
count++;
}
}
}
Output:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 55 of 215


Object Oriented Concepts using Java
Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true)
{
//code to be executed
}

do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop. The Java do-while loop is executed at least once because
condition is checked after loop body.

Syntax:
do
{
//code to be executed
}while(condition);

Example:
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=8);
}
}
Output:
12345678

Java Infinitive do-while Loop


If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 56 of 215


Object Oriented Concepts using Java
JUMPS IN STATEMENT:

 Statements or loops perform a set of operations continually until the control variable
will not satisfy the condition.
 But if we want to break the loops when condition will satisfy then Java give a
permission to jump from one statement to end of loop or beginning of loop as well
as jump out of a loop.
 “break” keyword use for exiting from loop and “continue” keyword use for
continuing the loop.
 Break statement is used to terminate from a loop while a test condition is true.

1. Break statement
2. Continue statement

Break Statement
The Java break is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.

Syntax:
jump-statement;
break;

Example:
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
System.out.println(i);
}
}
}
Output:
1234

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 57 of 215


Object Oriented Concepts using Java
Continue Statement
The Java continue statement is used to continue loop. It continues the current flow of
the program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

Syntax:

jump-statement;
continue;

Example:
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
Output:
1 2 3 4 6 7 8 9 10

Java Methods
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of code.
We write a method once and use it many times. 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.

Method Declaration :
In general, method declarations has six components:

1. Modifier: It defines the access type of the method i.e. from where it can be accessed in
your application. In Java, there 4 types of access specifiers.
 public: It is accessible in all classes in your application.
 protected: It is accessible within the class in which it is defined and in its subclass/es
 private: It is accessible only within the class in which it is defined.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 58 of 215


Object Oriented Concepts using Java
 default: It is declared/defined without using any modifier. It is accessible within the
same class and package within which its class is defined.

2. The return type: The data type of the value returned by the method or void if does not
return a value.

3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different.

4. Parameter list: Comma-separated list of the input parameters is defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().

5. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).

6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations.

Types of Methods in Java


There are two types of methods in Java:

1. Predefined Method: In Java, predefined methods are the method that is already defined
in the Java class libraries is known as predefined methods. It is also known as the standard
library method or built-in method. We can directly use these methods just by calling
them in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.
2. User-defined Method: The method written by the user or programmer is known as a
user-defined method. These methods are modified according to the requirement.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 59 of 215


Object Oriented Concepts using Java
Types of User-defined methods
 Static Method or Factory Methods
 Instance Method
 Abstract Method

1. Static Method
A method that has static keyword is known as static method. In other words, a
method that belongs to a class rather than an instance of a class is known as a static
method. We can also create a static method by using the keyword static before the method
name.
The main advantage of a static method is that we can call it without creating an
object. It can access static data members and also change the value of it. It is used to create
an instance method. It is invoked by using the class name. The best example of a static
method is the main() method.

2. Instance Method
The method of the class is known as an instance method. It is a non-static method
defined in the class. Before calling or invoking the instance method, it is necessary to create
an object of its class.

3. Abstract Method
The method that does not has method body is known as abstract method. In other
words, without an implementation is known as abstract method. It always declares in
the abstract class. It means the class itself must be abstract if it has abstract method. To
create an abstract method, we use the keyword abstract.

Method Overloading or Compile time Polymorphism


“Method overloading is a feature of Java in which a class has more than one method
of the same name and their parameters are different.”
We can say that Method overloading is a concept of Java in which we can create
multiple methods of the same name in the same class, and all methods work in different
ways. When more than one method of the same name is created in a Class, this type of
method is called the Overloaded Method. Method overloading increases the readability of
the program.

Different ways to overload the method


There are two ways to overload the method in java
1. By changing the data type
2. By changing number of arguments

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 60 of 215


Object Oriented Concepts using Java
1. Method Overloading: Changing data type of arguments
 In this example, two methods are created that differs in data type.
 The first add method receives two integer arguments
 Second, add method receives two double arguments.

/* Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.*/

class Functionoverloading
{
public void add(int x, int y)
{
int sum;
sum=x+y;
System.out.println(sum);
}
public void add(double a, double b)
{
double total;
total=a+b;
System.out.println(total);
}
}

class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10.40,10.30);
}
}
Output:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 61 of 215


Object Oriented Concepts using Java
2. Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition
of two numbers and second add method performs addition of three numbers.

/* Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.*/

class Functionoverloading
{
public void add(int x, int y)
{
int sum;
sum=x+y;
System.out.println(sum);
}
public void add(int a, int b, int c)
{
int total;
total=a+b+c;
System.out.println(total);
}
}

class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10,20,30);
}
}
Output:
30
60

Java Math Class


Java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square root, and trigonometric functions. Unlike
some of the numeric methods of class StrictMath, all implementations of the equivalent
functions of class Math are not defined to return the bit-for-bit the same results. This
relaxation permits better-performing implementations where strict reproducibility is not
required.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 62 of 215


Object Oriented Concepts using Java
The java.lang.Math class provides us access to many of these functions. The table
below lists some of the more common among these.

Below is a list of basic mathematical operation methods describing several methods


that Java math class offers:
Math.min(): this method returns the smallest of two values.
Math.max(): this method returns the largest of two values
Math.abs(): this method returns the absolute value of the value provided.
Math.round(): this method is used to round off the decimal numbers to the nearest value.
Math.sqrt(): this method returns the square root of a number given.
Math.cbrt(): this method returns the cube root of a given number.
Math.floor(): this method is used to find the largest integer value which is less than or equal
to the argument and is equal to the double value of a mathematical integer.
Math.pow(): this method returns the value of the first argument raised to the power second
argument provided.
Math.ceil(): list method is used to find the smallest integer value that is greater than or
equal to the argument.
Math.floorDiv(): this method is used to find the largest integer value which is less than or
equal to the quotient.
Math.random(): this java random method returns a double value that carries a positive
sign which is greater than or equal to 0.0 and less than 1.0

Trigonometric math methods


Below mentioned is a list of these methods:
Math.sin(): this method returns the sine value of a given double value.
Math.cos(): this method returns the cos value of a given double value.
Math.tan(): this method returns the tangent value of a given double value.

Logarithmic math methods


Here is a list explaining these methods:
Math.log(): this method is used to return the natural logarithm of double value
Math.log10(): this method is used to return the base 10 logarithm of a double value
Math.exp(): this method returns E (Euler’s value) raised to the power of a double value.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 63 of 215


Object Oriented Concepts using Java
//Program to implement Java Math class methods
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;

// return the maximum of two numbers


System.out.println("Maximum number of x and y is: " +Math.max(x, y));

// return the square root of y


System.out.println("Square root of y is: " + Math.sqrt(y));

//returns 28 power of 4 i.e. 28*28*28*28


System.out.println("Power of x and y is: " + Math.pow(x, y));

// return the logarithm of given value


System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10


System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

// return the log of x + 1


System.out.println("log1p of x is: " +Math.log1p(x));

// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));

// return (a power of 2)-1


System.out.println("expm1 of a is: " +Math.expm1(x));
}
}
Output:
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12
expm1 of a is: 1.446257064290475E12

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 64 of 215


Object Oriented Concepts using Java
Arrays
An array is a collection of similar type of elements, which has contiguous memory
location.

Java array is an object, which contains elements of a similar data type. Additionally, the
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Advantages
o Code Optimization: It makes the code optimized; we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It does not grow
its size at runtime. To solve this problem, collection framework is used in Java, which
grows automatically.

Types of Array in java


There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array

SINGLE DIMENSIONAL ARRAY (one dimensional array):


 A list of items can be given one variable name using only one subscript and such
a variable is called one dimensional array.
 One dimensional array is a list of variables of same type that are accessed by a
common name.
 An individual variable in the array is called an array element.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 65 of 215


Object Oriented Concepts using Java
Declaration of arrays:
 To declare an array below is a general form or syntax.
Datatype arrayName[ ];
Where, Datatype is valid data type in java and arrayName is a name of an array.
Example : int physics[ ];

Creation of arrays
 To allocate space for an array element use below general form or syntax.
arrayName = new type[size];
Where arrayName is the name of the array and type is a valid java datatype
and size specifies the number of elements in the array.
Example: physics = new int[10];
Above statement will create an integer of an array with ten elements that can be
accessed by physics.
physics[0]
Structure of one dimensional array physics[1]
 Note that array indexes begins with zero.
physics[2]
 That means if you want to access 1st element of an array use zero as
physics[3]
an index.
 To access 3rd element refer below example. physics[4]
 physics[2] = 10; // it assigns value 10 to the third element of an array. physics[5]
 java also allows an abbreviated syntax to declare an array. General physics[6]
form or syntax of is is as shown below.
physics[7]
physics[8]
physics[9]

Initialization of an Array
The final step is to put values into the array created. This process is known as
initialization.
Syntax:
arrayname[subscript] = value;

Example:
physics[0]=12;
physics[1]=15;
physics[2]=16;
physics[3]=18;
physics[4]=20;
physics[5]=23;
physics[6]=25;
physics[7]=27;

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 66 of 215


Object Oriented Concepts using Java
physics[8]=30;
physics[9]=35;
In The above example assigns the value as,

physics[0] 12

physics[1] 15
physics[2] 16
physics[3] 18
physics[4] 20
physics[5] 23
physics[6] 25
physics[7] 27
physics[8] 30
physics[9] 35

Example Program:
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
10
20
70
40
50

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 67 of 215


Object Oriented Concepts using Java
Example for Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

TWO DIMENSIONAL ARRAY:


 Two Dimensional Array in Java is the simplest form of Multi-Dimensional Array.
 In Two Dimensional Array, data is stored in row and columns.
 The record can access using both the row index and column index.

Declaration of Two Dimensional Array in Java


Following the format of declaration of two-dimensional array in Java
Programming Language:

Syntax:
DataType ArrayName[][];
ArrayName = new DataType[][];
(or)
DataType ArrayName[][] = new DataType[][];
Data_type:
 This will decide the type of elements it will accept.
 For example, If we want to store integer values then, the Data Type will be declared
as int, If we want to store Float values then, the Data Type will be float etc.
Array_Name:
 This is the name you want to give it to array.
 For example Car, students, age, marks, department, employees etc

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 68 of 215


Object Oriented Concepts using Java
Creating of Two Dimensional Array in java
int[][] a = new int[3][4];
 Here, a is a two-dimensional array. The array can
hold maximum of 12 elements of type int.
 Java uses zero-based indexing, that is, indexing
of arrays in Java starts with 0 and not 1.

Intialization of Array:

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

Example:
class MultidimensionalArray
{
public static void main(String[] args)
{
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}

Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 69 of 215


Object Oriented Concepts using Java
One Marks Questions
1. What is object and class?
2. What do you mean by data abstraction and encapsulation?
3. What is inheritance? Mention types of inheritance.
4. What is binding? Mention different types of binding
5. Who and when java was developed?
6. What was the first name of java?
7. Expand JDK, JVM and JRE
8. Which is the latest version of java?
9. When & which company owns java?
10. Why java is called compiled and interpreted language?
11. What do you mean platform independent?
12. What do you mean by garbage collection in java?
13. Why is java is called secured?
14. Mention types of programs in java?
15. What is import statement? Give example
16. What is javac and java?
17. What are tokens? Mention types of java tokens?
18. What is identifier? Give Example
19. Mention any two valid and invalid identifiers
20. What is literal? Give example
21. What is variable? Mention types of variable
22. What is byte code in java?
23. Write any 5 keywords in java?
24. What is static and final modifiers in java?
25. What is reference data types in java?
26. What is instanceof and new operator in java?
27. What is one way branching?
28. What is two way branching?
29. What is method? Mention different types of user defined methods in java?
30. What is method overloading? Give example
31. Mention different types to implement method overloading in java?
32. Why Math class is used in java?
33. Math.floor() and Math.random() mention their use in java?
34. What is array? Mention types of array
35. Write syntax to create array in java?

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 70 of 215


Object Oriented Concepts using Java
Five Marks Questions
1. Write a short note on History of Java?
2. Why java is Platform independent? Justify your answer
3. Write a short note on JVM?
4. Is java pure object oriented language? Justify your answer
5. Explain public static void main (String [] args) method in java?
6. Write rules to declare identifiers or variable.
7. How to declare constants in java?
8. What is class or static variable? Explain with example
9. Write a short note on Operators in Java?
10. What is ternary operator? Explain with syntax and example?
11. Differentiate between while and do while loop?
12. Explain switch statement with syntax and example?
13. Explain break and continue statements in java?
14. What is method? Explain different types methods in java?
15. Write a short note on Math class and its methods in java?

Ten Marks Questions


1. Explain concepts of OOPs?
2. What is inheritance? Explain different types of inheritance with example.
3. Explain features of Java?
4. Explain Structure of Java Program with an example?
5. What is constant? Explain different types of constants with example.
6. What are datatypes? Explain different types of datatypes with example.
7. Explain different types of variables available in java?
8. With a syntax and example explain different types of decision-making statements?
9. With a syntax and example explain different types of looping statements?
10. What is Function overloading or Compile time polymorphism with an example.
11. With syntax and example, write declaration, initialization of arrays in java?
12. Explain different types of arrays in java?

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 71 of 215


Object Oriented Concepts using Java

UNIT 2
OBJECTS AND CLASSES
Introduction
Java is an object-oriented programming language. Anything we wish to represent in
java program must be encapsulated in a class that defines the state and behavior of program
components known as objects. Classes create objects and objects use methods to
communicate between them. The core concept of the object-oriented approach is to break
complex problems into smaller objects.

An object is any entity that has a state and behavior. For example, a bicycle is an object. It
has

States/Characteristics/data members: idle, first gear, etc


Behaviors/methods/member functions: braking, accelerating, etc.
Before we learn about objects, let us first know about classes in Java.

Java Class
A class is a user defined blueprint or template for which objects are created. Before
we create an object, we first need to define the class. We can think of the class as a sketch
(prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based
on these descriptions we build the house. House is the object. Since many houses can be
made from the same description, we can create many objects from a class.

Defining a Class
Java provides a reserved keyword class to define a class. The keyword must be
followed by the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:


1. Access specifier or Modifiers: We can access Java classes using any access modifiers
such as public, private, protected and default.
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by convention).
4. Superclass (if any): The name of the class's parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent. While using
inheritance we use this.
5. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
6. Body: The class body surrounded by braces, { }.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 72 of 215


Object Oriented Concepts using Java
Syntax:
class Classname [extends superclassname] //optional
{
[Fields declaration:] //optional
[Methods declaration:] //optional
}

Everything inside the square brackets is optional

Example:

Fields Declaration:
 Data is encapsulated in a class by placing data fields inside the body of the class.
 These variables called instance variable.
 Because they created whenever an object of the class is instantiated.

Ex:
class Rectangle
{
int length;
int width; [also can declare as int length , width;]
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 73 of 215


Object Oriented Concepts using Java
 The class Rectangle contains two integer type instance variables.
 Instance variable doesn’t get memory at compile time.
 It gets memory at run time when object is (instance) created.
 That’s why it is called instance variable.

Methods Declaration:
 A class with only data fields (no methods) has no life.
 Add methods that are necessary for manipulating the data in the class.
 Methods are declared inside the body of the class after the declaration of instance
variables.

Syntax:
return_type methodname(parameter-list)
{
Method–body;
}
Method declarations have four basic parts:
1. The name of the method (method name).
2. The type of the value the method returns(type).
3. A list of parameters(parameter – list).
4. The body of the method.
 The type specifies the type of value the method world return. It could be void type,
if the method does not return any value.
 The method name is a valid identifier.
 The parameter list is always enclosed in parenthesis. The list contains variable and
its types.
Ex: void getdata (int a, int b);
 The body actually describes the operation to be performed on the data.

Example:
Class Rectangle
{
int length;
int width; // field declaration
void getdata(int x, int y) // method declaration
{
length = x;
width = y;
}
}
 Return type is void because it does not return any value.
We pass two integer values to the method, which are then assigned to the instance variable.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 74 of 215


Object Oriented Concepts using Java
Ex:
class Rectangle
{
int length, width; //fields declaration
void getData (int x, int y) //method declaration
{
length = x;
width = y;
}
int rectArea() //method declaration
{
int area = length* width;
return(area);
}
}
The new method rectArea() computes area of the rectangle and returns the result.

Accessing Instance Variable:


 An Instance variable within a method could not be accessible from other method.

Ex:
class Access
{
int x;
void method1()
{
int y;
x = 10; //legal
y= x; // legal
}
void method2()
{
int z;
x=5; // legal
z =10; // legal
y =1; // illegal couldn’t access y.
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 75 of 215


Object Oriented Concepts using Java
OBJECT:
 An object is a Real world entity.
 It is Run time entity
 It has state and behaviour.
 It is an instance of a class.

CREATING OBJECTS:
 An object in java is essentially a block of memory that contains space to store all the
instance variable.
 Objects in java are created using the new operation or operator or keyword.
 The new operator creates an object of the specified class and returns a reference to
that object.

Example:
Rectangle rect1; // Declare the object.
Rect1 = new Rectangle(); // instantiate the object.

 The first statement declares a variable to hold the object reference.


 The second one actually assigns the object reference to the variable.
 Both statements can be combined into one.

Rectangle rect1 = new Rectangle();

ACTION STATEMENT RESULT

Declare Rectangle rect1; Null rect1

Instantiat Rect1=new Rectangle(); rect1


e

Rect1 is a reference to Rectangle


Rectangle object object

Accessing Class Members:


 Every object containing its own set of variable.
 To access the class members follow the below syntax.
 We are outside the class, we cannot access the instance variables and the methods
directly. We must use object name and dot operator as shown below

Syntax:
objectname.variablename = value;
objectname.methodname(parameter-list);
Where,
object name = object.
variable name = name of the instance variable.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 76 of 215


Object Oriented Concepts using Java
value = value for that.
method name = method which want to call.
parameter-list = actual values.
Example:
public static void main (String [] args)
{
int area1,area2;
Rectangle rect1 =new Rectangle(); //creating object1
Rectangle rect2 =new Rectangle(); //creating object2
rect1.lenth =15; //accessing variable.
rect1.width =10; //accessing variable.
area1 =rect1.length*rect1.width;
rect2.getData (20, 12); //accessing variable.
area2 =rect2.rectArea();
}
rect1.length =15;
rect1.width =10;
rect2.length =20;
rect2.width =12;

Two object rect1 and rect2 store different values as shown below.
rect1 rect2
rect1.length 15 rect2.length 20
rect1.width 10 rect2.width 12

// Example Implementation of Class and Objects


class Rectangle // Class declaration
{
int length, width; // field declaration (instance variable)
void getData(int x, int y) //Method1 declaration
{
length =x;
width =y;
}
int rectArea() //Method2 declaration
{
int area =length*width;
return (area);
}
}
Class rectArea
{
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 77 of 215
Object Oriented Concepts using Java
public static void main(String area [ ])
{
int area1, area2;
Rectangle rect1 =new Rectangle (); // creating objects1
Rectangle rect2=new Rectangle (); // creating objects2
rect1.length =15; // Accessing variable for Object1
rect1.width =10; // Accessing variable for Object1
area1=rect1.length*rect1.width;
rect2 .getData(20,12); // Accessing method for Object2
area2=rect2.rectArea(); // Accessing method for Object2
system.out.println(“Area1=”+area1);
System.out.println(“ Area2=”+ area2);
}
}

Output:
Area1=150
Area2=240

Example2:
Class employee //class declaration
{
int id; //Field declaration (Instance variable)
string name; //Field declaration (Instance variable)
float salary; //Field declaration (Instance variable)
void insert(int i,string n,float s) //Method1 declared
{
id=i;
name=n;
salary=s;
}
void display ( ) //Method2 declared
{
system.out.println(id+” “+name” “+salary);
}
public class Emp
{
public static void main (string [ ]args)
{
Employee e1= new Employee (); //Object1 declared
Employee e2=new employee (); //Object2 declared
Employee e3=new employee (); //Object3 declared

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 78 of 215


Object Oriented Concepts using Java
e1.insert(101,”ajeet”, 45000); // Accessing of instance variable for object1
e2.insert(102,”irfan”, 25000); // Accessing of instance variable for object2
e3.insert(103,”nakul”, 55000); // Accessing of instance variable for object3
e1.display (); // Accessing of method
e2.display (); // Accessing of method
e3.display (); // Accessing of method
}}

output:
101 ajeet 45000
102 irfan 25000
103 nakul 55000

CONSTRUCTOR:
 Java constructors or constructors in Java is a terminology been used to construct
something in our programs.
 Constructor in java is a special type of method that is used to initialize the object.
 Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
 Constructs construct the values for object.
 Constructors are invoked implicitly when you instantiate objects.
 A constructor can be overloaded but cannot be overridden.

Rules for creating java constructor


There are rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
3. Constructors are called only once at the time of Object creation while method(s)
can be called any number of times.
4. A constructor in Java cannot be abstract, final, static, or synchronized.
5. Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.

Types of java constructors


There are two types of constructors:
1. Default constructor
2. No argument/parameter constructor
3. Parameterized constructor

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 79 of 215


Object Oriented Concepts using Java
1. Java Default Constructor
A default constructor is a constructor created by the compiler if we do not define
any constructor(s) for a class. The default constructor initializes instance variables with
default values.
Syntax:
<class_name>()
{
Constructor body
}
Example: (Default constructor)
class Student
{ int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1=new Student(); // Default constructor called
Student s2=new Student(); // Default constructor called
s1.display();
s2.display();
}
}
Output:
0 null
0 null
In the above class, we are not creating any constructor so compiler provides you a
default constructor. Here 0 and null values are provided by default constructor.

2. No argument/Parameter Constructor
 A constructor that don’t have parameters is known as no parameterized constructor.
 No Parameter constructor is used to provide default values to the distinct objects.
 If a constructor does not accept any parameters, it is known as a no-argument
constructor.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 80 of 215


Object Oriented Concepts using Java
Example: (No Argument/parameter constructor)
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
class Bike1
{
Bike1() // constructor declared
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1(); // constructor called
}
}

Output:
Bike is created

3. Java parameterized constructor


 A constructor that have parameters is known as parameterized constructor.
 Parameterized constructor is used to provide different values to the distinct objects.

Syntax:
<class_name>(parameter list)
{
Constructor body
}
Example: (parameterized constructor)
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 81 of 215


Object Oriented Concepts using Java
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

Note : A lot of people mix up the default constructor for the no-argument constructor, but they are
not the same in Java. Any constructor created by the programmer is not considered a default
constructor in Java.

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.
Java Constructor Java Method

Constructor is used to initialize the state Method is used to expose behaviour of an


of an object. object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.


The java compiler provides a default
Method is not provided by compiler in
constructor if you don't have any
any case.
constructor.

Constructor name must be same as the Method name may or may not be same as
class name. class name.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 82 of 215


Object Oriented Concepts using Java
Constructor Overloading
We can overload constructors like methods. The constructor overloading casn be
defined as the concept of having more than one constructor with different parameters so
that every constructor can perform a different task.

// Example for Constructor Overloading


class Main
{
String language;
// constructor with no parameter
Main()
{
this.language = "Java"
}
// constructor with a single parameter
Main(String language)
{
this.language = language;
}

public void getName()


{
System.out.println("Programming Langauage: " + this.language);
}

public static void main(String[] args)


{
// call constructor with no parameter
Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

obj1.getName();
obj2.getName();
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 83 of 215


Object Oriented Concepts using Java
Finalizer
Finalize method in Java is an Object Class method that is used to perform cleanup
activity before destroying any object. Garbage collector calls it before destroying the object
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 is an Object class method in Java. The finalize() method is a non-static and
protected method of java.lang.object class. In java, the Object class is superclass of all java
classes. Being an object class method finalize() method is available for every class in Java.
Hence, Garbage Collector can call finalize() method on any java object for clean-up activity.

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 in java, 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.

Before starting with syntax and coding of finalize() method in Java. Let's first see the terms
like Garbage collector, Clean up activity related to the method.

public class Demo


{
public static void main(String[] args)
{
String s1 = "Hello World!";
s1 = null;
System.gc();
System.out.println("Garbage collector is called");
}

@Override
protected void finalize()
{
System.out.println("Finalize method is called.");
}
}
Output:
Garbage collector is called

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 84 of 215


Object Oriented Concepts using Java
In the above program, when the String object 'a' holds value 'Hello World!' it has a reference
to 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.

Garbage Collector
The garbage collector is a part of Java Virtual Machine(JVM). Garbage
collector checks the heap memory, where all the objects are stored by JVM, looking for
unreferenced objects that are no more needed. And automatically destroys those objects.
Garbage collector calls finalize() method for clean up activity before destroying the object.
Java does garbage collection automatically; there is no need to do it explicitly, unlike other
programming languages.
The garbage collector in java can be called explicitly using the following method:
System.gc();
System.gc() is a method in java that invokes garbage collector which will destroy the
unreferenced objects. System.gc() calls finalize() method only once for each object.

What is the Cleanup Activity?


Cleanup activity is the process of closing all the resources being used by an object
before it is destroyed. Resources that are being used by any object are
database connections, network connections, etc. These resources are released and clean-up
activity is performed by the garbage collector in java and then the object is deleted.

The major advantage of performing clean-up before garbage collection is data resources or
network connections that are linked to unreferenced object are revoked and can be used
again. Cleanup ensures resources are not linked to objects unnecessary and helps JVM in
boosting memory optimization and speed.

Visibility Modifiers or Access Modifiers in Java


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:


1. Default
2. Private
3. Protected
4. Public

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 85 of 215


Object Oriented Concepts using Java
Default
When we don't use any keyword explicitly, Java will set a default access to a given
class, method or property. The default access modifier is also called package-private, which
means that all members are visible within the same package but aren't accessible from
other packages:

Private
Any method, property or constructor with the private keyword is accessible from the
same class only. This is the most restrictive access modifier and is core to the concept of
encapsulation. All data will be hidden from the outside world. Private signifies “just visible
inside the enclosing class“.

Protected
If we declare a method, property or constructor with the protected keyword, we can
access the member from the same package (as with package-private access level) and in
addition from all subclasses of its class, even if they lie in other packages. Protected
signifies “just noticeable inside the enclosing class and any subclasses“.

Public
If we add the public keyword to a class, method or property then we're making it
available to the whole world, i.e. all other classes in all packages will be able to use it. This
is the least restrictive access modifier:

//Program to implement access specifiers


class Access
{
int i;
public int j;
private int k;
protected int p;
void setValue(int i1,int j1,int k1,int p1) {
i=i1;
j=j1;
k=k1;
p=p1;
}
void base_view()
{
System.out.println("\t\t Base class");
System.out.println("Default = "+i);
System.out.println("Public = "+j);
System.out.println("Private = "+k);
System.out.println("Protected = "+p); }
}
class sub extends Access

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 86 of 215


Object Oriented Concepts using Java
{
void derived_view()
{
System.out.println("\t\t Derived Class");
System.out.println("Default = "+i);
System.out.println("Public = "+j);
/*System.out.println("Private = "+k); */
System.out.println("Protected = "+p);
}
}

class MemberAccess
{
public static void main(String args[])
{
sub t=new sub();
t.setValue(1,2,3,4);
t.base_view();
t.derived_view();
}
}

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Inbuilt classes in java


Built-in Classes Java provide some useful classes in the java.lang. Class and
Instance Methods

Some of built in classes of java are


 String
 String Buffer
 Character
 Files

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 87 of 215


Object Oriented Concepts using Java
String & String Buffer class
 Basically, string is a sequence of characters but it’s not a primitive type.
 When we create a string in java, it actually creates an object of type String.
 String is immutable object which means that it cannot be changed once it is created.
 String is the only class where operator overloading is supported in java. We can
concatenate two strings using + operator. For example "a"+"b"="ab".
 Java provides two useful classes for String
manipulation StringBuffer and StringBuilder.

How to create a string object?


There are two ways to create String object:
1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

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

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

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

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 88 of 215


Object Oriented Concepts using Java
public static void main(String args[])
{
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.

Some String functions or methods


Method Description Return
Type
charAt() Returns the character at the specified index char
(position)
compareTo() Compares two strings lexicographically int
compareToIgnoreCase() Compares two strings lexicographically, ignoring int
case differences
concat() Appends a string to the end of another string String
equals() Compares two strings. Returns true if the strings boolean
are equal, and false if not
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
length() Returns the length of a specified string int
split() Splits a string into an array of substrings String[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String

String Buffer class


 A string buffer is like a String, but can be modified.
 It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
 They are safe for use by multiple threads.
 Every string buffer has a capacity.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 89 of 215


Object Oriented Concepts using Java
Difference between Sting & String Buffer Class
No. String StringBuffer
1) The String class is immutable. The StringBuffer class is mutable.
2) String is slow and consumes more memory when StringBuffer is fast and consumes
we concatenate too many strings because every less memory when we
time it creates new instance. concatenate t strings.
3) String class overrides the equals() method of StringBuffer class doesn't
Object class. So you can compare the contents of override the equals() method of
two strings by equals() method. Object class.
4) String class is slower while performing StringBuffer class is faster while
concatenation operation. performing concatenation
operation.
5) String class uses String constant pool. StringBuffer uses Heap memory

Character class
The Character class is a wrapper that is used to wrap a value of the primitive type
char in an object. An object of class Character contains a single field whose type is char.
This class provides a large number of static methods for determining a character's
category (lowercase letter, digit, etc.) and for converting characters from uppercase to
lowercase and vice versa. This class is located into java.lang package.

Creating a Character object:


Character ch = new Character('a');
The above statement creates a Character object which contains ‘a’ of type char. There
is only one constructor in the Character class that expects an argument of char data type.

Files Class
The File class is an abstract representation of file and directory pathname. A
pathname can be either absolute or relative.
The File class have several methods for working with directories and files such as
creating new directories or files, deleting and renaming directories or files, listing the
contents of a directory etc.

this keyword
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".

this can also be used to:


 Invoke current class constructor
 Invoke current class method

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 90 of 215


Object Oriented Concepts using Java
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

//Program to implement this keyword


public class Main
{
int x;
// Constructor with a parameter
public Main(int x)
{
this.x = x;
}
// Call the constructor
public static void main(String[] args)
{
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}

One mark question


1. What is class?
2. Define object
3. Write syntax for defining a class.
4. Write syntax to create object.
5. Write few examples of object.
6. How do we access fields and methods of a class?
7. What is field & method?
8. Define constructor.
9. Write types of constructors.
10. Difference between default and parameterized constructor?
11. What is constructor overloading?
12. Why we need constructor in java?
13. When constructor is invoked in java?
14. Mention any 2 rules of a constructor?
15. Write syntax for defining a constructor in class.
16. Define finalizer
17. What do you mean by garbage collector in java?
18. What is the use of finalizer() method in java?
19. gc() method is used for?
20. When is gc() is invoked in java?

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 91 of 215


Object Oriented Concepts using Java
21. Mention different visibility modifiers or access modifiers in java
22. Define private & public
23. What is default & protected?
24. Write few inbuilt classes available in java
25. What is the difference between String and StringBuffer class?
26. Mention few String class methods available in java
27. Write use of this keyword in java.
28. Can we inherit private members? Justify

Five mark questions


1. What is class? Write syntax and example of a class
2. Write a short note on class & object
3. Write features of constructors
4. Mention types of constructors? Explain any one type of constructor
5. Differentiate between constructor and method in java
6. Explain constructor overloading with an example?
7. Write a short note of garbage collection in java
8. What is private, public, protected and default?
9. Write a short note of this keyword.

Ten mark questions


1. With an example explain how to declare and define a class and object in java?
2. Write a program to show working constructor overloading in java.
3. Explain different types of constructors available in java?
4. Explain different visibility modifiers in java?

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 92 of 215


Object Oriented Concepts using Java

UNIT-3
INHERITANCE AND POLYMORPHISM
Inheritance:
 Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours of parent object. Inheritance represents the IS-A relationship, also known
as parent child relationship.
 The mechanism of deriving a new class from an old class is called inheritance.
 The old class is known as the Base class or Parent class or Super class
 The new class is called the Derived class or Child class or Sub class
 The inheritance allows subclasses to inherit all the variables and methods of their
parent classes.
 Inheritance allows us to reuse of code, it improves reusability in your java application.

Syntax
class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 93 of 215


Object Oriented Concepts using Java
Java Inheritance Example
 As displayed in the figure
 Programmer is the subclass and Employee is the
superclass.
 Relationship between two classes is Programmer IS-A
Employee.
 It means that Programmer is a type of Employee.

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

Output:
Programmer salary is:40000.0
Bonus of programmer is:10000

Types of Inheritance:
 On the basis of class, there can be three types of inheritance in java
1. Single
2. Multilevel
3. Hierarchical
 Multiple and hybrid inheritance is supported through interface only.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 94 of 215


Object Oriented Concepts using Java
Single Inheritance:
 One sub class is derived from one super class
 From the above diagram class A serves as a Super class or parent class
 Class B serves as a Base class or Sub class.
Example:
class Animal //base class
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal //derived class
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...

From the above example, A class Animal is Super


class and class Dog is Sub class. Class Dog inherits
the properties of Class Animal.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 95 of 215


Object Oriented Concepts using Java
Multilevel Inheritance:
 In Multilevel inheritance there is a concept of grandparent class.
 From the above diagram then class C inherits class B and class B inherits class A
 Which means B is a parent class of C and A is a parent class of B.
 So in this case class C is implicitly inheriting the properties and method of class A
along with B that’s what is called multilevel inheritance.
Example:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("barking...");
}
}

class BabyDog extends Dog


{
void weep()
{
System.out.println("weeping...");
}
}

class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 96 of 215


Object Oriented Concepts using Java
Output:
weeping...
barking...
eating...

Hierarchical Inheritance:
 As in the below diagram that a class has more than one child classes (sub classes).
 In other words more than one child classes have the same parent class then such kind
of inheritance is known as hierarchical.
 Class A is a parent class of class B, class C and class D.
 One Parent class has many sub classes.

Example:
class Animal // PARENT CLASS
{
void eat()
{
System.out.println("eating...");
}
}

class Dog extends Animal // Sub class extends parent class


{
void bark()
{
System.out.println("barking...");
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 97 of 215


Object Oriented Concepts using Java
class Cat extends Animal // another Sub class extends parent class
{
void meow()
{
System.out.println("meowing...");
}
}

class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}
}

Output:
meowing...
eating...

Benefits of Inheritance
 Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
 In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 98 of 215


Object Oriented Concepts using Java
Method Overriding or Run time Polymorphism
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
 In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. Method must have same name as in the parent class
2. Method must have same parameter as in the parent class.
3. Must be IS-A relationship (inheritance).

Example of method overriding


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

 In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation.
 The name and parameter of the method is same and there is IS-A relationship
between the classes, so there is method overriding.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 99 of 215


Object Oriented Concepts using Java
Example Program:
class Bank
{
int getRateOfInterest()
{
return 0;
}
}

class SBI extends Bank


{
int getRateOfInterest()
{
return 8;
}
}

class ICICI extends Bank


{
int getRateOfInterest()
{
return 7;
}
}

class AXIS extends Bank


{
int getRateOfInterest(){
return 9;
}
}

class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 100 of 215
Object Oriented Concepts using Java
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Difference between Method Overloading and Overriding


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

Polymorphism
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an
object (or reference) to assume (be replaced by) or become many different forms of object.
Example: method/function overloading & method/function overriding.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 101 of 215
Object Oriented Concepts using Java
Example1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.

Example2:
Below is a simple example of the above concept of polymorphism:
6 + 10
The above refers to integer addition.
The same + operator can also be used for floating point addition:
7.15 + 3.78

Types of Polymorphism
There are two types of polymorphism one is compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is method/function
overloading. Runtime time polymorphism is done using inheritance and method/function
overriding. Here are some ways how we implement polymorphism in Object Oriented
programming languages.

Compile time polymorphism -> Method/Function Overloading


Run time polymorphism -> Method/Function Overriding.

Compile Time Polymorphism:


The compiler is able to select the appropriate function for a particular call at compile-
time itself. This is known as compile-time polymorphism. The compile-time polymorphism
is implemented with templates.
 Method/Function overloading

Method/Function Overloading
Using a single function name to perform different types of tasks is known as function
overloading. Using the concept of function overloading, design a family of functions with one
function name but with different argument lists. The function would perform different
operations depending on the argument list in the function call. The correct function to be
invoked is determined by checking the number and type of the arguments but not on the
function type.

Run-time polymorphism
The appropriate member function could be selected while the programming is
running. This is known as run-time polymorphism. The run-time polymorphism is
implemented with inheritance.
 Method/Function overriding

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 102 of 215
Object Oriented Concepts using Java
Method/Function Overriding
 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
 In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.

Dynamic Binding or Late Binding


When the compiler resolves the method call binding during the execution of the
program, such a process is known as Dynamic or Late Binding in Java. We also call Dynamic
binding as Late Binding because binding takes place during the actual execution of the
program.
The best example of Dynamic binding is the Method Overriding where both the
Parent class and the derived classes have the same method. And, therefore the type of the
object determines which method is going to be executed.
The type of object is determined during the execution of the program, therefore it is
called dynamic binding.

Generic Programming
Generics means parameterized types. The idea is to allow type (Integer, String, …
etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using
Generics, it is possible to create classes that work with different data types. An entity such
as class, interface, or method that operates on a parameterized type is a generic entity.

Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any
object. These features lack type safety. Generics add that type of safety feature. We will
discuss that type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like HashSet,
ArrayList, HashMap, etc., use generics very well. There are some fundamental differences
between the two approaches to generic types.

Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic method has type
parameters that are cited by actual type. This allows the generic method to be used in a
more general way. The compiler takes care of the type of safety which enables
programmers to code easily since they do not have to perform long, individual type
castings.

Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 103 of 215
Object Oriented Concepts using Java
parameter, separated by a comma. The classes, which accept one or more parameters, are
known as parameterized classes or parameterized types.

// Program to show working of user defined Generic classes

// We use < > to specify Parameter type


class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main
{
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj = new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}

Casting of Objects
Typecasting is the assessment of the value of one primitive data type to another type.
In java, there are two types of casting namely upcasting and downcasting as follows:

1. Upcasting is casting a subtype to a super type in an upward direction to the inheritance


tree. It is an automatic procedure for which there are no efforts poured in to do so
where a sub-class object is referred by a superclass reference variable. One can relate it
with dynamic polymorphism.
 Implicit casting means class typecasting done by the compiler without cast syntax.
 Explicit casting means class typecasting done by the programmer with cast syntax.

2. Downcasting refers to the procedure when subclass type refers to the object of the
parent class is known as downcasting. If it is performed directly compiler gives an

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 104 of 215
Object Oriented Concepts using Java
error as ClassCastException is thrown at runtime. It is only achievable with the use
of instanceof operator the object which is already upcast, that object only can be
performed downcast.

In order to perform class type casting we have to follow these two rules as follows:
1. Classes must be “IS-A-Relationship “
2. An object must have the property of a class in which it is going to cast.

Instance of operator
The instanceof operator checks whether an object is an instanceof a particular class.
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with
any variable that has null value, it returns false.

//Program to implement working of instance of operator


class Main
{
public static void main(String[] args)
{
String str = "Programiz";
boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Output
Is str an object of String? true
Here, str is an instance of the String class. Hence, the instanceof operator returns true.

Abstract Class & Methods


 An Abstract class is a conceptual class.
 An Abstract class cannot be instantiated – objects cannot be created.
 Abstract classes provides a common root for a group of classes, nicely tied together in a
package.
 When we define a class to be “final”, it cannot be extended. In certain situation, we want
properties of classes to be always extended and used. Such classes are called Abstract
Classes.
 Abstract method can never be final and static.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 105 of 215
Object Oriented Concepts using Java
Properties of Abstract Class
• A class with one or more abstract methods is automatically abstract and it cannot be
instantiated.
• A class declared abstract, even with no abstract methods cannot be instantiated.
• A subclass of an abstract class can be instantiated if it overrides all abstract methods
by implementing them.
• A subclass that does not implement all of the superclass abstract methods is itself
abstract; and it cannot be instantiated.
• We cannot declare abstract constructors or abstract static methods.

Syntax:
abstract class ClassName
{
...

abstract DataType MethodName1();


DataType Method2()
{
// method body
}
}
EXAMPLE:
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
OUTPUT:
running safely..

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 106 of 215
Object Oriented Concepts using Java
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

Interface
 An interface in java is a blueprint of a class. It has static constants and abstract
methods.
 The interface in java is a mechanism to achieve abstraction.
 There can be only abstract methods in the java interface not method body.
 It is used to achieve abstraction and multiple inheritance in Java.
 It cannot be instantiated just like abstract class.
 A class implements an interface, thereby inheriting the abstract methods of the
interface.

 Writing an interface is similar to writing a class. But a class describes the


attributes and behaviours of an object. And an interface contains behaviours that
a class implements.
 The class that implements the interface is abstract. all the methods of the interface
need to be defined in the class.
An interface is similar to a class in the following ways −
 An interface can contain any number of methods.

 An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
 The byte code of an interface appears in a .class file.

 Interfaces appear in packages, and their corresponding bytecode file must


be in a directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 107 of 215
Object Oriented Concepts using Java

<<Interface>>
Speaker
speak()

Politician Priest Lecturer


speak() speak() speak()

Declaring Interface:
The interface keyword is used to declare an interface. Here is a simple
example to
declare an interface −

Syntax:
public interface NameOfInterface
{
// Any number of final, static fields
// Any number of abstract method declarations
}

Interfaces have the following properties −


 An interface is implicitly abstract. Not need to use the abstract keyword
while declaring an interface.
 Each Fields in an interface is also implicitly static and final, so the
static and final keyword is not needed (Refer below diagram).
 Methods in an interface are also implicitly public.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 108 of 215
Object Oriented Concepts using Java
Example:
Interface ItemConstants //interface declared
{
int code = 1001; // Variable
declared in interface string name = “Fan”;
void display(); // Method declared in interface
}

Variable Declaration:

static final type VariableName=value;

Method Declaration:

return_type methodName (parameter_list);

Implementing Interface:
 Interfaces are used as “Super classes” whose properties are inherited by classes.

 It is therefore necessary to create a class that inherits the given interface.


SYNTAX:
Class className implements interfacename
{
Body of classname
}

Example:
interface Drawable // Interface declared
{
void draw();
}
class Rectangle implements Drawable //class implements interface
{
public void draw()
{
System.out.println("drawing rectangle");
}}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 109 of 215
Object Oriented Concepts using Java
Example:
interface Printable // Interface 1 declared
{
void print();
}
interface Showable // Interface 2 declared
{
void show();
}
class A7 implements Printable,Showable // implementing interface
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7(); // object declaration
obj.print();
obj.show();
}
}

OUTPUT:
Hello
Welcome

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 110 of 215
Object Oriented Concepts using Java
Extending Interface:
 An interface can extend another interface in the same way that a class can extend
another class.

 The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
 As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.

Syntax:

interface Name2 extends Name1


{
Body of Name2
}

 An interface can be subinterfaced from other interfaces.


 The new subinterface will inherit all the members of the subinterface in the
manner similar to subclasses.

Example:

Interface ItemConstants
{
int code =
1001; string
name = “Fan”;
}
Interface Item extends ItemConstants
{
void display();
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 111 of 215
Object Oriented Concepts using Java
Final Keyword:
 The final keyword in java is used to restrict the user.
 We can prevent an inheritance of classes by other classes by declaring them as final
classes.
 Any attempt to inherit these classes will cause an error.
 The java final keyword can be used in many
context. Final can be:

1. Variable/field
2. Method
3. class

The final variable:


 The final keyword can be applied with the
variables.
 If the variable as final, then the variable cannot change the value of final variable (It
will be constant).
 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.

Example:
In the below example 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

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 112 of 215
Object Oriented Concepts using Java
Final method:
 If the java Method made as final, then it won’t be overridden.

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();
honda.run();
}
}
Output: Compile Time Error

Final class:
 We can prevent an inheritance of classes by other classes by declaring them as final
classes.
 If the class has final, then the properties of that class couldn’t inherits.
 Any attempt to inherit these classes will cause an error.

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 Honda();

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 113 of 215
Object Oriented Concepts using Java
honda.run();
}
}

Output: Compile Time Error

JAVA PACKAGES:
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two types,
1. Java API package (Built-in package)
2. User-defined package. (Defined by user)
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
 Here, we will have the detailed learning of creating and using user-defined
packages.

Advantage of Java Package


 Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
 Java package provides access protection.
 Java package removes naming collision.

1. Java API Packages.


 Java APl(Application Program Interface) provides a large numbers of classes
grouped into different packages according to functionality.
 Most of the time we use the packages available with the the Java API.
 Following figure shows the system packages that are frequently used in the
programs.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 114 of 215
Object Oriented Concepts using Java

PACKAGE CONTENTS
NAME

Language support classes. They include classes for primitive types,


java.lang
string, math functions, thread and exceptions.
Language utility classes such as vectors, hash tables, random numbers,
java.util
data, etc.
Input/output support classes. They provide facilities for the input and
java.io
output of data.
java.applet Classes for creating and implementing applets.
Classes for networking. They include classes for communicating with
java.net
local computers as well as with internet servers.
Set of classes for implementing graphical user interface. They
java.awt
include classes for windows, buttons, lists, menus and so on.

Using API Packages


 The import statements are used at the top of the file, before any class declarations.
 The first statement allows the specified class in the specified package to be
imported. For example,
import java.awt.color;

 The above statement imports class color and therefore the class name can now be
directly used in the program.
 The below statement imports every class contained in the specified package.
import java.awt.*;
The above statement will bring all classes of java.awt package.

Creating User Defined Packages


 When you write a Java program, you create many classes. You can organize these classes
by creating your own packages.
 The packages that you create are called user-defined packages.
 A user-defined package contains one or more classes that can be imported in a Java
program.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 115 of 215
Object Oriented Concepts using Java
Syntax:
package <package_name>
// Class definition
public class <classname1>
{
// Body of the class.
}

Example:
package land.vehicle;
public class Car
{
String brand;
String color;
int wheels;
}

Steps Creating User defined packages


• Create a source file containing the package definition
• Create a folder having the same name as package name and save the source file within
the folder.
• Compile the source file.

Importing User Defined Packages


• You can include a user-defined package or any java API using the import statement.
• The following syntax shows how to implement the user-defined package, vehicle
from land in a class known as MarutiCar

import land.vehicle.Car;
public class MarutiCar extends Car
{
// Body of the class.
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 116 of 215
Object Oriented Concepts using Java
//Example program to implement user defined packages
package student.fulltime.BCA;//creating new package
import java.util.Scanner;
public class Studentpkg
{
public String name,sex;
public int age;
public void accept()
{
System.out.print("Enter the name ");
Scanner scan=new Scanner(System.in);
name=scan.nextLine();
System.out.print("Enter the sex ");
sex=scan.nextLine();
System.out.print("Enter the age ");
Scanner scan1=new Scanner(System.in);
age=scan1.nextInt();
}
public void display()
{
System.out.println("\nStudent Information\n") ;
System.out.println("Name:"+name+"\n"+"Sex"+sex+"\n"+"Age"+age+"\n");
}
}
Compile the above program and save in the directory.

Studentp.java
package student.fulltime.BCA;
import student.fulltime.BCA.Studentpkg;
public class Studentp
{
public static void main(String[] args)
{
Studentpkg s1=new Studentpkg();
s1.accept();
s1.display();
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 117 of 215
Object Oriented Concepts using Java
One mark questions
1. What is inheritance?
2. Why do we need inheritance?
3. Which keyword is used to do inheritance?
4. Define base class and derived class.
5. Write syntax for inheritance
6. Write types of inheritance available in java.
7. What is single inheritance? Give example
8. What is Multi-level inheritance? Give example
9. What is hierarchical inheritance? Give example
10. Can we inherit from more than base class in java?
11. What is interface?
12. Can we implement multiple inheritance in java? Justify
13. Write any two advantages of inheritance.
14. What do you mean by ambiguity situation?
15. What is polymorphism? Give example
16. What is method overriding? Give example
17. Define dynamic binding.
18. What is generic programming?
19. Write types of java generics
20. What is casting of objects?
21. What is upcasting and downcasting?
22. Write use of instance of operator.
23. What is abstract class?
24. Write syntax to declare abstract class?
25. What is abstract methods?
26. What is the use of abstract methods?
27. Which keyword is used to define interface?
28. What is the use of final keyword?
29. What is final class?
30. What is package?
31. Write any 2 built in package available in java.
32. Mention types of packages?
33. Write syntax for creating user defined packages.
34. Write syntax for importing packages in java

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 118 of 215
Object Oriented Concepts using Java
Five mark questions
1. What is inheritance? Explain single inheritance with example
2. Write advantages of inheritance.
3. Write a short note on inheritance.
4. Differentiate between method overriding and method overloading
5. Write Difference between inheritance and interface
6. With syntax and example explain interface.
7. Write a short note on java generics.
8. Explain any 2 built in packages of java?
9. Explain final field and final method?
10. Write properties of abstract class?
11. Write the features of method overriding.
12. Write advantages of packages.

Ten mark questions


1. What is inheritance? Explain different types of inheritance with example
2. Explain interface with an example?
3. Write steps to create user defined package with example
4. Explain method overloading or compile time polymorphism with an example?
5. Explain method overriding or run time polymorphism with an example?

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 119 of 215
Object Oriented Concepts using Java

Unit – 4
Event and GUI Programming
Event:
 A GUI application program contains several graphical components the user controls
the application by interacting with the graphical components doing things such as:
 Clicking on a button to choose a program option.
 Making a choice from a menu.
 Entering text in a text field.
 Dragging a scroll bar.
 An action such as clicking on a button is called as event.

Event Handling:
 When you perform an action on a graphical component you generate an event. In
event-driven programming the program responds to these events. The order of events
is determined by the user, not the program.
 This is different from programs where user interaction is done through the console.
In these programs, prompts or written to the console, and the user responds to the
prompts. The order of the Proms is determined by the program.
 An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard
or page scrolling, etc.

Responding on Events:
 A user interacts with a GUI application by causing events. Each time the user interacts
with a component, an event is sent to the application.
 Different events are sent to different parts of the application and application usually
ignores events that are not relevant to its purpose.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 120 of 215
Object Oriented Concepts using Java
Event types: where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2: that For ActionEvent we use addActionListener() to register.

Event Classes in Java


Event Class Listener Interface Description
ActionEvent ActionListener An event that indicates that a
component-defined action occurred like
a button click or selecting an item from
the menu-item list.
AdjustmentEvent AdjustmentListener The adjustment event is emitted by an
Adjustable object like Scrollbar.
ComponentEvent ComponentListener An event that indicates that a
component moved, the size changed or
changed its visibility.
ContainerEvent ContainerListener When a component is added to a
container (or) removed from it, then this
event is generated by a container object.
FocusEvent FocusListener These are focus-related events, which
include focus, focusin, focusout, and
blur.
ItemEvent ItemListener An event that indicates whether an item
was selected or not.
KeyEvent KeyListener An event that occurs due to a sequence
of keypresses on the keyboard.
MouseEvent MouseListener & The events that occur due to the user
MouseMotionListener interaction with the mouse (Pointing
Device).
MouseWheelEve MouseWheelListener An event that specifies that the mouse
nt wheel was rotated in a component.
TextEvent TextListener An event that occurs when an object’s
text changes.
WindowEvent WindowListener An event which indicates whether a
window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the registered class
to handle events. Abstract methods which need to implemented by the registered class to handle
events.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 121 of 215
Object Oriented Concepts using Java
Different interfaces consists of different methods which are specified below.

Listener Interface Methods


ActionListener  actionPerformed()
AdjustmentListener  adjustmentValueChanged()
ComponentListener  componentResized()
 componentShown()
 componentMoved()
 componentHidden()
ContainerListener  componentAdded()
 componentRemoved()
FocusListener  focusGained()
 focusLost()
ItemListener  itemStateChanged()
KeyListener  keyTyped()
 keyPressed()
 keyReleased()
MouseListener  mousePressed()
 mouseClicked()
 mouseEntered()
 mouseExited()
 mouseReleased()
MouseMotionListener  mouseMoved()
 mouseDragged()
MouseWheelListener  mouseWheelMoved()
TextListener  textChanged()
WindowListener  windowActivated()
 windowDeactivated()
 windowOpened()
 windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 122 of 215
Object Oriented Concepts using Java
Mouse and Keyboard events:
The mouse and keyboard input is handled in basically the same way as other
listeners. We select the component that we want to handle a listener and implement the
mouse or keyboard interfaces. When a mouse or keyboard event occurs, the appropriate
method is invoked in the interface.

Mouse Listeners:
To catch mouse events we import java.awt.event.MouseListener and the class we
want to handle events should implement the MouseListener interface. This interfaces
requires that we define the following methods:
 mouseClicked
 mouseEntered
 mousePressed
 mouseReleased
 mouseExited

Keyboard Listeners:
It is a similar drill for keyboard listeners. We just have to learn what interface to
implement and what methods need to be defined.

There are two kinds of events:


Typing a character and pressing/releasing a key on the keyboard.

Typing a character is a key-typed event while pressing or releasing a key is a key-pressed


or key-released event. To respond to a keyboard event, the component must have focus.

The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description


public abstract void keyPressed It is invoked when a key has been
1
(KeyEvent e); pressed.
public abstract void keyReleased It is invoked when a key has been
2.
(KeyEvent e); released.
public abstract void keyTyped It is invoked when a key has been
3.
(KeyEvent e); typed.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 123 of 215
Object Oriented Concepts using Java
GUI Basics:
GUI Programming:
 Graphical User Interface (GUI) programming.
 User interact with modern application programs using graphical components such
as:
 windows,
 buttons,
 textboxes menus and other several components.
 Graphical user interface GUI is implemented by using the classes from the standard
javax.swing and java.awt packages.
 There are 2 set of GUI components in Java:
 Components from abstract windowing toolkit.
 Components from swing.

Swing and AWT


 Graphical user interface GUI is implemented by using the classes from a standard
javax.swing and java.awt packages.
 There are two sets of GUI components in Java:
 Components from Abstract Windowing Toolkit
 Components from Swing

Three Parts of a GUI Program


A GUI program has three parts:
1. Graphical components that make up the graphical user interface. The graphical
components of swing objects you usually extend the me to make them fit your
application.
2. Listener methods that receive the events and respond to them. Listen methods are
Java methods that you write. They respond to event by calling application methods.
3. Application methods that do useful work for the user. Application methods for Java
methods that receive data from the GUI and send data to the GUI to be displayed.

Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based


application in java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components uses the
resources of system.

The java.awt package provides classes for AWT api such as


 TextField
 Label
 TextArea
 RadioButton

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 124 of 215
Object Oriented Concepts using Java
 CheckBox
 Choice
 List etc.

Java AWT Hierarchy


 The Java AWT contains the fundamental classes used for constructing GUIs. The
abstract component class is the base class for the AWT.
 Some of the AWT classes derived from Component are Buttons, Canvas and
Container.
 The hierarchy of Java AWT classes are given below.

Component:
Component is an abstract class that contains various classes such as Button,
Label,Checkbox,TextField, Menu and etc.

Container:
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The Container class extends Frame and Panel.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 125 of 215
Object Oriented Concepts using Java
Panels:
 Panel is the simplest container class. A panel provides space in which an application
can attach any other component, including other panels. The default layout manager
for a panel is the FlowLayout layout manager.
 The Panel is the container that doesn't contain title bar and menu bars. It can have
other
 components like button, textfield etc
Frames:
 The Frame is the container that contain title bar and can have menu bars. It can have
other
 components like button, textfield etc.
 In java Frames == Windows
 What you usually call a “window” Java calls a “frame”.
 Like all software objects, a frame object holds information and methods.
 GUI application programs are usually organized one or more frames.

Java AWT Example:


To create simple awt example, you need a frame. There are two ways to create a frame
in AWT.
 By extending Frame class (inheritance)
 By creating the object of Frame class (association)

// Simple example of AWT by inheritance


import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[])
{
First f=new First();
}
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 126 of 215
Object Oriented Concepts using Java
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.

Output:

Layout Manager
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.

There are following classes that represents the layout managers:


 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout
 javax.swing.BoxLayout
 javax.swing.GroupLayout
 javax.swing.ScrollPaneLayout
 javax.swing.SpringLayout etc.

BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the default
layout of frame or window. The BorderLayout provides five constants for each region:

 public static final int NORTH


 public static final int SOUTH
 public static final int EAST
 public static final int WEST
 public static final int CENTER

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 127 of 215
Object Oriented Concepts using Java
Constructors of BorderLayout class:
 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.

Example of BorderLayout class:

import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new Border(); }
}

GridLayout:
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 128 of 215
Object Oriented Concepts using Java
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class:

import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
JFrame f;
MyGridLayout()
{
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new MyGridLayout(); }
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 129 of 215
Object Oriented Concepts using Java
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a
flow). It is the default layout of applet or panel.

Fields of FlowLayout class:


 public static final int LEFT
 public static final int RIGHT
 public static final int CENTER
 public static final int LEADING
 public static final int TRAILING

Constructors of FlowLayout class:


FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.

FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.

FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.

Example of FlowLayout class:

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
JFrame f;
MyFlowLayout()
{
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 130 of 215
Object Oriented Concepts using Java

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new MyFlowLayout(); }
}

BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally.
For this purpose, BoxLayout provides four constants.
They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class:


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class:


1. BoxLayout(Container c, int axis): creates a box layout that arranges the
components with the given axis.

Example of BoxLayout class with Y-AXIS:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 131 of 215
Object Oriented Concepts using Java
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame


{
Button buttons[];

public BoxLayoutExample1 ()
{
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}

public static void main(String args[])


{
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

Example of BoxLayout class with X-AXIS:

import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample2 extends Frame


{
Button buttons[];
public BoxLayoutExample2()
{

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 132 of 215
Object Oriented Concepts using Java
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}

setLayout (new BoxLayout(this, BoxLayout.X_AXIS));


setSize(400,400);
setVisible(true);
}

public static void main(String args[])


{ BoxLayoutExample2 b=new BoxLayoutExample2(); }
}

CardLayout class
The CardLayout class manages the components in such a manner that only one
component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class:
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly used methods of CardLayout class:


 public void next(Container parent): is used to flip to the next card of the given
container.
 public void previous(Container parent): is used to flip to the previous card of the
given container.
 public void first(Container parent): is used to flip to the first card of the given
container.
 public void last(Container parent): is used to flip to the last card of the given
container.
 public void show(Container parent, String name): is used to flip to the specified card
with the given name.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 133 of 215
Object Oriented Concepts using Java
Example of CardLayout class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutExample extends JFrame implements ActionListener


{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample()
{
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{ card.next(c); }

public static void main(String[] args)


{
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 134 of 215
Object Oriented Concepts using Java
GUI Components:
1. Button
The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
java.awt.Button class is used to create a labelled button. GUI component that
triggers a certain programmed action upon clicking it.

Syntax:
Button b=new Button(“Text");
(Or) Button b1,b2; b1=new Button(“Text”);

b.setBounds(50,100,80,30);
setBounds(int x,int y,int width,int height)
This method is used to declare location, width & height of all components of AWT.
X Y Example: setBounds(50,100,80,30); width Height

2. Check Box: The Checkbox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a Checkbox changes its state from "on" to
"off" or from "off" to "on".

Syntax:
Checkbox c1=new Checkbox(“Text”);
(or) Checkbox c1,c2; c1=new Checkbox(“Text”);

Example:

3. RadioButtons:
 The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
 It should be added in ButtonGroup to select one radio button only.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 135 of 215
Object Oriented Concepts using Java
Syntax:
Choice c=new Choice();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");

Example:

4. Labels: The Label class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. A Label object is a component for placing text in a container. A label
displays a single line of read-only text. The text can be changed by the application, but a
user cannot edit it directly. The java.awt.Label class provides a descriptive text string
that is visible on GUI. An AWT Label object is a component for placing text in a container.

Syntax:
Label l1=new Label(“First Label”);
(or) Label l1,l2; l1=new Label(“Text”);

Example:

5. Text Fields: The object of a TextField class is a text component that allows a user to enter
a single line text and edit it. It inherits TextComponent class, which further inherits
Component class. A java.awt. TextField class creates a single-line text box for users to
enter texts.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 136 of 215
Object Oriented Concepts using Java
Syntax:
TextField t1=new TextField(“Text”);
(or) TextField t1,t2; t1=new TextField(“Text”);

Example:

6. Text Areas: The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
Syntax:
TextArea t1=new TextArea(“Text”);
(or) TextArea t1,t2; t1=new TextArea(“Text”);

Example:

7. Combo Boxes: A combo box is a combination of a text field and a drop-down list from
which the user can choose a value.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 137 of 215
Object Oriented Concepts using Java
Example:

8. Lists: List is a component that displays a set of Objects and allows the user to select one
or more items.
Syntax:
List ls=new List(Size);
ls.add("Item 1");
ls.add("Item 2");
ls.add("Item 3");

Example:

9. Scroll Bars: The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and columns.
Example:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 138 of 215
Object Oriented Concepts using Java
10. Sliders: The Java JSlider class is used to create the slider. By using JSlider, a user can
select a value from a specific range.
Example:

11. Window: A Window object is a top-level window with no borders and no menubar. The
default layout for a window is BorderLayout . A window must have either a frame, dialog,
or another window defined as its owner when it's constructed.
Example:

12. Menus: The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass. The object of
Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
Example:

13. Dialog Box: Dialog boxes are graphical components that are usually used to display
errors or give some other information to the user.
Example:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 139 of 215
Object Oriented Concepts using Java
Applet:
 Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side. Applet is a special
type of Java program that is used in web applications.
 Applets are embedded within a HyperText Markup Language (HTML) document.
 Applets provide a way to give life to a web page.
 Applets can be used to handle client-side validations.
 Browsers are required for their execution.
 Applets allow event-driven programming.

Working of Java Applet


 Java applets like Java programs consist of one or more class definitions.
 Once compiled, these classes are stored as files with a .class extension and
they consist of Java bytecode.
 Java bytecode is created by a Java-compatible compiler.
 Unlike Java applications, applets are executed within a Java-enabled web
browser such as Internet Explorer or tools like appletviewer.
 Applets are embedded within an HTML document via the APPLET tag that
references the Java applet's compiled .class file.

Types of Applets:
Web pages can contain two types of applets which are named after the
location at which they are stored.
1. Local Applet
2. Remote Applet APPLET

LOCAL REMOTE

Local Applets:
A local applet is the one that is stored on our own computer system.
When the Web-page has to find a local applet, it doesn't need to retrieve
information from the Internet.
A local applet is specified by a path name and a file name as shown below in which the
codebase attribute specifies a path name, whereas the code attribute specifies the name of
the byte-code file that contains the applet's code.

<applet codebase="MyAppPath" code="MyApp.class" width=200 height=200> </applet>

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 140 of 215
Object Oriented Concepts using Java

Remote Applets:
A remote applet is the one that is located on a remote computer system.
This computer system may be located in the building next door or it may
be on the other side of the world.
No matter where the remote applet is located, it's downloaded onto
our computer via the Internet.
The browser must be connected to the Internet at the time it needs
to display the remote applet.
To reference a remote applet in Web page, we must know the applet's URL (where it's
located on the Web) and any attributes and parameters that we need to supply.

 A local applet is specified by a URL and


<applet codebase="http://www.shreemdehacollege.com" a file name as shown
code="MyApp.class" width=200 height=200>
</applet> below.

Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms, including Linux, Windows,
Mac OS etc.
Drawback of Applet
 Plugin is required at client browser to execute applet.

Hierarchy of Applet

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 141 of 215
Object Oriented Concepts using Java
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container, which is the subclass of Component.

Lifecycle of Java Applet


Applet runs in the browser and its lifecycle-methods are called by JVM at its
birth, its death and when it is running or idle.
When an applet is made to work, it undergoes a series of changes as discussed below.
Every Applet can be said to be in any of the following states
1. New Born state
2. Running state
3. Idle state
4. Dead or Destroyed state

The following figure represents the life cycle of the Applet

New Born State


An applet enters into initialization state when the
applet is first loaded into the browser by calling the
init() method.
The init() method is called only one time in the life cycle on an applet.
The init() method retrieves the parameters through the PARAM tag of html file.
After the initialization of the init() method user can interact with the Applet.
We can override this method.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 142 of 215
Object Oriented Concepts using Java
Syntax:

public void init()


{
Statements
}

Running State:
After initialization, this state will automatically occur by invoking the start
method of applet.
The running state can be achieved from idle state when the applet is reloaded.
This method may be called multiple times when the Applet needs to be started
or restarted.
If the user leaves the applet and returns back, the applet may restart its running.
We can override this method.
Syntax:
public void start()
{
Statements
}

Idle State:
The idle state will make the execution of the applet to be halted temporarily.
Applet moves to this state when the currently executed applet is
minimized or when the user switches over to another page. At this point
the stop method is invoked.
From the idle state the applet can move to the running state.
The stop() method can be called multiple times in the life cycle of applet.
We can override this method.
Syntax:

public void stop()


{
Statements
}

Dead State:
When the applet programs terminate, the destroy function is invoked
which brings anapplet to its dead state.
The destroy() method is called only one time in the life cycle of Applet like init()
method.
In this state, the applet is removed from memory.
We can override this to cleanup resources.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 143 of 215
Object Oriented Concepts using Java
Syntax:
public void destroy()
{
Statements
}

Display State:
The applet is said to be in display state when the paint or update method is called.
This method can be used when we want to display output in the screen.
This method can be called any number of times.
Overriding paint() method is a must when we want to draw something
on the applet window.
paint() method takes Graphics object as argument
paint() method is automatically called each time the applet window is
redrawn i.e. when it is maximized from minimized state or resized or
when other windows uncover overlapped portions.
It can also be invoked by calling “repaint()” method.
Syntax:
public void paint(Graphics g)
{
Statements
}

Steps to Create and Execute Applet:


An applet is a Java program that runs in a Java-compatible browser such
as Internet explorer or Google Chrome or Mozilla Firefox
This feature allows users to display graphics and to run programs over the
Internet.
An applet allows web documents to be both animated and interactive.

Step 1: Import applet package and awt package:


To create an applet, our program must import the Applet class.
This class is found in the java.applet package.
The Applet class contains code that works with a browser to create a display
area.
We also need to import the java.awt package.
"awt” stands for “Abstract Window Toolkit”.
The java.awt package includes classes like Graphics.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 144 of 215
Object Oriented Concepts using Java
Step 2: Extend the Applet class:
Then, a class must be defined that inherits from the class ‘Applet’.
It contains the methods to paint the screen.
The inherited class must be declared public.

Step 3: Override the paint method to draw text or graphics:


The paint method needs the Graphics object as its parameter.
public void paint(Graphics g) { … }
The Graphics class object holds information about painting.
We can invoke methods like drawLine(), drawCircle() and etc using this object.

Syntax: The program looks something like this.


// 8. Create a simple applet which reveals the personal information of yours.

import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("Name : Vindhya Rani",150,150);
g.drawString("Age : 20",200,200);
g.drawString("Course : BCA",250,250);
g.drawString("Percentage : 85",300,300);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
********************OUTPUT********************

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 145 of 215
Object Oriented Concepts using Java
Step 4: Compiling the Program:
After writing the program, we compile it using the command "javac
MyApplet.java".
This command will compile our code so that we now have MyApplet.class file.
Step 5: Adding applet to HTML document:
To run the applet we need to create the HTML document.
The BODY section of the HTML document allows APPLET tag.
The HTML file looks something like this:
<HTML>
<BODY>
<APPLET codebase="MyAppPath" code="MyApp.class" width=200
height=200>
</APPLET>
</BODY>
</HTML>
Step 6: Running an applet:
The applet can be run in two ways
1. Using appletviewer: To run the appletviewer, type appletviewer filename.html
2. Using web browser: Open the web browser, type in the full address of html file

Graphics class methods:


The Graphics class several built-in methods to draw text and graphics on applets.
The Graphics class is found in java.awt package.
The paint() method takes Graphics class object as argument.
It plays two different, but related, roles.
First, it is the graphics context. The graphics context is information that will
affect drawing operations.
This includes the background and foreground colors, the font, and the
location and dimensions of the clipping rectangle (the region of a component
on which graphics can be drawn).
Second, the Graphics class provides methods for drawing simple geometric
shapes, text, and images to the graphics destination. It supports coordinate
system.

Following are some of the important methods found in Graphics class.


METHODS DESCRIPTION
drawText(String s, int x, int y) Prints the string ‘s’ at (x,y).
Set the current pen color to draw line, circle
setColor(Color c)
and etc.
getColor() Returns the current Color
drawLine(int x1, int y1, int x2, int Draws a line between the points (x1,y1) and
y2) (x2,y2)
drawRect (int x, int y, int width, int Draws (fills) a rectangle, (x,y) are the

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 146 of 215
Object Oriented Concepts using Java
height), coordinates of the top left corner, the bottom
right corner will be at (x+width,y+height)
fillRect (int x, int y, int width, int
height)
drawOval (int x, int y, int width,
int height), fillOval (intx, int y, int
Draws (fills) an oval bounded by the
width, int height) rectangle specified by these parameters.
Draws (fills) a rectangle with shaded sides
draw3DRect(), fill3DRect()
that provide a 3-D appearance.
drawRoundRect(), fillRoundRect() Draws (fills) a rectangle with rounded corners.
An arc is formed by drawing an oval
drawArc() between a start angle and a finish angle.

Draws lines connecting the points given by


the x and y arrays. Connects the last point to
drawPolygon (int[] x, int[] y, int n)
the first if they are not already the same point.
setFont(Font f) Sets the font

// 4. Program to draw several shapes in the created window.


import java.awt.*; // Importing awt package
import java.applet.*; // Importing applet package

public class Shapes extends Applet


{
public void paint(Graphics g)
{
g.setFont(new Font("Cambria", Font.BOLD,15));
g.drawString("Different Shapes", 15, 15);
g.drawLine(10,20,50,60);
g.drawRect(10,70,40,40);
g.setColor(Color.RED);
g.fillOval(60,20,30,90);
g.fillArc(60,135,80,40,180,180);
g.fillRoundRect(20,120,60,30,5,5);
}
}
/* <applet code="Shapes" width=200 height=200>
</applet>
*/

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 147 of 215
Object Oriented Concepts using Java
********************OUTPUT********************

Introduction to Swing
Swing:
 It is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
 Unlike AWT, Java Swing provides platform-independent and lightweight
components.
 The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.
4) AWT provides less Swing provides more powerful
components than Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5) AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as
an interface between model and
view.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 148 of 215
Object Oriented Concepts using Java
One mark questions
1. What event?
2. Expand GUI & API
3. What is event handling?
4. Mention types of events in java.
5. Which packages are required for GUI programming in java?
6. Write any two mouse events.
7. Write any two keyboard events.
8. What is frame
9. Define window
10. Expand AWT
11. Difference between textfield and textarea
12. Define list
13. What is label? Write syntax to create label in a frame
14. What is container?
15. What is layout manager? Mention types of layout manager
16. What is swing?
17. what is button?
18. What is menu? When we use it
19. What is applet?
20. Mention types of applets.
21. Write advantages of applets.
22. What is the use of init() and paint() method in applets
23. Which class is required to import to draw different shapes in applet.
24. What is the use of drawString() method?
25. Mention 2 methods of executing applet programs in java.
26. Write any 2 graphical methods of applet.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 149 of 215
Object Oriented Concepts using Java
Five mark questions
1. What is event? Explain different types of event in java?
2. Write difference between AWT & Swings
3. Write advantages of packages in java?
4. Why do we need GUI programming? Justify
5. Explain any 2 different layout manager?
6. Explain any two GUI components in java
7. Write a short note on AWT package
8. Mention methods of creating frame in java?
9. Explain different types of applets in java?
10. Write a short note on swings

Ten mark questions


1. Explain life cycle of an applet with a neat diagram
2. Write a program to draw several shapes in the created window
3. Explain different events in java with example
4. Explain any 5 GUI components in Java
5. Explain different types of layout managers

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 150 of 215
Object Oriented Concepts using Java

UNIT - 6
MULTITHREADING IN JAVA

Multithreaded Programming
 In modern operating systems such as Windows XP we can execute several programs
simultaneously
 This ability is known as multitasking
 In system’s terminology it is called multithreading
 A thread is a part of any task
 When there are many parts are available of a work then it will called as multithreads
 In multithreading a task is divided in to different parts
 Each part is working in parallel with others & their own work
 A thread has a single flow of control
 Thread has a beginning, a body, and an end
 Every program in java will have at least one thread
 Java also supports the multithreading concept
 Java enables us to use multiple flows of control in developing programs
 Each flow of control may thought of as a separate tiny program known as thread that
runs parallel to others
 A program that contains multiple flows of control is known as multithreaded
program
 Threads in java are subprograms of a main application program & share the same
memory space
 These are known as “lightweight threads”
 All threads are running on a single processor, the flow of execution is shared between
the threads

Advantages of Java Multithreading


 It does not block the user because threads are independent and you can perform
multiple operations at same time.
 You can perform many operations together so it saves time.
 Threads are independent so it does not affect other threads if exception occurs in a
single thread

Creating Threads
 Creating the threads in java is simple
 Threads are implemented in the form of objects that contain a method called run()
 The run() method is the heart & soul of any thread
 By using this method thread’s behaviour can be implemented & it’s make entire body
of a thread
The run() would appear as follows:

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 151 of 215
Object Oriented Concepts using Java
public void run( )
{
………………..
……………….. (statements for implementing thread)
………………..
}

 The run() method should be invoked by an object of the concerned thread

A new thread can be created in two ways:


1. By creating a thread class: Define a class that extends Thread class & override its
run() method
2. By converting a class to a thread: Define a class that implements Runnable interface

Extending the Thread Class


 Extending the thread involves the following steps:
1. Declaring the class
2. Implementing run method
3. Starting new thread

1. Declaring the class:


 The thread class can be extended as follows:
class MyThread extends Thread
{ ………………..
………………..
………………..
}

2. Implementing the run method


 The run() method has been inherited by the class MyThread
 In order to implement the code to be executed by the thread we have to override this
method
 This can be done by using following way:
public void run( )
{
…………….
……………. //Thread code here
}
 When we start the new thread, Java call the thread’s run() method

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 152 of 215
Object Oriented Concepts using Java
3. Starting New Thread
 To create & run an instance of our thread class, we must write the following code:
MyThread aThread = new MyThread
aThread.start( );
 The first line instantiates a new object of class MyThread
 The second line calls the start() method causing the thread to move into the runnable
state
 Then, the java runtime will schedule the thread to run by invoking its run() method
 Here the thread is said to be in the running state
 Before coming to running state the thread will always in runnable state

//Program to create thread using extending thread class


class Multi extends Thread // Extending thread class
{
public void run() // run() method declared
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(); //object initiated
t1.start(); // run() method called through start()
}
}
Output: thread is running…

Runnable interface is one more method to create the threads


 The runnable interface declares the run() method that is required for implementing
threads in our program
 To do this, the following steps need to be performed

Steps Implementing the ‘Runnable’ Interface


1. The first step is to create a class that implements the Runnable interface.
2. Now, you need to override the run method in the Runnable class.
3. Next, you need to pass the Runnable object as a parameter to the constructor of the
Thread class object while creating it. Now, this Thread object is capable of executing
our Runnable class.
4. Finally, you need to invoke the Thread object’s start method.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 153 of 215
Object Oriented Concepts using Java
//Program to implement creating threads using runnable interface
class Multi3 implements Runnable // Implementing Runnable interface
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3(); // object initiated for class
Thread t1 =new Thread(m1); // object initiated for thread
t1.start();
}
}

Output: thread is running…

Stopping and Blocking a Thread


Stopping a Thread
 A thread can be stopped while it was in its execution stage
 To do so we have to call its stop() method, like:
aThread.stop( );
 This statement causes the thread to move to the dead state
 A thread will also move to the dead state automatically when it reaches the end of its
method

Blocking a Thread
 A thread can also be temporarily suspended from entering in to the runnable by
using the either of the following methods:
 sleep( )
 suspend( )
 wait( )
 These methods cause the thread to go into the blocked state
 The thread will return to runnable state by using any one of the following methods:
When the specified time is elapsed
resume( )
notify( )

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 154 of 215
Object Oriented Concepts using Java
Life Cycle of a Thread
 A thread is also having its own life cycle
 During this, a thread can enter in many states to complete its life cycle
They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

Newborn State
 A thread is said in to newborn state when it was just created
 The thread is not yet scheduled for running
 At this state we can do only one of the following
 Scheduled it for running using start( ) method
 Kill it using stop( ) method

If scheduled, it moves to the runnable state if we attempt to use any other method at this
stage, an exception will be thrown.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 155 of 215
Object Oriented Concepts using Java
Runnable State
 The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
 In runnable state the thread is able to run
 But till it doesn't start the execution
 This state shows the status of the thread for execution

Running State
 When the thread starts the execution by using the processor this state is called
running state
 After runnable always running state will be there
 A thread runs until it over its execution or any other thread has to ask for processor
 When the thread is in its running state, we can ensure that the control is in run()
method of the thread.

Blocked State
 A thread is said to be blocked when it is prevented from entering in to the runnable
state
 This happens when the thread is suspended, sleeping or waiting for certain period
of time
 A blocked thread is considered “not runnable” but not dead & therefore fully
qualified to run again
 This state is achieved when we invoke suspend() or sleep() or wait() methods.
 This state may appears more than one times in the life cycle of a thread

Dead State
 A thread is said to be in dead state when it ends its execution
 Every thread has a life cycle
 A running thread ends its life when it has completed executing its run( ) method
 Every born thread has to be a dead state at last
 However, we can kill it by sending the stop message to it at any state thus causing a
premature death to it.
 A thread can be killed as soon it is born, or while it is running, or even when it is in
"not runnable" (blocked) condition.
 This state is achieved when we invoke stop() method or the thread completes it
execution.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 156 of 215
Object Oriented Concepts using Java
Thread Methods:
 Thread is a class found in java.lang package.
 It provides several different methods to perform thread tasks and control thread behaviors.
 The methods of Thread class with their meanings are listed below:

Thread Priority
 In Java, each thread is assigned a priority
 The priority affects the order in which it is scheduled for running
 The java scheduler will going to assign the priority to the threads if all are at same
level
 A user also assign the different priorities for threads
 Java permits us to set the priority of a thread using setPriority() method as follows:
ThreadName.setPriority(intNumber);
 The intNumber is an integer value to which the thread priority is set
 The thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
 The intNumber may assume one of these constants
 The default setting is NORM_PRIORITY
 By assigning priority to threads, we can ensure that they are given the attention they
deserve
 Priority can be set to a thread according to its post of the work

Thread Synchronization
Generally threads use their own data and methods provided inside their run()
methods.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 157 of 215
Object Oriented Concepts using Java
But if we wish to use data and methods outside the thread’s run()
method, they may compete for the same resources and may lead to
serious problems.
For example, one thread may try to read a record from a file while
another is still writing to the same file.
Depending on the situation, we may get strange results.
Java enables us to overcome this problem using a technique known as
synchronization.

In case of Java, the keyword synchronized helps to solve such problems by


keeping a watch on such locations.

For example, the method that will read information from a file and the
method that will update the same file may be declared as synchronized as shown
below:
synchronized void update( )
{
………….. // code here is synchronized
}
When the method declared as synchronized, Java creates a "monitor" and
hands it over to the thread that calls the method first time.

As long as the thread holds the monitor, no other thread can enter the
synchronized section of code i.e. other threads cannot interrupt this thread with
that object until its complete execution. It is like locking a function.

It is also possible to mark a block of code as synchronized as shown below:

synchronized (lock-object)

{
.......... // code here is synchronized
}

Whenever a thread has completed its work of using synchronized method


(or block of code), it will hand over the monitor to the next thread that is ready to
use the same resource.

DEADLOCK:
Deadlock describes a situation where two or more threads are blocked
forever, waiting for each other.
This undesirable situation may occur when two or more threads are
waiting to gain control on a resource.
Due to some reasons, the condition on which the waiting threads rely on
to gain control does not happen. This results in a situation called as

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 158 of 215
Object Oriented Concepts using Java
deadlock.
But, java automatically recognizes this situation and terminates some
processes automatically to ensure safer execution.

For example, assume that the thread A must access Method1 before it can
release Method2, but the thread B cannot release Method1 until it gets holds of

Method2.

Exception Handling
Errors and Various Types of Errors:
Errors are the wrongs that can make a program go wrong.
In computer terminology, errors may be referred to as bugs.
It is common to make mistakes while developing as well as typing a program.
A mistake might lead to an error causing to program to produce unexpected
results.
An error may produce an incorrect output or may terminate the
execution of the program abruptly or even may cause the system to crash.
It is therefore important to detect and manage properly all the possible errors.

Types of Errors:
Errors may broadly be classified into two categories:
1. Compile-time errors
2. Run-time errors
Compile-time errors:
All syntax errors will be detected and displayed by the Java compiler and
therefore these errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file.
It is necessary to fix these errors to get it compiled.
It becomes an easy job to a programmer to correct these errors because Java
compiler tells us where the errors are.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 159 of 215
Object Oriented Concepts using Java
Most of the compile-time errors are due to typing mistakes.
Typographical errors are hard to find.
We may have to check the code word by word, or even
character by character.
The most common errors are:
 Missing semicolons
 Missing (or mismatch of) brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables Incompatible types in assignments / initialization
 Bad references to objects
 Use of = in place of = = operator

RUN-TIME ERRORS:
Sometimes, a program may compile successfully creating the .class file but
may not run properly these errors are known as Run time error.
Such programs may produce wrong results due to wrong logic or may
terminate due to errors such as stack overflow.
Most common run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclasses
 Passing a parameter that is not in a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Using a null object reference to access a method or a variable.
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
Example: The following code generates division-by-zero runtime error.
int x=5, y=0;
System.out.println(x/y);
It displays the following message and stops without executing further statements.
Java.lang.ArithmeticException: / by zero

Exception and Exception Handling:


EXCEPTION:
Exception is a condition caused by a runtime error in a program.
It is an abnormal event that arises during the execution of the program and
terminates the normal flow of the program.
Abnormality occurs when the program is running.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 160 of 215
Object Oriented Concepts using Java
For example:
 If a user enters a string where an integer is expected, an error occurs
at runtime that causes the program to be stopped intermediately.
 Java has a built-in mechanism for handling runtime errors, referred
to as exception handling.
 This is to ensure that we can write robust (error-free) programs.
Exception Handling:
Handling runtime errors is exception handling.
In java, when an abnormal condition occurs within a method then the exceptions are thrown
in form of Exception Object
The normal program control flow is stopped and an exception object is
created to handle that exceptional condition.
If the exception object is not caught and handled properly, the interpreter
will display an error message and it will terminate the program.
If we want the program to continue with the execution of the remaining
code, then we should try to catch the exception.

The Exception handling mechanism performs the following tasks:


1. Find the problem.
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect
errors and to throw exceptions and the other to catch exceptions and to take
appropriate actions.
Exception handling mechanism includes the key words: try,
catch, throw, throws and finally.

Advantages of exception handling:


It ensures safer termination of a program.
It demands proper input entry or proper handling of a program.
User has a chance to correct the accidental mistakes while running a program.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 161 of 215
Object Oriented Concepts using Java
The program becomes robust and more user-friendly.
With this mechanism, the working code and the error-handling code can be
disintegrated. It allows different handling code-blocks for different types of errors.

Types of exception
There are mainly two types of exceptions: checked and unchecked where error
is considered as unchecked exception. The sun microsystem says there are three
types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Checked Exception
The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile- time.

Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions. e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.

Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.

Syntax of Exception Handling Mechanism:


Syntax: Try-Catch-Blocks

 Java uses a keyword try to preface a block of code that is likely to cause an error
condition
 A catch block defined by the keyword catch “catches” the exception “thrown” by the
try block an handles it appropriately
 The catch block is added immediately after the try block
 Ex - ………..
..............
try
{
statement; // generates an exception
}

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 162 of 215
Object Oriented Concepts using Java
catch (Exception - type e)
{
statement; // process the exception
}

Try - Block:
“try” block contains the code in which runtime error may occur.
It throws Exception object.
A try block must be followed by at least one catch block or a finally block.
But, it can be followed by multiple catch blocks.
A try block allows another try block within.

Catch - Block:
“catch” block contains the handling code for runtime errors i.e. when run
time error occurs, instead of terminating the program, control comes to
“catch” block.
Program control enters into “catch” block only when the corresponding runtime
error occurs.
After executing the handling code the control continues with the remaining part of
the program.
Multiple “catch” blocks can be written to handle different errors. In a “catch” block the
exception type must be mentioned.

System Defined Exceptions:


All exceptions are classes. They are subclasses of either ‘Exception’ or
‘RuntimeException’ class. We can also instantiate them. Some common system-
defined exceptions are listed below.

Exception Type Cause of Exception


ArithmeticException Caused by math errors such as division by zero
ArraylndexOutOfBoundsExcep
Caused by bad array indexes
tion
Caused when a program tries to store the wrong type
ArrayStoreException of data in an array
FileNotFoundException Caused by an attempt to access a nonexistent file
Caused by general I/O failures, such as inability to
lOException read from a file
NullPointerException Caused by referencing a null object
Caused when a conversion between strings and number
NumberFormatException
fails
Caused when there's not enough memory to allocate a
OutOfMemory Exception newobject
Caused when an applet tries to perform an action not
SecurityException allowed by the browser's security setting

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 163 of 215
Object Oriented Concepts using Java
StackOverFlowExceptlon Caused when the system runs out of stack space
Caused when a program attempts to access a
StringlndexOutOfBoundsExcep
nonexistent character position in a string
tlon

/* Program to catch NegativeArraySizeException. This exception is caused when the array


is initialized to negative values.*/
public class NegativeArraySizeExceptionExample
{
public static void main(String[] args)
{
try
{
int[] array = new int[-5];
}
catch (NegativeArraySizeException nase)
{
nase.printStackTrace();
//handle the exception
}
System.out.println("Continuing execution...");
}
}

********************OUTPUT********************

Multiple catch block:


Several types of exceptions may arise when executing the program.
They can be handled by using multiple catch blocks for the same try block.
In such cases, when an exception occurs the run time system will try to
find match for the exception object with the parameters of the catch blocks
in the order of appearance.
When a match is found the corresponding catch block will be executed.
If there is no matching catch block the program will be terminated abruptly.
Multiple catch blocks are necessary because handling code is different for
different types oferrors.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 164 of 215
Object Oriented Concepts using Java
Example:
The Following program uses Multiple catch blocks and code in a catch block
will be executed only when the corresponding errors occurs. Sample output is also
shown.
class Test
{
public static void main(String as[])
{
try
{
int x=Integer.parseInt(as[0]);
int y=Integer.parseInt(as[1]);
System.out.print("Division="+ (x/y));
}
catch(ArithmeticException ae)
{
System.out.println("Denominator was zero");
}
catch(NumberFormatException ne)
{
System.out.println("Please supply numbers");
}
catch(ArrayIndexOutOfBoundsException ie)
{
System.out.println("Please supply two arguments");
}
}
}

The above program produces the following output in different runs.


c:\jdk1.5\bin>java Test 8 0
Denominator was zero

c:\jdk1.5\bin>java Test xx yy
Please supply numbers

c:\jdk1.5\bin>java Test 5
Please supply two arguments

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 165 of 215
Object Oriented Concepts using Java
Using finally statement:
The finally block is always executed, regardless of whether or not an exception is
thrown.
It is recommended for actions like closing file streams and releasing system
resources.
Writing the finally block for try-block is optional unless there is no catch-block.
If no exception occurs during the running of the try-block, all the catch-
blocks are skipped, and finally-block will be executed after the try-block.
The finally block may be added after the catch block, or after the last catch
block.

try
{
Statements that may generate the exception
}

finally
{
Statements to be executed before exiting exception handler
}

try
{
Statements that may generate the exception
}
catch(Exception-Type1 a)
{
Statements to process the exception ‘a’
}
…. // other catch blocks
….

finally
{
Statements to be executed before exiting exception
handler
}
Handles the exception and moves to finally block

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 166 of 215
Object Oriented Concepts using Java
/*Program to handle NullPointerException and use the “finally” method to display a
message to the user.*/

import java.io.*;
class Exceptionfinally
{
public static void main (String args[])
{
String ptr = null;
try
{
if (ptr.equals("gfg"))
System.out.println("Same");
else
System.out.println("Not Same");
}

catch(NullPointerException e)
{
System.out.println("Null Pointer Exception Caught");
}

finally
{
System.out.println("finally block is always executed");
}
}
}
********************OUTPUT********************

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 167 of 215
Object Oriented Concepts using Java
Difference between final, finally and finalize:
There are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

Collections in Java
1. Java Collection Framework
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework


The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 168 of 215
Object Oriented Concepts using Java
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean It returns true if the iterator has more elements otherwise
hasNext() it returns false.

2 public Object next() It returns the element and moves the cursor pointer to the
next element.

3 public void remove() It removes the last elements returned by the iterator. It is
less used.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 169 of 215
Object Oriented Concepts using Java
Introduction Java Beans
Reusability is the main concept in any programming language. A JavaBean is a software
component that has been designed to be reusable in a variety of environments.

What is JavaBeans?
JavaBeans is a portable, platform-independent model written in Java Programming Language. Its
components are referred to as beans.

In simple terms, JavaBeans are classes which encapsulate several objects into a single object.
It helps in accessing these object from multiple places. JavaBeans contains several elements
like Constructors, Getter/Setter Methods and much more.

JavaBeans has several conventions that should be followed:


 Beans should have a default constructor (no arguments)
 Beans should provide getter and setter methods
o A getter method is used to read the value of a readable property
o To update the value, a setter method should be called
 Beans should implement java.io.serializable, as it allows to save, store and restore the
state of a JavaBean you are working on

JavaBean Properties
A JavaBean property can be accessed by the user of the object. The feature can be of any Java
data type, containing the classes that you define. It may be of the following mode: read, write,
read-only, or write-only. JavaBean features are accessed through two methods:

1. getEmployeeName ()
For example, if the employee name is firstName, the method name would be getFirstName()
to read that employee name. This method is known as an accessor. Properties of getter
methods are as follows:
1. Must be public in nature
2. Return-type should not be void
3. The getter method should be prefixed with the word get
4. It should not take any argument

2.setEmployeeName ()
For example, if the employee name is firstName, the method name would be setFirstName()
to write that employee name. This method is known as a mutator. Properties of setter
methods:
1. Must be public in nature
2. Return-type should be void
3. The setter method has to be prefixed with the word set
4. It should take some argument

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 170 of 215
Object Oriented Concepts using Java
Example Program: Implementation of JavaBeans
The example program shown below demonstrates how to implement JavaBeans.
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee()
{
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}

Next program is written in order to access the JavaBean class that we created above:
public class Employee1
{
public static void main(String args[])
{
Employee s = new Employee();
s.setName("Chandler");
System.out.println(s.getName());
}
}

Output:
Chandler

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 171 of 215
Object Oriented Concepts using Java
Advantages of JavaBeans
The following list enumerates some of the benefits of JavaBeans:
Portable
JavaBeans components are built purely in Java, hence are fully portable to any platform that
supports the Java Run-Time Environment. All platform specifics, as well as support for
JavaBeans, are implemented by the Java Virtual Machine.

Compact and Easy


JavaBeans components are simple to create and easy to use. This is an important focus
sector of the JavaBeans architecture. It does not take much effort to write a simple Bean.
Also, a bean is lightweight, so, it doesn’t have to carry around a lot of inherited baggage to
support the Beans environment.

Carries the Strengths of the Java Platform


JavaBeans is pretty compatible, there isn’t any new complicated mechanism for
registering components with the run-time system.

Disadvantages of JavaBeans
1. JavaBeans are mutable, hence lack the advantages offered by immutable objects.
2. JavaBeans will be in inconsistent state partway through its construction.

Java Networking
Java Networking is a concept of connecting two or more computing devices together
so that we can share resources. Java socket programming provides facility to share data
between different computing devices.

Advantages of Java Networking


1. Sharing resources
2. Centralize software management
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes

Java Networking Terminology


The widely used Java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 172 of 215
Object Oriented Concepts using Java
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1. It is
composed of octets that range from 0 to 255. It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.

3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.

4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable
but slow. The example of connection-oriented protocol is TCP. But, in connection-less
protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.

6) Socket
A socket is an endpoint between two-way communications.
java.net package
The java.net package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking
identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces
i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to
the resource pointed by URLs.

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 173 of 215
Object Oriented Concepts using Java
One mark questions
1. What is thread?
2. What is multitasking?
3. How to achieve multitasking in java?
4. What are the advantages of multithreading
5. Which method is used to block the thread in java?
6. Write two methods to create thread in java?
7. When did thread gets running to runnable state?
8. Which methods are used to unblock the thread?
9. What is thread synchronization?
10. What is an exception?
11. How many types of errors are their name them?
12. Write few compile time errors.
13. Mention few run time errors.
14. Mention types of exceptions in java.
15. Write any two checked and unchecked exceptions in java
16. What do you mean by NullPointer Exception?
17. Why do we use finally method?
18. What is java bean?
19. What is java networking?
20. Which is the super class for all exceptions?

Two mark questions


1. Write the advantages of multithreading?
2. Write different states of threads.
3. Explain any one method of creating thread with example?
4. Write a short note on exception handling.
5. Write advantages of exception handling.
6. Write a short note on finally method.
7. Write syntax of try and catch block
8. Write a short note on java beans

Ten mark questions


1. Explain with a neat diagram life cycle of a thread?
2. With an example explain exception handling
3. Explain different methods of Thread class?
4. Explain how to create thread using Runnable interface with an example
5. Write a program to implement NegativeArray Exception

Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 174 of 215

You might also like