0% found this document useful (0 votes)
4 views140 pages

2nd Bca C Java Notes

The document outlines the syllabus for the Bachelor of Computer Applications (BCA) degree program at the University of Madras, focusing on Java Programming for the second year, fourth semester. It details the learning objectives, course outcomes, and unit contents, which cover fundamental concepts of object-oriented programming, Core Java, GUI development using AWT and Swing, and exception handling. Recommended texts and reference materials are also provided to support the learning process.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views140 pages

2nd Bca C Java Notes

The document outlines the syllabus for the Bachelor of Computer Applications (BCA) degree program at the University of Madras, focusing on Java Programming for the second year, fourth semester. It details the learning objectives, course outcomes, and unit contents, which cover fundamental concepts of object-oriented programming, Core Java, GUI development using AWT and Swing, and exception handling. Recommended texts and reference materials are also provided to support the learning process.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIVERSITY OF MADRAS

BACHELOR OF COMPUTER APPLICATIONS (BCA)


DEGREE PROGRAMME
SYLLABUS WITH EFFECT FROM 2023-2024

Year: II Semester: IV
Java Programming 220C4A
Common for B.C.A. , [Link].-SA , [Link].-CSc , [Link].-CSc-wAI , [Link].-CSc-wDS
Credits 5 Lecture Hours:4 per week

Learning Objectives: (for teachers: what they have to do in the class/lab/field)


 To provide fundamental knowledge of object-oriented programming.
 To equip the student with programming knowledge in Core Java from the basics up.
 To enable the students to use AWT controls, Event Handling and Swing for GUI.
Course Outcomes: (for students: To know what they are going to learn)
CO1: Understand the basic Object-oriented concepts. Implement the basic constructs of
Core Java
CO2: Implement inheritance, packages, interfaces and exception handling of Core Java.
CO3: Implement multi-threading and I/O Streams of Core Java
CO4: Implement AWT and Event handling.
CO5: Use Swing to create GUI.

Units Contents
I Introduction: Review of Object-Oriented concepts - Java buzzwords (Platform
independence, Portability, Threads)- JVM architecture –Java Program structure - –
Java main method - Java Console output([Link]) - simple java program - Data
types - Variables - type conversion and casting- Java Console input: Buffered input -
operators - control statements - Static Data - Static Method - String and String Buffer
Classes
II Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic
concepts - Types of inheritance - Member access rules - Usage of this and Super key
word - Method Overloading - Method overriding - Abstract classes - Dynamic method
dispatch - Usage of final keyword -Packages: Definition - Access Protection -
Importing Packages - Interfaces: Definition – Implementation – Extending Interfaces

III Exception Handling: try – catch - throw - throws –- finally – Built-in exceptions -
Creating own Exception classes - garbage collection, finalise -Multithreaded
Programming: Thread Class - Runnable interface – Synchronization – Using
synchronized methods – Using synchronized statement - Interthread Communication –
Deadlock.

IV The AWT class hierarchy - Swing: Introduction to Swing - Hierarchy of swing


components. Containers - Top level containers - JFrame - JWindow - JDialog - JPanel
- JButton - JToggleButton - JCheckBox - JRadioButton - JLabel,JTextField -
JTextArea - JList - JComboBox – JscrollPane - Event Handling: Events - Event
sources - Event Listeners - Event Delegation Model (EDM) - Handling Mouse and
Keyboard Events

V Adapter classes - Inner classes -Java Util Package / Collections Framework:Collection


& Iterator Interface- Enumeration- List and ArrayList- Vector- Comparator
UNIVERSITY OF MADRAS
BACHELOR OF COMPUTER APPLICATIONS (BCA)
DEGREE PROGRAMME
SYLLABUS WITH EFFECT FROM 2023-2024

Learning Resources:
Recommended Texts
Herbert Schildt, The Complete Reference, Tata McGraw Hill, New Delhi, 7th Edition, 2010.
Gary Cornell, Core Java 2 Volume I – Fundamentals, Addison Wesley, 1999.
Reference Books
Head First Java, O’Rielly Publications, Y. Daniel Liang, Introduction to Java Programming,
7th Edition, Pearson Education India, 2010.
Unit - I Java Programming II BCA

Unit -I

Introduction to Review of Object Oriented Concepts:

Introduction: Review of Object-Oriented concepts - Java buzzwords (Platform independence,


Portability, Threads)- JVM architecture –Java Program structure - – Java main method - Java Console
output(System. out) - simple java program - Data types - Variables - type conversion and casting- Java
Console input: Buffered input - operators - control statements - Static Data - Static Method - String and
String Buffer Classes.

 Object-Oriented Programming or Java OOPs concept refers to languages that use


objects in programming, they use objects as a primary source to implement what is
to happen in the code. Objects are seen by the viewer or user, performing tasks you
assign.
 Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism, etc.

Concepts of OOPS:

 Class
 Object
 Method and method passing
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Compile-time polymorphism
 Runtime polymorphism

Class:
 A class is a user-defined blueprint or prototype from which objects are created.

1
Unit - I Java Programming II BCA

 It represents the set of properties or methods that are common to all objects of one
type.
 Using classes, you can create multiple objects with the same behavior instead of
writing their code multiple times. Class declarations can include these components
in order:

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


2. Class name: The class name should begin with the initial letter capitalized by convention.
3. Superclass (if any): The name of the class’s parent (super class), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
4. 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.
5. Body: The class body is surrounded by braces, { }.

Object:
An object is a basic unit of Object-Oriented Programming that represents real-life entities.
A typical Java program creates many objects, which as you know, interact by invoking
methods.
The objects are what perform your code; they are the part of your code visible to the
viewer/user. An object mainly consists of:

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


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

Abstraction

 Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.
 The trivial or non-essential units are not displayed to the user. Ex: A car is viewed as a
car rather than its individual components.

Encapsulation

It is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together the code and the data it manipulates. Another way to think about
encapsulation is that it is a protective shield that prevents the data from being accessed
by the code outside this shield.
Inheritance
 It is the mechanism in Java by which one class is allowed to inherit the features (fields
and methods) of another class.
 We are achieving inheritance by using extends keyword. Inheritance is also known as
“is-a” relationship.

 Super class: The class whose features are inherited is known as superclass (also known as base
or parent class).
 Subclass: The class that inherits the other class is known as subclass (also known as derived or
extended or child class). The subclass can add its own fields and methods in addition to the
super class fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can

2
Unit - I Java Programming II BCA

derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

Polymorphism
 It refers to the ability of object-oriented programming languages to differentiate
between entities with the same name efficiently.
 This is done by Java with the help of the signature and declaration of these entities.
The ability to appear in many forms is called polymorphism.

JAVA Buzz words:


 The primary objective of Java programming language creation was to make it portable,
simple and secure programming language.
 Apart from this, there are also some excellent features which play an important role in
the popularity of this language.
 The features of Java are also known as Java buzzwords.
 A list of the most important features of the Java language is given below.

 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic

Simple
 Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.

3
Unit - I Java Programming II BCA

 There is no need to remove unreferenced objects because there is an Automatic


Garbage Collection in Java.

Object-oriented
 Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporate both data and behavior.
Backward Skip 10sPlay Video
Platform Independent

 Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language.
 There are two types of platforms software-based and hardware-based.
 Java provides a software-based platform.
 The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms.

It has two components:

 Runtime Environment
 API(Application Programming Interface)
 Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured

 Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.

Portable

 Java is portable because it facilitates you to carry the Java byte code to any platform. It
doesn't require any implementation.

4
Unit - I Java Programming II BCA

Multi-threaded

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

Architecture-neutral

 Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

High-performance

 Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
 It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.

JVM (Java Virtual Machine)

1. A specification where working of Java Virtual Machine is specified.


2. But implementation provider is independent to choose the algorithm. Its implementation
has been provided by Oracle and other companies.
3. An implementation known as JRE (Java Runtime Environment).
4. Runtime Instance Whenever you write java command on the command prompt to run the
java class, an instance of JVM is created.

The JVM performs following operation:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

5
Unit - I Java Programming II BCA

JVM Architecture

1) Class loader

Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the class loader. There are three built-in class loaders in Java.

1. Bootstrap Class Loader: This is the first class loader which is the super class of Extension
class loader.

It loads the [Link] file which contains all class files of Java Standard Edition like [Link]
package classes, [Link] package classes, [Link] package classes, [Link] package classes,
[Link] package classes etc.

2. Extension Class Loader: This is the child class loader of Bootstrap and parent class loader of
System class loader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application Class Loader: This is the child class loader of Extension class loader. It
loads the class files from class path. By default, class path is set to current directory. You can
change the class path using "-cp" or "-class path" switch. It is also known as Application class
loader.

Example:
public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=[Link];

6
Unit - I Java Programming II BCA

[Link]([Link]());
//If we print the classloader name of String, it will print null because it is an
//in-built class which is found in [Link], so it is loaded by Bootstrap classloader
[Link]([Link]());
}
}

Structure of Java Program

 Java is an object-oriented programming, platform independent, and secure programming


language that makes it popular.
 Using the Java programming language, we can develop a wide variety of applications. So,
before diving in depth, it is necessary to understand the basic structure of Java program in
detail. In this section, we have discussed the basic structure of a Java program. At the end
of this section, you will able to develop the Hello world Java program, easily.

Documentation Section

7
Unit - I Java Programming II BCA

The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's name, date
of creation, version, program name, company name, and description of the program. It improves the
readability of the program.

o Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:

/**It is an example of documentation comment*/

Package Declaration

 It must be defined before any class and interface declaration.


 It is necessary because a Java class can be placed in different packages and directories
based on the module they are used.
 For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:

//save as [Link]
package mypack;
public class Simple
{
public static void main(String args[]){
[Link]("Welcome to package");
}
}

Interface Section

 An interface is a slightly different from the class. It contains


only constants and method declarations.
 Another difference is that it cannot be instantiated. We can use interface in classes by using
the implements keyword.
 An interface can also be used with other interfaces by using the extends keyword. For
example:

Interface car
{
void start();
void stop();
}
Class Definition

 It is vital part of a Java program. Without the class, we cannot create any Java
program. A Java program may conation more than one class definition.

8
Unit - I Java Programming II BCA

 We use the class keyword to define the class. The class is a blueprint of a Java
program. It contains information about user-defined methods, variables, and
constants.

Every Java program has at least one class that contains the main () method. For example:

class Student //class definition


{
}

Class Variables and Constants

 In this section, we define variables and constants that are to be used later in the
program.
 In a Java program, the variables and constants are defined just after the class
definition.
 The variables and constants store values of the parameters. It is used during the
execution of the program

class Student //class definition


{
String sname; //variable
int id;
double percentage;
}

Java Main Method

 In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method.
 In other words, it is an entry point of the class. It must be inside the class. Inside the
main method, we create objects and call the methods. We use the following statement
to define the main () method:

public static void main(String args[])


{
}
For example:
public class Student //class definition
{
public static void main(String args[])

9
Unit - I Java Programming II BCA

{
//statements
}
}
Java Console Class

 The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
 If you read password using Console class, it will not be displayed to the user.
 The [Link] class is attached with system console internally. The Console class is
introduced since 1.5.

Java Console class declaration

Let's see the declaration for [Link] class:

1. public final class Console extends Object implements Flushable


Java Console class methods

Method Description

Reader reader() It is used to retrieve the reader object associated with the console

String readLine() It is used to read a single line of text from the console.

String readLine(String fmt, Object... It provides a formatted prompt then reads the single line of text
args) from the console.

char[] readPassword() It is used to read password that is not being displayed on the
console.

char[] readPassword(String fmt, It provides a formatted prompt then reads the password that is not
Object... args) being displayed on the console.

Console format(String fmt, Object... It is used to write a formatted string to the console output stream.
args)

Console printf(String format, It is used to write a string to the console output stream.
Object... args)

PrintWriterwriter() It is used to retrieve the PrintWriter object associated with the


console.

void flush() It is used to flushes the console.

How to get the object of Console

System class provides a static method console() that returns the singleton instance of Console class.

10
Unit - I Java Programming II BCA

1. public static Console console(){}

Let's see the code to get the instance of Console class.

1. Console c=[Link]();

Java Console Example

import [Link];
class ReadStringTest{
public static void main(String args[]){
Console c=[Link]();
[Link]("Enter your name: ");
String n=[Link]();
[Link]("Welcome "+n);
}
}

Simple Java Program:

class Simple {
public static void main(String args[]){
[Link]("Hello Java");
}
}

Data Types in Java

Data types in Java are of different sizes and values that can be stored in the variable that is made
as per convenience and circumstances to cover up all test cases.
Java has two categories in which data types are segregated.

1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

11
Unit - I Java Programming II BCA

12
Unit - I Java Programming II BCA

Primitive Data Types in Java


Primitive data are only single values and have no special capabilities. There are 8 primitive
data types. They are depicted below in tabular format below as follows:

Type Casting in Java

In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically.

The automatic conversion is done by the compiler and manual conversion performed by the
programmer.

Types of Type Casting

There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

13
Unit - I Java Programming II BCA

Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no chance
to lose data. It takes place when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

Type conversion:

Java provides various data types just like any other dynamic languages such as boolean, char, int,
unsigned int, signed int, float, double, long, etc in total providing 7 types where every datatype
acquires different space while storing in memory.

When you assign a value of one data type to another, the two types might not be compatible with each
other. If the data types are compatible, then Java will perform the conversion automatically known as
Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example,
assigning an int value to a long variable.

[Link] Input Stream class in Java

14
Unit - I Java Programming II BCA

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the
input and to support the mark and reset methods. When the BufferedInputStream is created, an
internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is
refilled as necessary from the contained input stream, many bytes at a time.
Constructor and Description
 BufferedInputStream(InputStream in) : Creates a BufferedInputStream and saves its
argument, the input stream in, for later use.
 BufferedInputStream(InputStream in, int size) : Creates a BufferedInputStream with the
specified buffer size, and saves its argument, the input stream in, for later use.
Methods:
int available() : Returns an estimate of the number of bytes that
can be read (or skipped over) from this input stream without
blocking by the next invocation of a method for this input stream.
Syntax:public int available()
throws IOException
Returns:
an estimate of the number of bytes that can be
read (or skipped over) from this input stream without blocking.
Throws:
IOException
void close() : Closes this input stream and releases any system resources associated with the
stream.
Syntax:public void close()
throws IOException
Overrides:
close in class FilterInputStream
Throws:
IOException
void mark(int readlimit) : Marks the current position in this input stream.
Syntax:public void mark(int readlimit)
Overrides:
mark in class FilterInputStream
Parameters:
readlimit - the maximum limit of bytes that can be read
before the mark position becomes invalid.
booleanmarkSupported() : Tests if this input stream supports the mark and reset methods.
Syntax:publicbooleanmarkSupported()
Overrides:
markSupported in class FilterInputStream
Returns:
a boolean indicating if this stream type supports the mark and reset methods.
int read() : Reads the next byte of data from the input stream.
Syntax:public int read()
throws IOException
Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException
int read(byte[] b, int off, int len) : Reads bytes from this byte-input stream into the specified
byte array, starting at the given offset.
Syntax:public int read(byte[] b,
int off,
int len)
throws IOException
Parameters:

15
Unit - I Java Programming II BCA

b - destination buffer.
off - offset at which to start storing bytes.
len - maximum number of bytes to read.
Returns:
the number of bytes read, or -1 if the end of the stream has been reached.
Throws:
IOException
void reset() : Repositions this stream to the position at the time the mark method was last
called on this input stream.
Syntax:public void reset()
throws IOException
Overrides:
reset in class FilterInputStream
Throws:
IOException
long skip(long n) :Skips over and discards n bytes of data from this input stream
Syntax:public long skip(long n)
throws IOException
Parameters:
n - the number of bytes to be skipped.
Returns:
the actual number of bytes skipped.
Throws:
IOException
Program:

// Java program to demonstrate working of BufferedInputStream

import [Link];

import [Link];

import [Link];

// Java program to demonstrate BufferedInputStream methods

class BufferedInputStreamDemo

public static void main(String args[]) throws IOException

// attach the file to FileInputStream

FileInputStream fin = new FileInputStream("[Link]");

16
Unit - I Java Programming II BCA

BufferedInputStream bin = new BufferedInputStream(fin);

// illustrating available method

[Link]("Number of remaining bytes:" +

[Link]());

// illustrating markSupported() and mark() method

boolean b=[Link]();

if (b)

[Link]([Link]());

// illustrating skip method

/*Original File content:

* This is my first line

* This is my second line*/

[Link](4);

[Link]("FileContents :");

// read characters from FileInputStream and

// write them

int ch;

while ((ch=[Link]()) != -1)

[Link]((char)ch);

17
Unit - I Java Programming II BCA

// illustrating reset() method

[Link]();

while ((ch=[Link]()) != -1)

[Link]((char)ch);

// close the file

[Link]();

Output:
Number of remaining bytes:47
FileContents :
is my first line
This is my second line
This is my first line
This is my second line
Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

18
Unit - I Java Programming II BCA

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift <<>>>>>

Relational comparison <><= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
[Link](x++);//10 (11)
[Link](++x);//12
[Link](x--);//12 (11)
[Link](--x);//10
}}

19
Unit - I Java Programming II BCA

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
[Link](a++ + ++a);//10+12=22
[Link](b++ + b++);//10+11=21

}}

Output:

22
21

Java Unary Operator Example: ~ and !


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
[Link](~a);//-11 (minus of total positive value which starts from 0)
[Link](~b);//9 (positive of total minus, positive starts from 0)
[Link](!c);//false (opposite of boolean value)
[Link](!d);//true
}}

Output:

-11
9
false
true

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.

Java Arithmetic Operator Example


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

20
Unit - I Java Programming II BCA

int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression


public class OperatorExample{
public static void main(String args[]){
[Link](10*10/5+3-1*4/2);
}}

Output:

21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

Java Left Shift Operator Example


public class OperatorExample{
public static void main(String args[]){
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240
}}

Output:

40
80
80
240

21
Unit - I Java Programming II BCA

Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.

Java Right Shift Operator Example


public OperatorExample{
public static void main(String args[]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}}

Output:

2
5
2

Java Shift Operator Example: >> vs >>>


public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
[Link](20>>2);
[Link](20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
[Link](-20>>2);
[Link](-20>>>2);
}}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false

Java Control Statements | Control Flow in Java

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.

22
Unit - I Java Programming II BCA

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:

Decision-making statements decide which statement to execute and when. Decision-making


statements evaluate the Boolean expression and control the program flow depending upon the result
of the condition provided.

There are two types of decision-making statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either
true or false. In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

1. if(condition) {

23
Unit - I Java Programming II BCA

2. statement 1; //executes when condition is true


3. }

Consider the following example in which we have used the if statement in the java code.

[Link]

[Link]

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Consider the following example.

[Link]

public class Student {


public static void main(String[] args) {

24
Unit - I Java Programming II BCA

int x = 10;
int y = 12;
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.

ADVERTISEMENT

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Consider the following example.

[Link]

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {

25
Unit - I Java Programming II BCA

[Link]("city is meerut");
}else if (city == "Noida") {
[Link]("city is noida");
}else if(city == "Agra") {
[Link]("city is agra");
}else {
[Link](city);
}
}
}

Output:

Delhi

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.

Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Consider the following example.

[Link]

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if([Link]("India")) {
if([Link]("Meerut")) {

26
Unit - I Java Programming II BCA

[Link]("Your city is Meerut");


}else if([Link]("Noida")) {
[Link]("Your city is Noida");
}else {
[Link]([Link](",")[0]);
}
}else {
[Link]("You are not living in India");
}
}
}

Output:

Delhi

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;

27
Unit - I Java Programming II BCA

.
.
.
case valueN:
statementN;
break;
default:
default statement;
1. }

Consider the following example to understand the flow of the switch statement.

[Link]

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
}
}
}

Output:

While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.

28
Unit - I Java Programming II BCA

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop

In Java, for loop is similar to C and C++.. It enables us to initialize the loop variable, check the
th
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.

for(initialization, condition, increment/decrement) {


//block of statements
}

The flow chart for the for-loop


loop is given below.

Consider the following example to understand the proper functioning of the for loop in java.

[Link]

public class Calculation {


public static void main(String[] args) {

29
Unit - I Java Programming II BCA

int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}

Output:

The sum of first 10 natural numbers is 55

Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.

for(data_type var : array_name/collection_name){


//statements
}

Consider the following example to understand the functioning of the for-each loop in Java.

[Link]

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
for(String name:names) {
[Link](name);
}
}
}

Output:

Printing the content of the array names:

Java
C
C++
Python

30
Unit - I Java Programming II BCA

JavaScript

Java while loop

The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in while
loop.

It is also known as the entry-controlled


controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.

The syntax of the while loop is given below.

while(condition){
//looping statements
}

The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java

public class Calculation {

31
Unit - I Java Programming II BCA

public static void main(String[] args) {


// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
while(i<=10) {
[Link](i);
i = i + 2;
}
}
}

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.

ADVERTISEMENT
1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.

32
Unit - I Java Programming II BCA

Consider the following example to understand the functioning of the do-while


while loop in Java.

[Link]

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}
}

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.

33
Unit - I Java Programming II BCA

ADVERTISEMENT

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks only
the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

[Link]

public class BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

[Link]

public class Calculation {

34
Unit - I Java Programming II BCA

public static void main(String[] args) {


// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
[Link](k);
if(k==5) {
break a;
}
}
}

}
}

Output:

0
1
2
3
4
5

Java continue statement

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in Java.

public class ContinueExample {

public static void main(String[] args) {

35
Unit - I Java Programming II BCA

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

if(j == 4) {
continue;
}
[Link](j);
}
}
}

Output:

0
1
2
3
5
1
2
3
5
2
3
5
Java static keyword

The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.

The static can be:

1. Variable (also known as a class variable)


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

36
Unit - I Java Programming II BCA

1) Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}

Example of static variable


//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){[Link](rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code

37
Unit - I Java Programming II BCA

//[Link]="BBDIT";
[Link]();
[Link]();
}
}

Output:

111 Karan ITS


222 Aryan ITS

Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each
object will have the value 1 in the count variable.

//Java Program to demonstrate the use of an instance variable


//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
[Link](count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:

1
1
1

38
Unit - I Java Programming II BCA

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}
public static void main(String args[]){
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}

Output:

1
2
3

2) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;

39
Unit - I Java Programming II BCA

static String college = "ITS";


//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){[Link](rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}
}

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){

40
Unit - I Java Programming II BCA

int result=[Link](5);
[Link](result);
}
}

Output:125

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.

class A{
int a=40;//non static

public static void main(String args[]){


[Link](a);
}
}
Output:Compile Time Error

Java static block

o Is used to initialize the static data member.


o It is executed before the main method at the time of classloading.

Example of static block


class A2{
static{[Link]("static block is invoked");}
public static void main(String args[]){
[Link]("Hello main");
}
}

Output:static block is invoked


Hello main

class A3{

41
Unit - I Java Programming II BCA

static{
[Link]("static block is invoked");
[Link](0);
}
}

Output:

static block is invoked

Since JDK 1.7 and above, output would be:

Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend [Link]

Java String Buffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in
Java is the same as String class except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class


Modifier and Method Description
Type

public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.

public insert(int offset, String s) It is used to insert the specified string with this string at
synchronized the specified position. The insert() method is overloaded
StringBuffer like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int startIndex, It is used to replace the string from specified startIndex
synchronized int endIndex, String str) and endIndex.
StringBuffer

public delete(int startIndex, int It is used to delete the string from specified startIndex

42
Unit - I Java Programming II BCA

synchronized endIndex) and endIndex.


StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total
number of characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int beginIndex, It is used to return the substring from the specified
int endIndex) beginIndex and endIndex.

(Unit – I Completed)

43
Unit - II Java Programming II BCA

UNIT 2

Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic concepts -
Types of inheritance - Member access rules - Usage of this and Super key word - Method
Overloading - Method overriding - Abstract classes - Dynamic method dispatch - Usage of
final keyword -Packages: Definition - Access Protection - Importing Packages - Interfaces:
Definition – Implementation – Extending Interfaces

Java Classes

A class in Java is a set of objects which shares common characteristics/ behavior


and common properties/ attributes.
It is a user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named Raja is an
object.

Properties of Java Classes


1. Class is not a real-world entity. It is just a template or blueprint or prototype from
which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
 Interface

Class Declaration in Java


access_modifierclass <class_name>
{
data member;
method;
constructor;
nested class;
interface;

Components of Java Classes


In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by
convention).
4. Super class (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.
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.

1
Unit - II Java Programming II BCA

6. Body: The class body is surrounded by braces, { }.


Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-
life entities.
Objects are the instances of a class that are created to use the attributes and methods of
a class.
An object consists of:
1. State: It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of
an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the class. But the values of
those attributes, i.e. the state are unique for each object.
A single class may have any number of instances.

Dog tuffy;

2
Unit - II Java Programming II BCA

Initializing a Java object


The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the class constructor.
Example:

// Class Declaration

publicclassDog {
// Instance Variables
String name;
String breed;
intage;
String color;

// Constructor Declaration of Class


publicDog(String name, String breed, intage,
String color)
{
[Link] = name;
[Link] = breed;
[Link] = age;
[Link] = color;
}

// method 1
publicString getName() { returnname; }

// method 2

3
Unit - II Java Programming II BCA

publicString getBreed() { returnbreed; }

// method 3
publicintgetAge() { returnage; }

// method 4
publicString getColor() { returncolor; }

@OverridepublicString toString()
{
return("Hi my name is "+ [Link]()
+ ".\nMy breed,age and color are "
+ [Link]() + ","+ [Link]()
+ ","+ [Link]());
}

publicstaticvoidmain(String[] args)
{
Dog tuffy
= newDog("tuffy", "papillon", 5, "white");
[Link]([Link]());
}
}

Output
Hi my name is tuffy.
My breed,age and color are papillon,5,white

Array in java:

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.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

4
Unit - II Java Programming II BCA

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];
Example of Java Array

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

Output:

10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

5
Unit - II Java Programming II BCA

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Output:33

3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){
//body of the loop
}

//Java Program to print the array elements using for-each loop


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i);
}}

Output:

6
Unit - II Java Programming II BCA

33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any array.

//Java Program to demonstrate the way of passing an array


//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];

[Link](min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}

Output:

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)

7
Unit - II Java Programming II BCA

dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Constructor

In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.

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

Every time an object is created using the new () keyword, at least one constructor is
called.

t calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

Rules for creating Java constructor

There are two rules defined for the constructor.

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


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized.

Types of Java constructors

There are two types of constructors in Java:

8
Unit - II Java Programming II BCA

1. Default constructor (no


(no-arg constructor)
2. Parameterized constructor

Java Default Constructor

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

Syntax of default constructor:


<class_name>(){}

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.

Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated
fferentiated by the compiler by the number of parameters in the list
and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){

9
Unit - II Java Programming II BCA

id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
} Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in Java

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

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of
object. an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the compiler
you don't have any constructor in a class. in any case.

The constructor name must be same as the class The method name may or may not be same
name. as the class name.

10
Unit - II Java Programming II BCA

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

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.

Java Inheritance Example

11
Unit - II Java Programming II BCA

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

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

12
Unit - II Java Programming II BCA

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

13
Unit - II Java Programming II BCA

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
1. Dog d=new Dog();
2. [Link]();
3. [Link]();
4. }}

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}

14
Unit - II Java Programming II BCA

class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}

Output:

15
Unit - II Java Programming II BCA

meowing...

eating...

16
Unit - II Java Programming II BCA

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

17
Unit - II Java Programming II BCA

Method Overloading in Java

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

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

Advantage of method overloading

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 number of arguments


2. By changing the data type

Method Overloading: changing no. of arguments

We have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}} Output:
22
33

18
Unit - II Java Programming II BCA

Method Overloading: changing data type of arguments


we have created two methods that differs in data type. The first add method receives two
integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}

Output:

22
24.9
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)

class Vehicle{
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();

19
Unit - II Java Programming II BCA

//calling the method with child class instance


[Link]();
}
}
Output:

Vehicle is running

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java.

It can have abstract and non-abstract methods (method with the body).

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

Dynamic Method Dispatch Java

Java, as an object-oriented programming language, supports one of the key features of OOP -
polymorphism. It allows objects to take on multiple forms, and one way it achieves this is
through a mechanism called dynamic method dispatch. The feature plays a crucial role in
achieving flexibility and extensibility in Java programs.

Dynamic Method Dispatch

Dynamic method dispatch or run-time polymorphism is the mechanism through which the
correct version of an overridden method is called at runtime. When a subclass overrides a
method from its super class, the overridden method in the subclass is executed when called
on an instance of the subclass, even if the reference to the object is of the super class type.

[Link]

class Animal {
void makeSound() {
[Link]("Generic Animal Sound");
}
}

20
Unit - II Java Programming II BCA

class Dog extends Animal {


@Override
void makeSound() {
[Link]("Bark");
}
}
class Cat extends Animal {
@Override
void makeSound() {
[Link]("Meow");
}
}
public class DynamicMethod {
public static void main(String[] args) {
Animal[] animals = {new Dog(), new Cat()};
for (Animal animal : animals) {
[Link]();
}
}
}

Output:

Bark
Meow
Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will
be constant).

21
Unit - II Java Programming II BCA

2) Java final method

If you make any method as final, you cannot override it.

3) Java final class

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

final class Bike{}

class Honda1 extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
[Link]();
}
}
Output:Compile Time Error

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

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

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

22
Unit - II Java Programming II BCA

Simple example of java package

The package keyword is used to create a package in java.

//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . [Link]

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. [Link] etc to run the class.

23
Unit - II Java Programming II BCA

To Compile: javac -d . [Link]

To Run: java [Link]

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e.

it represents destination. The represents the current folder.

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import [Link];
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*

//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();

24
Unit - II Java Programming II BCA

}
}
Output:Hello

2) Using [Link]

If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]

//save by [Link]

package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello

25
Unit - II Java Programming II BCA

Interface in Java

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.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

26
Unit - II Java Programming II BCA

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple inheritance.

interface Printable{
void print();
}
interface Showable{
void show();

27
Unit - II Java Programming II BCA

}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
[Link]();
[Link]();
}
}
Output:Hello
Welcome

(Unit – II completed)

28
Unit - III[Type here] Java Programming II BCA

Unit –III

Exception Handling: try – catch - throw - throws –- finally – Built-in exceptions - Creating
own Exception classes - garbage collection, finalise -Multithreaded Programming: Thread Class
- Runnable interface – Synchronization – Using synchronized methods – Using synchronized
statement - Interthread Communication – Deadlock.

Exception Handling:

 The Exception Handling in Java is powerful mechanisms to handle the runtime


errors so that the normal flow of the application can be maintained.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as

1. ClassNotFoundException,
2. IOException,
3. SQLException,
4. RemoteException, etc.

Advantage of Exception Handling

 Maintain the normal flow of the application.

An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked.

An error is considered as the unchecked exception.

1
Unit - III[Type here] Java Programming II BCA

 Checked Exception
 Unchecked Exception
 Error

Java Exception Keywords

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.

Java Exception Handling Example

[Link]

public class JavaExceptionExample{

2
Unit - III[Type here] Java Programming II BCA

public static void main(String args[]){


try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]:/ by zero
rest of the code...

Built in Exceptions:

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in exceptions
in Java.

Arithmetic exception: It is thrown when an exceptional condition has occurred in an arithmetic


operation.

// Java program to demonstrate


// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index is Out Of Bounds");
}
}
}

Output:

3
Unit - III[Type here] Java Programming II BCA

Can't divide a number by 0

ArrayIndexOutOfBoundsException :
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
Java program to demonstrate.

FileNotFoundException
import [Link];
import [Link];
import [Link];
class File_notFound_Demo {
public static void main(String args[])
{
try {
// Following file does not exist
File file = new File("E:// [Link]");
FileReaderfr = new FileReader(file);
}
catch (FileNotFoundException e) {
[Link]("File does not exist");
}
}
}

Output:
Array Index is Out Of Bounds

ClassNotFoundException : This Exception is raised when we try to access a class whose


definition is not found.

// Java program to illustrate the


// concept of ClassNotFoundException
class Bishal {

} class Geeks {

} class MyClass {
public static void main(String[] args)
{
Object o = [Link](args[0]).newInstance();
[Link]("Class created for" + [Link]().getName());
}
}

Output:
ClassNotFoundException
FileNotFoundException : This Exception is raised when a file is not accessible or does not
open.

4
Unit - III[Type here] Java Programming II BCA

// Java program to demonstrate


// FileNotFoundException
import [Link];
import [Link];
import [Link];
class File_notFound_Demo {

public static void main(String args[])


{
try {

// Following file does not exist


File file = new File("E:// [Link]");

FileReaderfr = new FileReader(file);


}
catch (FileNotFoundException e) {
[Link]("File does not exist");
}
}
}

Output:
File does not exist
IOException : It is thrown when an input-output operation failed or interrupted
JAVA

Output:
error: unreported exception IOException; must be caught or declared to be thrown
InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
error: unreported exception InterruptedException; must be caught or declared to be thrown
NoSuchMethodException : t is thrown when accessing a method which is not found.
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
NullPointerException : This exception is raised when referring to the members of a null
object. Null represents nothing .
JAVA

// Java program to demonstrate


// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = [Link](24); // accessing 25th element

5
Unit - III[Type here] Java Programming II BCA

[Link](c);
}
catch (StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
}
}

Output:
NullPointerException..
NumberFormatException : This exception is raised when a method could not convert a string
into a numeric format.

StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an


index is either negative than the size of the string.
JAVA

// Java Program to illustrate


// StackOverflowError
class Test {
public static void main(String[] args)
{
m1();
}
public static void m1()
{
m2();
}
public static void m2()
{
m1();
}
}

Output:
StringIndexOutOfBoundsException

CREATING OUR OWN EXCEPTION:

 An exception is an issue (run time error) that occurred during the execution of a
program.
 When an exception occurred the program gets terminated abruptly and, the code
past the line that generated the exception never gets executed.

In order to create a custom exception, we need to extend the Exception class that belongs
to [Link] package.

6
Unit - III[Type here] Java Programming II BCA

// A Class that represents use-defined exception

class MyException extends Exception {

public MyException(String s)

// Call constructor of parent Exception

super(s);

// A Class that uses above MyException

public class Main {

// Driver Program

public static void main(String args[])

try {

// Throw an object of user defined exception

throw new MyException("GeeksGeeks");

catch (MyException ex) {

[Link]("Caught");

// Print the message from MyException object

7
Unit - III[Type here] Java Programming II BCA

[Link]([Link]());

Output
Caught
GeeksGeeks
Java Garbage Collection
In java, garbage means unreferenced objects.

 Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


 It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

1)By nulling a reference:


Employee e=new Employee();
e=null;

2) By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:

8
Unit - III[Type here] Java Programming II BCA

protected void finalize(){}

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.

public static void gc(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){[Link]("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
}
}
Output:
object is garbage collected
object is garbage collected

Multithreading in Java
 Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
 Each part of such program is called a thread. So, threads are light-weight processes within
a process.
Threads can be created by using two mechanisms :
Extending the Thread class
Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the [Link] class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We create
an object of our new class and call start() method to start the execution of a thread. Start()
invokes the run() method on the Thread object.
Java

// Java code for thread creation by extending

9
Unit - III[Type here] Java Programming II BCA

// the Thread class

classMultithreadingDemo extendsThread {

publicvoidrun()

try{

// Displaying the thread that is running

[Link](

"Thread "+ [Link]().getId()

+ " is running");

catch(Exception e) {

// Throwing an exception

[Link]("Exception is caught");

// Main Class

publicclassMultithread {

publicstaticvoidmain(String[] args)

10
Unit - III[Type here] Java Programming II BCA

intn = 8; // Number of threads

for(inti = 0; i< n; i++) {

MultithreadingDemo object

= newMultithreadingDemo();

[Link]();

Output

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Thread creation by implementing the Runnable Interface


We create a new class which implements [Link] interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.

Java code for thread creation by implementing


the Runnable Interface
classMultithreadingDemo implementsRunnable {
publicvoidrun()
{

11
Unit - III[Type here] Java Programming II BCA

try{
// Displaying the thread that is running
[Link](
"Thread "+ [Link]().getId()
+ " is running");
}
catch(Exception e) {
// Throwing an exception
[Link]("Exception is caught");
}
}
}

// Main Class
classMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
Thread object
= newThread(newMultithreadingDemo());
[Link]();
}
}
}

Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
 If we extend the Thread class, our class cannot extend any other class because Java
doesn’t support multiple inheritance.
 But, if we implement the Runnable interface, our class can still extend other base classes.
 We can achieve basic functionality of a thread by extending Thread class because it
provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.
 Using runnable will give you an object that can be shared amongst multiple threads.

12
Unit - III[Type here] Java Programming II BCA

Synchronization in Java
 Multi-threaded programs may often come to a situation where multiple threads try to
access the same resources and finally produce erroneous and unforeseen results.

Types of Synchronization
 There are two synchronizations in Java mentioned below:
 Process Synchronization
 Thread Synchronization
Types of Synchronization
 There are two synchronizations in Java mentioned below:
 Process Synchronization
 Thread Synchronization

Process Synchronization in Java

 Process Synchronization is a technique used to coordinate the execution of multiple


processes. It ensures that the shared resources are safe and in order.

Thread Synchronization in Java

 Thread Synchronization is used to coordinate and ordering of the execution of the


threads in a multi-threaded program. There are two types of thread synchronization are
mentioned below:
 Mutual Exclusive
 Cooperation (Inter-thread communication in Java)

Mutual Exclusive

 Mutual Exclusive helps keep threads from interfering with one another while sharing
data. There are three types of Mutual Exclusive mentioned below:
 Synchronized method.
 Synchronized block.
 Static synchronization.
Example of Synchronization

import [Link].*;
import [Link].*;

// A Class used to send a message


class Sender {
public void send(String msg)
{
[Link]("Sending\t" + msg);
try {
[Link](1000);
}
catch (Exception e) {
[Link]("Thread interrupted.");
}

13
Unit - III[Type here] Java Programming II BCA

[Link]("\n" + msg + "Sent");


}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
[Link](msg);
}
}
}

// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type


[Link]();
[Link]();

// wait for threads to end


try {
[Link]();
[Link]();
}
catch (Exception e) {
[Link]("Interrupted");
}
}
}

Output
Sending Hi

14
Unit - III[Type here] Java Programming II BCA

Hi Sent
Sending Bye

Bye Sent

Inter-thread Communication in Java

 Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.
 Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.
 It is implemented by following methods of Object class:

1. wait()
2. notify()
3. notifyAll()

4. wait() method

The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws InterruptedException It waits for the specified amount of time.

2) notify () method

The notify () method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.

Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

15
Unit - III[Type here] Java Programming II BCA

Syntax:

public final void notifyAll()

 The point to point explanation of the above diagram is as follows:


 Threads enter to acquire lock.
 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
 If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
 Now thread is available to acquire lock.

After completion of the task, thread releases the lock and exits the monitor state of the object.

Example of Inter Thread Communication in Java

[Link]

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


[Link]("going to withdraw...");

16
Unit - III[Type here] Java Programming II BCA

if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link]-=amount;
[Link]("withdraw completed...");
}

synchronized void deposit(int amount){


[Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){[Link](15000);}
}.start();
new Thread(){
public void run(){[Link](10000);}
}.start();

}}

Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

17
Unit - III[Type here] Java Programming II BCA

Deadlock in Java

 Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a


thread is waiting for an object lock, that is acquired by another thread and second thread
is waiting for an object lock that is acquired by first thread.
 Since, both threads
hreads are waiting for each other to release the lock, the condition is called
deadlock.

public class TestDeadlockExample1 {


public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
[Link]("Thread 1: locked resource 1");

try { [Link](100);} catch (Exception e) {}

synchronized (resource2) {
[Link]("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
[Link]("Thread 2: locked resource 2");

18
Unit - III[Type here] Java Programming II BCA

try { [Link](100);} catch (Exception e) {}

synchronized (resource1) {
[Link]("Thread 2: locked resource 1");
}
}
}
};

[Link]();
[Link]();
}
}

Output:

Thread 1: locked resource 1


Thread 2: locked resource 2

Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:

Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason for
a deadlock condition. It normally happens when you give locks to multiple threads.

Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to
the unnecessary threads that cause the deadlock condition.

Using Thread Join: A deadlock usually happens when one thread is waiting for the other to
finish. In this case, we can use join with a maximum time that a thread will take.

(Unit – III completed)

19
Unit - IV Java Programming II BCA
Unit – IV

The AWT class hierarchy - Swing: Introduction to Swing - Hierarchy of swing components.
Containers - Top level containers - JFrame - JWindow - JDialog - JPanel - JButton -
JToggleButton - JCheckBox - JRadioButton - JLabel,JTextField - JTextArea - JList -
JComboBox – JscrollPane - Event Handling: Events - Event sources - Event Listeners - Event
Delegation Model (EDM) - Handling Mouse and Keyboard Events

Java AWT Hierarchy

 Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
 Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
 Layout Managers: Layout Managers are responsible for arranging data in the
containers some of the layout managers are BorderLayout, FlowLayout, etc.
 Event Handling: AWT allows the user to handle the events like mouse clicks, key
presses, etc. using event listeners and adapters.
 Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert
images and write text in the components of a Java Application.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI] components as AWT and is
part of the standard Java distribution. By today’s application GUI requirements, AWT is a
limited implementation, not quite capable of providing the components required for
developing complex GUIs required in modern commercial applications. The AWT
component set has quite a few bugs and does take up a lot of system resources when
compared to equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with programmers
creating GUI’s for commercial applications.
 Swing is a Set of API (API
(API- Set of Classes and Interfaces)
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the he looks and
Functionality of GUIs’
 Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets

1
Unit - IV Java Programming II BCA
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, the Swing is built on top of the
AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent, and The Swing Components are
lightweight.
 Swing Supports a Pluggable look and feel and Swing provides more powerful
components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
 Further Swing Follows MVC.
Difference between Java Swing and Java AWT
There are certain points from which Java Swing is different than Java AWT as mentioned
below:
Java AWT Java Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.

The components of Java Swing are


Components of AWT are heavy weighted.
lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

AWT components require [Link] Swing components requires [Link]


package. package.

2
Unit - IV Java Programming II BCA

Method Description

It add a component on another


public void add(Component c)
component.

public void setSize(int width,int height)


It sets size of the component.

public void setLayout(LayoutManager It sets the layout manager for the


m) component.

It sets the visibility of the component. It


public void setVisible(boolean b)
is by default false.

Commonly Used Methods of Component Class

The methods of Component class are widely used in Java swing that are given below.

There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

1. Window: Window is a top-level container that represents a graphical window or dialog box.
2. The Window class extends the Container class, which means it can contain other components,
3. such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for
3. grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have menu bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.

3
Unit - IV Java Programming II BCA

JComponent

Component is an abstract class that programmers can use to modify

to build unique components that are suited to the particular requirements of their applications.

JComponent and other Swing components are lighter

than their AWT equivalents

Syntax of JComponent
public abstract class JComponent extends
Container implements Serializable

swing component classes:

Java Swing was introduced as part of the Java Foundation Classes (JFC) in the late 1990s,

aiming to address the limitations of the earlier Abstract Window Toolkit (AWT).

Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame

object inside the main() method.

File Name: [Link]

import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


[Link](130,100,100, 40);//x axis, y axis, width, height

[Link](b);//adding button in JFrame


10.
11. [Link](400,500);//400 width and 500 height
12. [Link](null);//using no layout managers
13. [Link](true);//making the frame visible
14. }
15. }

4
Unit - IV Java Programming II BCA

Example of Swing by Association Inside Constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File Name: [Link]

import [Link].*;
public class Demo {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
[Link](130,100,100, 40);
[Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500 height
10. [Link](null);//using no layout managers
11. [Link](true);//making the frame visible
12. }
13. public static void main(String[] args) {
14. new Demo();
15. }
16. }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets

the position of the button.

Example of Swing by Inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File Name: [Link]

5
Unit - IV Java Programming II BCA
import [Link].*;
public class DemoSwing extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
[Link](130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
10. setVisible(true);
11. }
12. public static void main(String[] args) {
13. new Simple2();
14. }}

Java swing controls

Java JLabel
The object of JLabel 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.

It inherits JComponent class.

JLabel class declaration

Let's see the declaration for [Link] class.

public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

Creates a JLabel instance with no image and with


JLabel()
an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

Creates a JLabel instance with the specified


JLabel(Icon i)
image.

Creates a JLabel instance with the specified text,


JLabel(String s, Icon i, int horizontalAlignment)
image, and horizontal alignment.

Java JLabel Example

6
Unit - IV Java Programming II BCA
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. [Link](50,100, 100,30);
12. [Link](l1); [Link](l2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. }

Java JButton
The JButton class is used to create a labeled button that has platform independent implementation.

The application result in some action when the button is pushed. It inherits AbstractButton class.

A key element of graphical user interfaces (GUIs) in Java that is used to create interactive buttons

is the JButton class. Users can click these labelled buttons to initiate particular operations within the

application. Because JButton offers a platform-independent implementation,

it can be used in a variety of settings and operating systems. It is descended from the AbstractButton class,

which offers shared functionality for all button kinds in the Swing GUI framework and Java's

Abstract Window Toolkit (AWT). Developers can improve the usability and interactivity of their

Java programmes by adding sensible user interface components to their JButton objects through

configuration.

JButton class declaration

Let's see the declaration for [Link] class.

public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description

7
Unit - IV Java Programming II BCA
JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Creates a button with both specified text and


JButton(String s, Icon i)
icon.

import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
10. [Link](true);
11. }
12. }
Output:

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.

It inherits JTextComponent class.

JTextField class declaration

Let's see the declaration for [Link] class.

8
Unit - IV Java Programming II BCA
public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

Creates a new TextField initialized with the


JTextField(String text)
specified text.

Creates a new TextField initialized with the


JTextField(String text, int columns)
specified text and columns.

Creates a new empty TextField with the specified


JTextField(int columns)
number of columns.

Java JTextField Example

import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. [Link](50,150, 200,30);
12. [Link](t1); [Link](t2);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. }
17. }
Output:

9
Unit - IV Java Programming II BCA

Java JTextArea
The object of a JTextArea class is a multi-line region that displays text. It allows the editing

of multiple-line text. It inherits the JTextComponent class. An editable and showing

multi-line text component in Java is represented by the JTextArea class, which is a component

of the [Link] package.

TextArea Class Declaration

Let's see the declaration for [Link] class.

Commonly Used Constructors

Constructor Description

JTextArea() Creates a text area that displays no text initially.

Creates a text area that displays specified text


JTextArea(String s)
initially.

Creates a text area with the specified number of


JTextArea(int row, int column)
rows and columns that displays no text initially.

Creates a text area with the specified number of


JTextArea(String s, int row, int column)
rows and columns that displays specified text.

10
Unit - IV Java Programming II BCA

Java JTextArea Example

File Name: [Link]

import [Link].*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
10. [Link](null);
11. [Link](true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. }}
Output:

Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry.

It allows the editing of a single line of text. It inherits JTextField class.

11
Unit - IV Java Programming II BCA

JPasswordField class declaration

Let's see the declaration for [Link] class.

public class JPasswordField extends JTextField

Commonly used Constructors:

Constructor Description

Constructs a new JPasswordField, with a default


JPasswordField() document, null starting text string, and 0 column
width.

Constructs a new empty JPasswordField with the


JPasswordField(int columns)
specified number of columns.

Constructs a new JPasswordField initialized with


JPasswordField(String text)
the specified text.

Construct a new JPasswordField initialized with


JPasswordField(String text, int columns)
the specified text and columns.

Java JPasswordField Example

import [Link].*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
[Link](20,100, 80,30);
[Link](100,100,100,30);
[Link](value); [Link](l1);
10. [Link](300,300);
11. [Link](null);
12. [Link](true);
13. }
14. }
Output:

12
Unit - IV Java Programming II BCA

Java JCheckBox
The JCheckBox 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 ".

It inherits JToggleButton class.

JCheckBox class declaration

Let's see the declaration for [Link] class.

public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

Creates an initially unselected check box button


JJCheckBox()
with no text, no icon.

Creates an initially unselected check box with


JChechBox(String s)
text.

Creates a check box with text and specifies


JCheckBox(String text, boolean selected)
whether or not it is initially selected.

Creates a check box where properties are taken


JCheckBox(Action a)
from the Action supplied.

13
Unit - IV Java Programming II BCA

Commonly used Methods:

Methods Description

It is used to get the AccessibleContext associated


AccessibleContextgetAccessibleContext()
with this JCheckBox.

It returns a string representation of this


protected String paramString()
JCheckBox.

Java JCheckBox Example

import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
10. [Link](checkBox1);
11. [Link](checkBox2);
12. [Link](400,400);
13. [Link](null);
14. [Link](true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}
Output:

14
Unit - IV Java Programming II BCA

Java JRadioButton
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.

JRadioButton class declaration

Let's see the declaration for [Link] class.

public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

Creates an unselected radio button with specified


JRadioButton(String s)
text.

Creates a radio button with the specified text and


JRadioButton(String s, boolean selected)
selected status.

Commonly used Methods:

15
Unit - IV Java Programming II BCA
Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b)
It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton Example

import [Link].*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
[Link](75,50,100,30);
[Link](75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. [Link](r1);[Link](r2);
12. [Link](r1);[Link](r2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }

16
Unit - IV Java Programming II BCA

Output

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by

user is shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration

Let's see the declaration for [Link] class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,


ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

Creates a JComboBox that contains the elements


JComboBox(Object[] items)
in the specified array.

Creates a JComboBox that contains the elements


JComboBox(Vector<?> items)
in the specified Vector.

Commonly used Methods:

Methods Description

17
Unit - IV Java Programming II BCA
void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox


is editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListeneri) It is used to add the ItemListener.

Java JComboBox Example

import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
10. [Link](null);
11. [Link](400,500);
12. [Link](true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }
Output:

18
Unit - IV Java Programming II BCA

Event Handling in Java

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.
The [Link] package can be used to provide various event classes.
Classification of Events
 Foreground Events
 Background Events

Types of Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to
interaction by the user on components in Graphic User Interface (GUI). Interactions
nteractions are nothing
but clicking on a button,
scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background

19
Unit - IV Java Programming II BCA
events. Examples of these events are operating system failures/interrupts,
operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation
Event model.
Delegation Event model
 It has Sources and Listeners.

Delegation Event Model

 Source: Events are generated from the source. There are various sources
 like buttons, checkboxes, list, menu
menu-item, choice, scrollbar, text components,
 windows, etc., to generate events.
 Listeners: Listeners are used for handling the events generated from the source.
Each of these listeners represents interfaces that are responsible for handling
events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()

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

An event that indicates that a


component-defined
defined
ActionEvent ActionListener action occurred like a button click
or selecting
an item from the menu-item list.

20
Unit - IV Java Programming II BCA

The adjustment event is emitted by


AdjustmentEvent AdjustmentListener
an Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size
changed or changed its visibility.

When a component is added to


a container (or) removed from it,
ContainerEvent ContainerListener
then this event is generated by a
container object.

These are focus-related events,


FocusEvent FocusListener which include focus, focusin,
focusout, and blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.

An event that occurs due to a


KeyEvent KeyListener sequence of keypresses on t
he keyboard.

The events that occur due to the


MouseEvent MouseListener&MouseMotionListener user interaction with the mouse
(Pointing Device).

An event that specifies that


MouseWheelEvent MouseWheelListener the mouse
wheel was rotated in a component.

An event that occurs when


TextEvent TextListener an object’s
text changes.

An event which indicates whether


WindowEvent WindowListener a window has changed its
status or not.

Listener Interface Methods

ActionListener  actionPerformed()

21
Unit - IV Java Programming II BCA

AdjustmentListener  adjustmentValueChanged()

 componentResized()
 componentShown()
ComponentListener
 componentMoved()
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener  itemStateChanged()

 keyTyped()
KeyListener  keyPressed()
 keyReleased()

 mousePressed()
 mouseClicked()
MouseListener  mouseEntered()
 mouseExited()
 mouseReleased()

 mouseMoved()
MouseMotionListener
 mouseDragged()

MouseWheelListener  mouseWheelMoved()

TextListener  textChanged()

 windowActivated()
 windowDeactivated()
 windowOpened()
WindowListener  windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

Flow of Event Handling


User Interaction with a component is required to generate an event.
The object of the respective event class is created automatically after event generation,
and it holds all information of the event source.
The newly created object is passed to the methods of the registered listener.
The method executes and returns the result.

22
Unit - IV Java Programming II BCA
Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
Within Class
Other Class
Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may
throw errors due to the unavailability of some packages.
Event Handling Within Class
Java

// Java program to demonstrate the

// event handling within the class

[Link].*;

[Link].*;

classGFGTop extendsFrame implementsActionListener {

TextFieldtextField;

GFGTop()

// Component Creation

textField = newTextField();

// setBounds method is used to provide

23
Unit - IV Java Programming II BCA

// position and size of the component

[Link](60, 50, 180, 25);

Button button = newButton("click Here");

[Link](100, 120, 80, 30);

// Registering component with listener

// this refers to current instance

[Link](this);

// add Components

add(textField);

add(button);

// set visibility

setVisible(true);

// implementing method of actionListener

publicvoidactionPerformed(ActionEvent e)

// Setting text to field

24
Unit - IV Java Programming II BCA

[Link]("GFG!");

publicstaticvoidmain(String[] args)

newGFGTop();

Output

After Clicking, the text fie


field
ld value is set to GFG!

// Java program to demonstrate the

// event handling by the other class

[Link].*;

[Link].*;

25
Unit - IV Java Programming II BCA

classGFG1 extendsFrame {

TextFieldtextField;

GFG2()

// Component Creation

textField = newTextField();

// setBounds method is used to provide

// position and size of component

[Link](60, 50, 180, 25);

Button button = newButton("click Here");

[Link](100, 120, 80, 30);

Other other = newOther(this);

// Registering component with listener

// Passing other class as reference

[Link](other);

26
Unit - IV Java Programming II BCA

// add Components

add(textField);

add(button);

// set visibility

setVisible(true);

publicstaticvoidmain(String[] args)

newGFG2();

Java

/// import necessary packages

[Link].*;

// implements the listener interface

27
Unit - IV Java Programming II BCA

classOther implementsActionListener
lementsActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {

[Link] = gfgObj;

publicvoidactionPerformed(ActionEvent e)

// setting text from different class

[Link]("Using Different Cl
Classes");

Output

Handling event from different class

28
Unit - IV Java Programming II BCA
Event Handling By Anonymous Class
Java

// Java program to demonstrate the

// event handling by the anonymous class

[Link].*;

[Link].*;

classGFG3 extendsFrame {

TextFieldtextField;

GFG3()

// Component Creation

textField = newTextField();

// setBounds method is used to provide

// position and size of component

[Link](60, 50, 180, 25);

Button button = newButton("click Here");

29
Unit - IV Java Programming II BCA

[Link](100, 120, 80, 30);

// Registering component with listener anonymously

[Link](newActionListener() {

publicvoidactionPerformed(ActionEvent e)

// Setting text to field

[Link]("Anonymous");

});

// add Components

add(textField);

add(button);

//make size viewable

setSize(300,300);

// set visibility

setVisible(true);

30
Unit - IV Java Programming II BCA

publicstaticvoidmain(String[] args)

newGFG3();

Output

Handling anonymously

Mouse Events
To handle mouse events, you can use
the MouseListener and MouseMotionListener interfaces. The MouseListener interface
handles events like mouse clicks, presses
presses,, releases, and when the mouse enters or exits a
component. The MouseMotionListener interface handles events when the mouse is moved or
dragged.
Example of MouseListener:
Java
import [Link];
import [Link];
import [Link];

public class MouseEventDemo extends JFrame implements MouseListener {


public MouseEventDemo() {
addMouseListener(this);
setSize(300, 200);
setVisible(true);
}

@Override
public void mouseClicked(MouseEvent
MouseEvent e) {

31
Unit - IV Java Programming II BCA
[Link]("Mouse Clicked");
}

@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}

@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}

public static void main(String[] args) {


new MouseEventDemo();
}
}
.
Keyboard Events
To handle keyboard events, you can use the KeyListener interface. This interface handles
events like key presses, key releases, and key typing.
Example of KeyListener:
Java
import [Link];
import [Link];
import [Link];

public class KeyEventDemo extends JFrame implements KeyListener {


public KeyEventDemo() {
addKeyListener(this);
setSize(300, 200);
setVisible(true);
}

32
Unit - IV Java Programming II BCA

@Override
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}

@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}

@Override
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]());
}

public static void main(String[] args) {


new KeyEventDemo();
}
}

(Unit – IV completed)

33
Unit - V Java Programming III BCA

Unit – 5

Adapter classes - Inner classes -Java Util Package / Collections Framework:Collection &
Iterator Interface- Enumeration- List and ArrayList Vector- Comparator
Adapter Classes
Adapter Classes Java provides a special feature, called an adapter class, that can simplify the

creation of event handlers in certain situations. An adapter class provides an empty implementation

of all methods in an event listener interface. Adapter classes are useful when you want to receive

and process only some of the events that are handled by a particular event listener interface. You

can define a new class to act as an event listener by extending one of the adapter classes and

implementing only those events in which you are interested

For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and

mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you were

interested in only mouse drag events, then you could simply extend MouseMotionAdapter and

override mouseDragged( ).

As you can see by looking at the program, not having to implement all of the methods defined by

the MouseMotionListener and MouseListener interfaces saves you a considerable amount of effort

and prevents your code from becoming cluttered with empty methods. As an exercise, you might

want to try rewriting one of the keyboard input examples shown earlier so that it uses a KeyAdapter

1
Unit - V Java Programming III BCA

Inner Classes
An inner class is a class defined within another class, or even within an expression. This section
illustrates how inner classes can be used to simplify the code when using event adapter classes. To
understand the benefit provided by inner classes, consider the applet shown in the following listing.
It does not use an inner class.
s. Its goal is to display the string “Mouse Pressed” in the status bar of
the applet viewer or browser when the mouse is pressed. There are two :The The Java Library top-level
top
classes in this program. MousePressedDemo extends Applet, and MyMouseAdapter extends
MouseAdapter. The init( ) method of MousePressedDemo instantiates MyMouseAdapter and
provides this object as an argument to the addMouseListener( ) method.

2
Unit - V Java Programming III BCA

Java Util Package


The utility package, ([Link])) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable interface
which provides the iterator to iterate through all the collections.
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection
of Objects. In Java, a separate framework named the “Collection Framework” has been defined in
JDK 1.2 which holds all the Java Collection Classes and Interface in it.
In Java, the Collection interface (([Link]) and Map interface ([Link]
[Link]) are the
two main “root” interfaces of Java collection classes.
What is a Framework in Java?
A framework is a set of classes and interfaces which provide a ready-made
made architecture. In order to
implement a new feature or a class, there is no need to define a framework. However, an optimal
object-oriented
oriented design always includes a framework with a collection of classes such that all the
classes perform the same kind of task.
Need for a Separate Collection Framework in Java
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables.
Hashtables All of these
collections
ns had no common interface. Therefore, though the main aim of all the collections is the
same, the implementation of all these collections was defined independently and had no correlation
among them. And also, it is very difficult for the users to remember all the different methods,
syntax, and constructors present in every collection class.
Let’s understand this with an example of adding an element in a hashtable and a vector.
3
Unit - V Java Programming III BCA
Collections are a cornerstone of Java programming. Whether you’re working with lists, sets, or
maps, a strong understanding of collections is crucial.
Advantages of the Java Collection Framework
Since the lack
ack of a collection framework gave rise to the above set of disadvantages, the following
are the advantages of the collection framework.
1. Consistent API: The API has a basic set of interfaces like Collection,
Collection Set, List, or Map, all
the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces
have some common set of methods.

2. Reduces programming effort: A programmer doesn’t have to worry about the design of the
Collection but rather he can focus on its best use in his program. Therefore, the basic
concept of Object-oriented
oriented programming (i.e.) abstraction has been successfully
implemented.

3. Increases program speed and quality: Increases performance by providing high- high
performance implementations of useful data structures and algorithms beca
because in this case,
the programmer need not think of the best implementation of a specific data structure. He
can simply use the best implementation to drastically boost the performance of his
algorithm/program.
Hierarchy of the Collection Framework in Java
The utility package, ([Link]) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable interface
which provides the iterator to iterate through all the collec
collections.
tions. This interface is extended by the
main collection interface which acts as a root for the collection framework. All the collections
extend this collection interface thereby extending the properties of the iterator and the methods of
this interface. The
he following figure illustrates the hierarchy of the collection framework.

4
Unit - V Java Programming III BCA
Before understanding the different components in the above framework, let’s first understand a
class and an interface.
 Class: A class is a user-defined
defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.

 Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, nobody). Interfaces
specify what a class must do and not how. It is the blueprint of the class.
Methods of the Collection Interface
This interface contains various methods which can be directly used by all the collections which
implement this interface. They are:

Interfaces that Extend the Java Collections Interface


The collection framework contains multiple interfaces where every interface is used to store a
specific type of data. The following are the interfaces present in the framework.

5
Unit - V Java Programming III BCA
1. Iterable Interface
This is the root interface for the entire collection framework. The collection interface extends the
iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The
main functionality of this interface is to provide an iterator for the collections. Therefore, this
interface contains only one abstract method which is the iterator. It returns the
Iterator iterator();
2. Collection Interface
This interface extends the iterable interface and is implemented by all the classes in the collection
framework. This interface contains all the basic methods which every collection has like adding the
data into the collection, removing the data, clearing the data, etc. All these methods are
implemented in this interface because these methods are implemented by all the classes irrespective
of their style of implementation. And also, having these methods in this interface ensures that the
names of the methods are universal for all the collections. Therefore, in short, we can say that this
interface builds a foundation on which the collection classes are implemented.
3. List Interface
This is a child interface of the collection interface. This interface is dedicated to the data of the list
type in which we can store all the ordered collections of the objects. This also allows duplicate data
to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack,
etc. Since all the subclasses implement the list, we can instantiate a list object with any of these
classes.
For example:
List <T> al = new ArrayList<> ();
List <T>ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
The classes which implement the List interface are as follows:
i). ArrayList
ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. The size of an
ArrayList is increased automatically if the collection grows or shrinks if the objects are removed
from the collection. Java ArrayList allows us to randomly access the list. ArrayListcan not be used
for primitive types, like int, char, etc. We will need a wrapper class for such cases.
Let’s understand the ArrayList with the following example:
// Java program to demonstrate the
// working of ArrayList
import [Link].*;
import [Link].*;

6
Unit - V Java Programming III BCA
class GFG {

// Main Method
public static void main(String[] args)
{

// Declaring the ArrayList with


// initial size n
ArrayList<Integer> al = new ArrayList<Integer>();

// Appending new elements at


// the end of the list
for (int i = 1; i<= 5; i++)
[Link](i);

// Printing elements
[Link](al);

// Remove element at index 3


[Link](3);

// Displaying the ArrayList


// after deletion
[Link](al);

// Printing elements one by one


for (int i = 0; i<[Link](); i++)
[Link]([Link](i) + " ");
}
}
Output

7
Unit - V Java Programming III BCA
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
Vector
A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. This is identical to
ArrayList in terms of implementation. However, the primary difference between a vector and an
ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.
Let’s understand the Vector with an example:
// Java program to demonstrate the
// working of Vector
import [Link].*;
import [Link].*;

class GFG {

// Main Method
public static void main(String[] args)
{

// Declaring the Vector


Vector<Integer> v = new Vector<Integer>();

// Appending new elements at


// the end of the list
for (int i = 1; i<= 5; i++)
[Link](i);

// Printing elements
[Link](v);

// Remove element at index 3


[Link](3);
8
Unit - V Java Programming III BCA

// Displaying the Vector


// after deletion
[Link](v);

// Printing elements one by one


for (int i = 0; i<[Link](); i++)
[Link]([Link](i) + " ");
}
}

Enumerations or popularly known as enum serve the purpose of representing a group of named
constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named
Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with
the enumeration type. A few important features of EnumSet are as follows:
 It extends AbstractSet class and implements Set Interface in Java.
 EnumSet class is a member of the Java Collections Framework & is not synchronized.
 It’s a high-performance set implementation, much faster than HashSet.
 All of the elements in an EnumSet must come from a single enumeration type that is
specified when the set is created either explicitly or implicitly.
 It does not allow null Objects and throws NullPointerException if we do so.
 It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the
collection is modified while iterating.
 The Hierarchy of EnumSet is as follows:
 [Link]
↳[Link]<E>
↳[Link]<E>
↳[Link]<E>

9
Unit - V Java Programming III BCA

Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type.
Benefits of using EnumSet
 Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in
an EnumSet are implemented using bitwise arithmetic operations.
 EnumSet is faster
ster than HashSet because we no need to compute any hashCode to find the
right bucket.
 The computations are executed in constant time and the space required is very little.
// Java Program to Illustrate Working
// of EnumSet and its functions

// Importing required classes


import [Link];

// Enum
enumGfg{ CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };

// Main class
// EnumSetExample
public class GFG {

10
Unit - V Java Programming III BCA
// Main driver method
public static void main(String[] args) {

// Creating a set
EnumSet<Gfg> set1, set2, set3, set4;

// Adding elements
set1 = [Link]([Link], [Link],
[Link], [Link]);
set2 = [Link](set1);
set3 = [Link]([Link]);
set4 = [Link]([Link], [Link]);

// Printing corresponding elements in Sets


[Link]("Set 1: " + set1);
[Link]("Set 2: " + set2);
[Link]("Set 3: " + set3);
[Link]("Set 4: " + set4);
}
}

The EnumSet Class EnumSet extends AbstractSet and implements Set. It is specifically for use with
keys of an enum type. It is a generic class that has this declaration: class EnumSet> Here, E
specifies the elements. Notice that E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type. EnumSet defines no constructors. Instead, it uses the
factory methods shown in Table 17-7 to create objects. All methods can throw
NullPointerException. The copyOf( ) and range( ) methods can also throw
IllegalArgumentException. Notice that the of( ) method is overloaded a number of times. This is in
the interest of efficiency. Passing a known number of arguments can be faster than using a vararg
parameter when the number of arguments is small.
Java Comparator Interface

The Comparator interface is essential for custom sorting in Java. Understanding its proper
implementation can help you write cleaner and more efficient code Java Comparator interface
Java Comparator interface is used to order the objects of a user-defined class.

11
Unit - V Java Programming III BCA
This interface is found in [Link] package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface

Method Description

public int compare(Object


It compares the first object with the second object.
obj1, Object obj2)

public boolean
It is used to compare the current object with the specified object.
equals(Object obj)

public boolean
It is used to compare the current object with the specified object.
equals(Object obj)

A comparator interface is used to order the objects of user-defined classes. A comparator object is
capable of comparing two objects of the same class. Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name,
address, DOB, etc, and we need to sort the array based on Roll no or name?

The Comparator interface is essential for custom sorting in Java. Understanding its proper
implementation can help you write cleaner and more efficient code.
Method 1: One obvious approach is to write our own sort() function using one of the standard
algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll
No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects of a
user-defined class. This interface is present in [Link] package and contains 2 methods
compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort
the elements based on data members. For instance, it may be on roll no, name, age, or anything
else.

Method of Collections class for sorting List elements is used to sort the elements of List by the
given comparator. .

public void sort(List list, ComparatorClass c)


To sort a given List, ComparatorClass must implement a Comparator interface.
How do the sort() method of Collections class work?
12
Unit - V Java Programming III BCA
Internally the Sort method does call Compare method of the classes it is sorting. To compare two
elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than,
equal, or greater to the other. It uses this result to then determine if they should be swapped for
their sort.

// Java Program to Demonstrate Working of

// Comparator Interface

// Importing required classes

import [Link].*;
import [Link].*;
import [Link].*;

// Class 1
// A class to represent a Student
class Student {

// Attributes of a student
int rollno;
String name, address;

// Constructor
public Student(int rollno, String name, String address)
{

// This keyword refers to current instance itself


[Link] = rollno;
[Link] = name;
[Link] = address;
}

// Method of Student class


// To print student details in main()
public String toString()
{

// Returning attributes of Student


return [Link] + " " + [Link] + " "
+ [Link];
}
}

// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {

// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
13
Unit - V Java Programming III BCA

return [Link] - [Link];


}
}

// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {

// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{

return [Link]([Link]);
}
}

// Class 4
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating an empty ArrayList of Student type


ArrayList<Student> ar = new ArrayList<Student>();

// Adding entries in above List


// using add() method
[Link](new Student(111, "Mayank", "london"));
[Link](new Student(131, "Anshul", "nyc"));
[Link](new Student(121, "Solanki", "jaipur"));
[Link](new Student(101, "Aggarwal", "Hongkong"));

// Display message on console for better readability


[Link]("Unsorted");

// Iterating over entries to print them


for (int i = 0; i < [Link](); i++)
[Link]([Link](i));

// Sorting student entries by roll number


[Link](ar, new Sortbyroll());

// Display message on console for better readability


[Link]("\nSorted by rollno");

// Again iterating over entries to print them


for (int i = 0; i < [Link](); i++)
[Link]([Link](i));
14
Unit - V Java Programming III BCA

// Sorting student entries by name


[Link](ar, new Sortbyname());

// Display message on console for better readability


[Link]("\nSorted by name");

// // Again iterating over entries to print them


for (int i = 0; i < [Link](); i++)
[Link]([Link](i));
}
}

(Unit – V Completed)

15

You might also like