RNS FIRST GRADE COLLEGE
( (An Autonomous Institute Affiliated to Bangalore University and NAAC
Accredited with ‘A’ Grade)
[Link] Road, Channasandra, R R Nagara, Bengaluru – 560 098
DEPARTMENT OF COMPUTER APPLICATIONS
II SEMESTER BCA
Subject Code:
OBJECT ORIENTED PROGRAMMING USING JAVA
Prepared by
Prof. Anusha
Assistant Professor
Dept. of Computer Applications
RNSIT Campus, [Link] Road, Channasandra, Rajarajeshwari Nagar Post,
Bengaluru,Karnataka 560098
Website: [Link] Ph: 080-28611110
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
COURSE CONTENT
UNIT-1 [12 Hours]
Introduction: Basics of object-oriented programming, comparison of procedure-oriented and
object oriented programming paradigms; Difference between C and Java Programming
languages; Features of Java; Objects and classes in Java, Structure of a Java program; Data
Types, variables and operators in java; Control structures- Branching and looping; Methods &
Constructors in java; Java Development Kit (JDK); Built-in classes in Java; Math, Character,
String, String Buffer and Scanner; Wrapper classes; The abstract, static and final classes;
Casting objects; The instance of operator; Usage of this keyword; Arrays in Java.
UNIT-2 [11 Hours]
Inheritance: Super and subclasses; visibility modifiers; Types of Inheritance- single, multiple,
hierarchical and hybrid inheritance; the interface concept in Java, Polymorphism: Compile time
and run time polymorphisms – Method overloading and method overriding. Package: Types of
packages; the util, awt and swing packages; Creating and importing user-defined packages. I/O
programming: Standard I/O streams in Java; Types of streams – Based on the type of
Operations and the type of file.
UNIT-3 [11 Hours]
Event handling: Major events in Java; Two Event Handling mechanisms- Event classes and
Event Listener Interfaces; Mouse and keyboard events; GUI: Panels; Frames; Layout managers
– Flow, border and grid layouts; Buttons; Checkboxes; Radio buttons; Labels; Text fields; Text
areas; Combo boxes; Scroll bars; Sliders; Menu, Dialog boxes. Applet programming:
Comparison of applets and applications; Applet life cycle; Developing and running applets.
String handling: String construction, string length, special string operations, character
extraction, string comparison, modifying string and string buffers.
UNIT-4 [11 Hours]
Exception handling: Types of Java exception – checked and unchecked exceptions; Usage of
try-catch-finally blocks. Multithreading: comparison of multithreading and multitasking; Life
cycle of a thread; two ways of creating thread – by extending the Thread class and by
implementing the Runnable Interface, Thread synchronization. Advanced concepts:
Collections in Java; Introduction to JavaBeans and Java security manager, Importance of
generic programming in java with examples.
Reference Books
1. Ken Arnold, James Gosling, “The Java Programming Language, Fourth Edition,
Addison Wisely, 2005.
2. R Herbert Schildt, ‘The Complete Reference Java, 7th Edition, McGraw Hill, 2007.
For internal circulation only 1
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
TABLE OF CONTENTS
SL. NO. PARTICULARS PAGE NO.
1 Unit-I - Introduction to Java, objects and classes 3-21
2 Unit-II - Inheritance and Polymorphism 23-39
3 Unit-III - Event handling and Applets lifecycle 41-61
4 Unit-IV - Promotion Decisions 63-76
For internal circulation only 2
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
UNIT – I
INTRODUCTION TO JAVA, OBJECTS AND CLASSES
1. Introduction
2. Concept of classes and objects
3. Procedure oriented Vs Object oriented language
4. Features of Java
5. Structure of Java program
6. Data types, variables and operators
7. Control structures and its types
8. Methods and Constructors
9. JDK toolkit
10. Built-in classes and Wrapper classes.
11. The abstract, static and final classes and its usage.
12. The instance of operator
13. “this” keyword and its importance.
*******
1. Introduction: Java is a programming language and a platform. Java is a high level,
robust, object-oriented and secure programming [Link] was developed by Sun
Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team changed the name from
Oak to [Link] is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more!
2. Classes and Objects: In object oriented programming, object and class plays vital
role in programming. These are the two main pillars of OOP. Without object and
class, we cannot create a program in Java.
For internal circulation only 3
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
Class:
A class in Java is a blueprint or a template for creating objects. It defines the structure
and behavior (data members and methods) that the objects of the class will have.
Classes encapsulate data and methods into a single unit.
Syntax:
class ClassName {
// Data members (fields)
// Methods
}
Object:
An object is an instance of a class. It represents a real-world entity and is created
using the new keyword. Each object has its own set of data (state) and can perform
actions (methods) defined in the class.
Syntax:
ClassName obj = new ClassName();
3. Procedure Oriented Vs Object Oriented Language:
Procedural Oriented Programming Object-Oriented Programming
In object-oriented programming, the
In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.
Procedural programming follows a top- Object-oriented programming follows
down approach. a bottom-up approach.
Object-oriented programming has access
There is no access specifier in procedural
specifiers like private, public, protected,
programming.
etc.
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have
Object-oriented programming provides
any proper way of hiding data so it is less
data hiding so it is more secure.
secure.
In procedural programming, overloading is Overloading is possible in object-oriented
not possible. programming.
For internal circulation only 4
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
Procedural Oriented Programming Object-Oriented Programming
In object-oriented programming, the
In procedural programming, there is no
concept of data hiding and inheritance is
concept of data hiding and inheritance.
used.
Code reusability absent in procedural Code reusability present in object-
programming, oriented programming.
Examples: C, FORTRAN, Pascal, Basic,
Examples: C++, Java, Python, C#, etc.
etc.
4. Features of Java :
Here are the 12 features of Java programming
Object-Oriented
Java is based on object-oriented programming principles like inheritance,
encapsulation, polymorphism, and abstraction.
Simple
Java is easy to learn and eliminates complexities like pointers and multiple
inheritance.
Secured
Java provides security through features like bytecode verification, no direct memory
access, and a secure runtime environment.
For internal circulation only 5
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
Platform Independent
Java is "write once, run anywhere" because Java programs run on the JVM, making it
platform-independent.
Robust
Java emphasizes strong memory management, exception handling, and type-checking
to avoid errors.
Portable
Java code can run on any machine without modifications, thanks to its platform
independence and use of the JVM.
Architecture Neutral
Java ensures consistent output regardless of hardware or operating system.
Dynamic
Java supports dynamic loading of classes and runtime linking of libraries.
Interpreted
Java bytecode is interpreted by the JVM, making it portable and platform-
independent.
High Performance
Java achieves better performance through Just-In-Time (JIT) compilation and
optimization techniques.
Multithreaded
Java supports multithreading to perform multiple tasks simultaneously, improving
performance.
Distributed
Java enables the creation of distributed applications with networking capabilities,
using APIs like RMI and EJB.
These features make Java a popular programming language for developing reliable,
scalable, and secure applications.
5. 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.
For internal circulation only 6
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
Documentation Section
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. Whatever we write in the documentation section, the Java compiler
ignores the statements during the execution of the program. To write the
statements in the documentation section, we use comments. The comments
may be single-line, multi-line, and documentation comments.
Single-line Comment: It starts with a pair of forwarding slash (//).
Multi-line Comment: It starts with a /* and ends with */. We write between
these two symbols.
Documentation Comment: It starts with the delimiter (/**) and ends with
*/.
Package Declaration
The package declaration is optional. It is placed just after the documentation
section. In this section, we declare the package name in which the class is
placed. Note that there can be only one package statement in a Java program.
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.
Import Statements
The package contains the many predefined classes and interfaces. If we want
to use any class of a particular package, we need to import that class. The
import statement represents the class stored in the other package. We use the
import keyword to import the class. It is written before the class declaration
and after the package statement. We use the import statement in two ways,
either import a specific class or import all classes of a particular package. In a
Java program, we can use multiple import statements. For Example:
import [Link];
Interface Section
It is an optional section. We can create an interface in this section if required.
We use the interface keyword to create an interface. 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.
Class Definition
In this section, we define the class. 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. We use the class keyword to define the class.
The class is a blueprint of a Java program. It contains information about user-
For internal circulation only 7
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
defined methods, variables, and constants. Every Java program has at least one
class that contains the main() method.
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. We can also decide and define
the scope of variables by using the modifiers. It defines the life of the
variables.
Main Method Class
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
6. Data types, variables and operators:
Data Types in Java: Data types define the type of data a variable can store.
Java has two categories of data types:
Primitive Data Types (8 types)
Non-Primitive Data Types (Objects, Arrays, Strings, etc.)
Primitive Data Types
Integer Types
byte (1 byte): Range -128 to 127
short (2 bytes): Range -32,768 to 32,767
int (4 bytes): Range -2^31 to 2^31-1
long (8 bytes): Range -2^63 to 2^63-1
Floating Point Types
float (4 bytes): For decimal numbers (up to 7 decimal digits).
double (8 bytes): For precise decimal numbers (up to 15 decimal digits).
Character Type
char (2 bytes): Stores a single character using Unicode (e.g., 'A', '1').
Boolean Type
boolean (1 bit): Can hold only true or false.
Non-Primitive Data Types
Strings: Sequence of characters, e.g., "Hello"
Arrays: Collection of similar data types.
For internal circulation only 8
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
Classes and Objects: User-defined types.
Variables in Java : A variable is a container that stores data. Variables are created using a
data type.
Types of Variables:
Local Variables
Declared inside methods, constructors, or blocks.
Scope: Limited to the block in which it is declared.
Instance Variables
Declared inside a class but outside methods.
Each object of the class gets its own copy.
Static Variables
Declared with the static keyword.
Shared among all objects of the class.
Example:
int age = 25; // Local variable
double salary = 50000.50; // Instance variable
static String college = "RNSFGC"; // Static variable
Operators in Java
Operators are special symbols or keywords used to perform operations on variables and
values.
Types of Operators
Arithmetic Operators :Used for basic mathematical operations:
+ (Addition), - (Subtraction), * (Multiplication), / (Division), %
(Modulus).
Example:
int a = 10, b = 3;
[Link](a + b); // Output: 13
[Link](a % b); // Output: 1
Relational (Comparison) Operators: Compare values and return a boolean
result. ==, !=, >, <, >=, <=
Example:
For internal circulation only 9
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
int x = 5, y = 10;
[Link](x > y); // Output: false
Logical Operators : Used for logical operations: && (AND), || (OR), !
(NOT).
Example:
boolean a = true, b = false;
[Link](a && b); // Output: false
[Link](!a); // Output: false
Assignment Operators : Assign values to variables. =, +=, -=, *=, /=, %=
Example:
int num = 10;
num += 5; // num = num + 5;
[Link](num); // Output: 15
Unary Operators : Operate on a single operand:+, -, ++, --
Example:
int x = 10;
x++;
[Link](x); // Output: 11
Bitwise Operators :Work on bits: &, |, ^, ~, <<, >>.
Ternary Operator :Short-hand for if-else:
Syntax: condition ? expression1 : expression2;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link](max); // Output: 20
7. Control Structures and its types:
Control structures determine the flow of program execution in a systematic manner.
Java provides three main types of control structures:
Sequential Control
Selection (Decision-Making) Control
Looping (Iteration) Control
For internal circulation only 10
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
Sequential Control Structure
Sequential execution means the statements are executed in the order in
which they appear, one after the other.
Example:
public class SequentialExample {
public static void main(String[] args) {
[Link]("Start of Program"); // Step 1
int a = 5, b = 10; // Step 2
int sum = a + b; // Step 3
[Link]("Sum: " + sum); // Step 4
}
}
Output:
Start of Program
Sum: 15
Selection (Decision-Making) Control Structure
Executes a block of code based on specific conditions.
Types of Selection Structures:
if Statement: Executes a block of code only if the condition is true.
Example:
public class IfExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
[Link]("The number is positive.");
}
}
}
Output:
For internal circulation only 11
Subject Name: OOPs Using Java
Faculty Name: Prof. Anusha
The number is positive.
if-else Statement: Executes one block if the condition is true and another block if
the condition is false.
Example:
public class IfElseExample {
public static void main(String[] args) {
int number = -5;
if (number > 0) {
[Link]("Positive Number");
} else {
[Link]("Negative Number");
}
}
}
Output:
Negative Number
if-else if Ladder: Checks multiple conditions in sequence.
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
}
}
For internal circulation only 12
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Output:
Grade B
switch Statement: Selects one block of code to execute based on a matching
value.
Example:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Other Day");
}
}
}
Output:
Wednesday
Looping (Iteration) Control Structure
Executes a block of code repeatedly until a condition is met or becomes false.
Types of Loops:
for Loop : Repeats a block of code a fixed number of times.
Example:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Iteration: " + i);
}
}
}
For internal circulation only 13
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
while Loop :Repeats a block of code as long as the condition is true.
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link]("Count: " + i);
i++;
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
do-while Loop : Executes the block of code at least once, even if the condition is
false.
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
For internal circulation only 14
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link]("Count: " + i);
i++;
} while (i <= 3);
}
}
Output:
Count: 1
Count: 2
Count: 3
Enhanced for Loop (For-each Loop) :Used for iterating over arrays or collections.
Example:
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
for (int num : numbers) {
[Link]("Number: " + num);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
8. Methods and Constructors:
Methods
Definition: A method is a block of code that performs a specific task. It is
executed when called or invoked.
Syntax:
returnType methodName(parameters) {
// method body
For internal circulation only 15
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
}
Where :
returnType: Data type of the value returned (e.g., int, void, etc.). Use void if
no value is returned.
methodName: The name used to call the method.
parameters: Inputs passed to the method (optional)
Types of Methods:
Predefined Methods: Built-in methods provided by Java (e.g.,
[Link](), [Link]()).
User-Defined Methods: Methods created by the programmer.
Constructors
A constructor is a special method used to initialize objects. It is automatically
invoked when an object is created.
Key Points about Constructors:
The constructor name must be the same as the class name.
Constructors do not have a return type, not even void.
If no constructor is defined, Java provides a default constructor.
Constructors are used to initialize instance variables.
Types of Constructors:
Default Constructor (A constructor that takes no parameters)
Parameterized Constructor (A constructor that takes parameters)
9. JDK tool Kit :
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar),
a documentation generator (Javadoc), etc. to complete the development of a Java
Application.
For internal circulation only 16
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
10. Built in and Wrapper classes:
Built-in Classes
These are classes provided by the Java Standard Library to simplify
programming.
Examples include String, Math, System, and Scanner.
Example:
public class BuiltInExample {
public static void main(String[] args) {
int num1 = 25;
double result = [Link](num1); // Using built-in Math class
[Link]("Square root of " + num1 + " is: " + result);
}
For internal circulation only 17
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
}
Output: Square root of 25 is: 5.0
Wrapper Classes
Wrapper classes convert primitive data types into [Link] are
part of the [Link] package.
Primitive types (like int, char) have corresponding wrapper classes:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Example:
public class WrapperExample {
public static void main(String[] args) {
// Primitive to Wrapper (Boxing)
int num = 10;
Integer obj = [Link](num); // Boxing
[Link]("Wrapper Object: " + obj);
// Wrapper to Primitive (Unboxing)
int newNum = [Link](); // Unboxing
[Link]("Primitive Value: " + newNum);
Output :
Wrapper Object: 10
For internal circulation only 18
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Primitive Value: 10
11. The abstract, static and final classes and its usage:
Abstract Classes
A class that cannot be instantiated and is declared using the abstract
keyword.
It is used to define a blueprint for subclasses with abstract and concrete
methods.
Abstract Method: A method without implementation (no body) that must be
implemented by subclasses.
Example of Abstract Class
abstract class Animal {
abstract void sound(); // Abstract method
void eat() { // Concrete method
[Link]("Animals eat food.");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks.");
}
}
public class AbstractExample {
public static void main(String[] args) {
Animal myDog = new Dog(); // Polymorphism
[Link]();
[Link]();
}
}
Output:
Dog barks.
Animals eat food.
Static Classes
A class cannot be instantiated and is declared static inside another class.
It is used to group related methods or constants.
A static class can only contain static members.
Example of Static Class
class OuterClass {
static class InnerStaticClass {
For internal circulation only 19
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
static void display() {
[Link]("This is a static inner class.");
}
}
}
public class StaticExample {
public static void main(String[] args) {
[Link]();
}
}
Output:
This is a static inner class.
Final Classes
A class declared as final cannot be subclassed (no inheritance).
It is used to prevent modification of a class structure.
Used for security, constants, and ensuring a class remains unmodified.
Example of Final Class
final class Vehicle {
void display() {
[Link]("This is a vehicle.");
}
}
// This will give an error if we try to inherit
// class Car extends Vehicle { }
public class FinalExample {
public static void main(String[] args) {
Vehicle v = new Vehicle();
[Link]();
}
}
Output:
This is a vehicle.
12. The “instance of operator” : The instanceof operator in Java is used to check
whether an object is an instance of a specific class or an interface. It is a type
comparison operator that returns true if the object is an instance of the specified class,
subclass, or interface. Otherwise, it returns false.
Syntax:
object instanceof ClassName
For internal circulation only 20
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Returns true if the object is of the specified class or a subclass.
Returns false otherwise.
Example:
class Animal {}
class Dog extends Animal {}
public class InstanceofExample {
public static void main(String[] args) {
Animal a = new Dog();
[Link](a instanceof Dog); // true
[Link](a instanceof Animal); // true
}
}
13. Importance of “this” keyword:
The “this” keyword is a reference variable in Java that refers to the current instance
of a class. It is used within an instance method or constructor to refer to the current
object.
Example:
class Person {
String name;
// Constructor with parameter
Person(String name) {
[Link] = name; // Refers to the instance variable
}
void display() {
[Link]("Name: " + [Link]); // Refers to the current object
}
}
public class ThisKeywordExample {
public static void main(String[] args) {
Person p = new Person("Alice");
[Link](); // Output: Name: Alice
}
}
For internal circulation only 21
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
UNIT- II
For internal circulation only 22
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
UNIT – II
INHERITANCE AND POLYMORPHISM
1. Concept of Inheritance
2. Superclass and subclass
3. Visibility modifiers
4. Types of Inheritance
5. The concept of Interface
6. Polymorphism and its types
7. Method Overloading and Overriding
8. Packages and its types
9. Creating and importing user defined packages
10. I/O programming- Streams and its types
*******
1 . Concept of Inheritance:
Inheritance is the mechanism in java by which one class is allow to inherit the features (fields
and methods) of another class. It is process of deriving a new class from an existing class. A
class that is inherited is called a superclass and the class that does the inheriting is called a
subclass. Inheritance represents the IS-A relationship, also known as parent-child
relationship. The keyword used for inheritance is extends
Syntax: class Subclass-name extends Superclass-name
{
//methods and fields
}
Advantages of Inheritance:
• Code reusability - public methods of base class can be reused in derived
classes
• Data hiding – private data of base class cannot be altered by derived class
• Overriding--With inheritance, we will be able to override the methods of the
base class in the derived class
Example:
class Animal {
void eat() {
For internal circulation only 23
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link]("Animal eats");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited method from Animal
[Link](); // Dog's own method
}
}
2. Superclass and Subclass:
Superclass: The class that is inherited from. It contains common attributes and
methods which are inherited by its subclasses.
Subclass: The class that inherits properties and methods from the superclass. A
subclass can override methods of the superclass to provide specific behavior.
Example:
class Vehicle {
void move() {
[Link]("Vehicle moves");
}
}
class Car extends Vehicle {
@Override
void move() {
[Link]("Car moves");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Vehicle();
For internal circulation only 24
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Car c = new Car();
[Link](); // Vehicle moves
[Link](); // Car moves (overridden method)
}
}
3. Visibility Modifiers:
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
For internal circulation only 25
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Understanding Java Access Modifiers
Example of public modifier:
public class Car {
public String model; // public field
public void drive() { // public method
[Link]("Driving the car");
class Test {
public static void main(String[] args) {
Car car = new Car();
[Link] = "Tesla"; // Accessible because model is public
[Link](); // Accessible because drive() is public
Example of private modifier:
class Car {
private String model; // private field
For internal circulation only 26
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
private void startEngine() { // private method
[Link]("Starting engine");
public void drive() {
startEngine(); // private method can be called within the class
class Test {
public static void main(String[] args) {
Car car = new Car();
// [Link] = "Tesla"; // Error: Cannot access private field model
// [Link](); // Error: Cannot access private method startEngine
[Link](); // drive() can still be called since it is public
Example of protected modifier:
class Vehicle {
protected String model; // protected field
protected void start() { // protected method
[Link]("Starting the vehicle");
class Car extends Vehicle {
public void drive() {
model = "Tesla"; // Accessible in subclass
For internal circulation only 27
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
start(); // Accessible in subclass
class Test {
public static void main(String[] args) {
Car car = new Car();
[Link](); // Works because Car is a subclass of Vehicle
// [Link](); // Error: Cannot access protected method outside subclass
Example of default modifier:
class Car {
String model; // Default access level (package-private)
void start() { // Default access level (package-private)
[Link]("Starting the vehicle");
class Test {
public static void main(String[] args) {
Car car = new Car();
[Link] = "Tesla"; // Accessible within the same package
[Link](); // Accessible within the same package
For internal circulation only 28
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
4. Types of Inheritance:
Single Inheritance: In single inheritance, a sub-class is derived from only one super
class. It inherits the properties and behavior of a single-parent class. Sometimes, it is
also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is
a child class. The class ‘B’ inherits all the properties of the class ‘A’.
Example:
class Animal {
void eat() {
[Link]("Eating food...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
}
}
Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a
base class, and as well as the derived class also acts as the base class for other classes.
In the below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C.
class Animal {
For internal circulation only 29
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
void eat() {
[Link]("Eating food...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
class Puppy extends Dog {
void play() {
[Link]("Playing...");
}
}
public class Test {
public static void main(String[] args) {
Puppy puppy = new Puppy();
[Link](); // Inherited from Animal
[Link](); // Inherited from Dog
[Link](); // Defined in Puppy
}
}
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one subclass. In the below image, class A serves
as a base class for the derived classes B, C, and D.
Example:
class Animal {
void eat() {
[Link]("Eating food...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
class Cat extends Animal {
void meow() {
[Link]("Meowing...");
}
}
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
For internal circulation only 30
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
Cat cat = new Cat();
[Link](); // Inherited from Animal
[Link](); // Defined in Cat
}
}
Hybrid Inheritance: Hybrid Inheritance is a combination of two or more types of
inheritance. It can involve the mixing of single inheritance, multilevel inheritance, and
hierarchical inheritance.
Example:
// Base class (Superclass)
class LivingBeing {
void breathe() {
[Link]("Breathing...");
}
}
// Single Inheritance
class Animal extends LivingBeing {
void eat() {
[Link]("Animal is eating...");
}
}
// Multilevel Inheritance (Dog extends Animal)
class Dog extends Animal {
void bark() {
[Link]("Dog is barking...");
}
}
// Hierarchical Inheritance (Cat also extends Animal)
class Cat extends Animal {
void meow() {
[Link]("Cat is meowing...");
}
}
public class Test {
public static void main(String[] args) {
// Creating an object of Dog (Multilevel Inheritance)
Dog dog = new Dog();
[Link](); // Inherited from LivingBeing
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
// Creating an object of Cat (Hierarchical Inheritance)
Cat cat = new Cat();
[Link](); // Inherited from LivingBeing
For internal circulation only 31
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link](); // Inherited from Animal
[Link](); // Defined in Cat
}
}
Important Note: Java does not support multiple inheritance with classes due to
potential ambiguity in method inheritance, but multiple inheritance can be achieved by
using interfaces.
5. The concept of Interface: An interface in Java is a blueprint of a class. It has static
constants and abstract [Link] 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 [Link] other
words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Why use interfaces?
They allow you to achieve abstraction and multiple inheritance.
They define a contract for the class.
Example:
interface Animal {
void sound();
class Dog implements Animal {
public void sound() {
[Link]("Bark");
class Cat implements Animal {
public void sound() {
[Link]("Meow");
public class Test {
For internal circulation only 32
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
public static void main(String[] args) {
// Creating an object of Dog
Animal a = new Dog();
[Link](); // Output: Bark
// Creating an object of Cat
a = new Cat();
[Link](); // Output: Meow
}}
Relationship Between Classes and Interfaces
6. Polymorphism and its types:
Polymorphism is a fundamental concept in Java that allows objects to take on
different forms and perform different tasks based on the context in which they
are used. The word polymorphism comes from the Greek words poly, meaning
"many", and morphs, meaning "forms".
Types:
Compile time polymorphism: Also known as early binding,
overloading, and static binding, this is when the compiler decides
which method to call. It's faster because the method execution path
is known at compile time.
Run-time polymorphism: Also known as late binding, dynamic
binding, and overriding, this is when the method call is decided
during the program's execution. It's slower because the method
execution path is determined at runtime.
For internal circulation only 33
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Difference between Compile time and Runtime Polymorphism
7. Method Overloading and Method Overriding:
Method Overloading
Method overloading is a feature in Java that allows a class to have more than
one method with the same name, provided their parameter lists are different. It
enables methods to perform similar but distinct tasks. Method overloading is a
form of compile-time polymorphism, meaning that the compiler determines
which method to call based on the method signature (name and parameter list).
Example
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](10, 20)); // Calls add(int, int)
[Link]([Link](10.5, 20.5)); // Calls add(double, double)
}
}
Method Overriding
Method overriding is a fundamental concept in object-oriented programming
(OOP) that allows a subclass to provide a specific implementation for a
method that is already defined in its superclass. It enables a subclass to inherit
the method from the superclass but override it to perform a different task.
Method overriding is essential for achieving runtime polymorphism, where the
method that gets called is determined by the actual object type at runtime, not
the reference type.
Example
class Animal {
void sound() { [Link]("Animal sound"); }
}
For internal circulation only 34
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
class Dog extends Animal {
@Override
void sound() { [Link]("Bark"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Bark (overridden method is called)
}
}
8. Packages and Its types:
A package in Java is a way to group related classes, interfaces, and sub-packages
together. It helps in organizing the code in a modular way, avoids name conflicts, and
makes it easier to maintain and manage the code.
There are two types of packages in Java:
Built-in Packages
User-defined Packages
Built-in Packages
Java provides a number of built-in packages that contain classes and interfaces for
performing common tasks such as input/output, networking, utilities, etc. Some
commonly used built-in packages are:
[Link]: Contains utility classes such as collections, date, and time handling
classes.
[Link]: Provides classes for input and output operations.
[Link]: Contains fundamental classes, such as String, Math, System, and
Object.
[Link]: Contains classes for networking operations like Socket, URL, and
HttpURLConnection
Example:
import [Link]; // Importing the Scanner class from [Link] package
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number:");
int num = [Link]();
[Link]("You entered: " + num);
}
}
User-defined Packages:
A user-defined package is created by the programmer to group related classes and
interfaces. To define a user-defined package, we use the package keyword.
For internal circulation only 35
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Steps to create and use a user-defined package:
Create the package: Define a package using the package keyword at the top of
the source file.
Create classes: Create classes within the package.
Import the package: Use the import keyword in other classes to access the
classes and interfaces of the package.
9. Creating and Importing User defined packages
To create a package is quite easy: simply include a package command as the first
statement in a Java source file.
Any classes declared within that file will belong to the specifiedpackage.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the
default package, which has no name.
This is the general form of the package statement.
package pkg;
Java uses file system directories to store [Link] example, the following
statement creates a package called MyPackage:
package MyPackage;
classes you declare to be part of MyPackage must be stored in a
directory called MyPackage.
Remember that case is significant, and the directory name must match the
package name exactly.
More than one file can include the same package statement. The package
statement simply specifies to which package the classes defined in a file
belong.
Example:
/*[Link]*/
import [Link];
import [Link];
import [Link];
public class MainClass
public static void main(String args[])
Square square=new Square();
Triangle triangle=new Triangle();
For internal circulation only 36
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Circle circle=new Circle();
[Link]((float)5.5);
[Link]("The area of square is:"+[Link]());
[Link]((double)20.56,(double)23.90);
[Link]("The area of triangle is:"+[Link]());
[Link]((double)5.5);
[Link]("The area of circle is:"+[Link]());
/*[Link]*/
package shape;
public class Square
float side;
public void getData(float temp)
side=temp;
public double area()
return (side*side);
/*[Link]*/
package shape;
For internal circulation only 37
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
public class Triangle
double base;
double height;
public void getData(double temp1,double temp2)
base=temp1;
height=temp2;
public double area()
return ((1.0/2.0)*(base*height));
/*[Link]*/
package shape;
public class Circle
double radius;
double height;
public void getData(double temp)
radius=temp;
public double area(){
For internal circulation only 38
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
return ((3.1427*(2.0*radius)*(2.0*radius))/4.00);}}
10. I/O programming – Streams and its types
o Streams are used for I/O operations in Java. A stream is a sequence of data
used to read from or write to a source (like a file).
Byte Streams: Handle binary data (like images, audio files).
Example: FileInputStream, FileOutputStream.
Character Streams: Handle character data (text data).
Example: FileReader, FileWriter.
Buffered Streams: Provide efficient reading/writing by buffering data.
Example: BufferedReader, BufferedWriter.
Example:
import [Link].*;
public class FileExample {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("[Link]");
FileOutputStream fout = new FileOutputStream("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link](i);
[Link]();
[Link]();
} catch (IOException e) {
[Link]("Error: " + e);
}}}
For internal circulation only 39
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
UNIT- III
For internal circulation only 40
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
UNIT – III
EVENT HANDLING AND APPLET LIFE CYCLE
1. Concept of Event handling
2. Two Event handling mechanisms
3. Event classes and Interfaces
4. GUI and Layout Managers
5. Applet Programming
6. Applet Vs Application programming
7. Applet lifecycle
8. Developing and running applets
9. String Handling and its operations
*******
1 . Concept of Event Handling:
Event handling in Java is a mechanism that allows a program to respond to user
actions such as clicks or by presses or system-generated events. This is an essential
part of creating interactive applications, especially in graphical user interfaces (GUIs).
The components of Event handling are:
Event: An occurrence like a button press or a mouse move.
Event Source: The component that generates the event (e.g., a button).
Event Listener: An object that listens for and handles events using
specific methods
The [Link] package can be used to provide various event classes.
Classification of Events
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 are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
Background Events: Events that don’t require interactions of users to
generate are known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.
2 . Two Event Handling Mechanisms:
Delegation Event model: It has source and Listeners. The Delegation Event model is
defined to handle events in GUI programming languages. The GUI stands for
Graphical User Interface, where a user graphically/visually interacts with the
[Link] GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an event that
For internal circulation only 41
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
is mapped to a code to respond to functionality to the user. This is known as event
handling.
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, 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.
Steps involved in the Event Delegation model are:
1. We shold add apprproiate listener component. This is donw with the
help of “addxxxListener()” method, Similarly to remove a listener
from the component , we can use “removexxxListener()” method.
2. Implement the methods of the listener, especially the method which
handles the event
3. When an event is generated on the component, then the method in
step2 will be executed and the event is handled.
Important Event Classes and Interface
Example:
import [Link].*;
For internal circulation only 42
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
import [Link].*;
public class WindowClosingExample extends Frame {
public WindowClosingExample() {
// Set the frame title
setTitle("Window Closing Example");
setSize(400, 300);
// Add a WindowListener to handle the window closing event
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link]("Window is closing...");
dispose(); // Releases system resources
[Link](0); // Terminates the program
}
});
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
new WindowClosingExample(); // Create and display the frame
}
}
MOUSE EVENTS: Mouse events occur when the mouse interacts with a component.
Common events include clicking, pressing, releasing, entering, or exiting a component area.
The listener methods for Mouse Events are :
mouseClicked(MouseEvent e): Invoked when the mouse button is clicked.
mousePressed(MouseEvent e): Invoked when the mouse button is pressed.
mouseReleased(MouseEvent e): Invoked when the mouse button is released.
For internal circulation only 43
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
mouseEntered(MouseEvent e): Invoked when the mouse enters a component.
mouseExited(MouseEvent e): Invoked when the mouse exits a component.
Additionally, the MouseMotionListener interface is used for:
mouseDragged(MouseEvent e): Invoked when the mouse is dragged.
mouseMoved(MouseEvent e): Invoked when the mouse is moved.
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventExample extends JFrame {
public MouseEventExample() {
setTitle("Mouse Event Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Interact with the window!", [Link]);
[Link](new Font("Arial", [Link], 16));
add(label);
// Add MouseListener to handle mouse events
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered the window");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited the window");
}
For internal circulation only 44
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
});
setVisible(true);
}
public static void main(String[] args) {
new MouseEventExample();
}
}
KEY EVENTS: Key events occur when a user interacts with the keyboard, such as pressing,
releasing, or typing a key. The listener methods for Key Events are:
keyPressed(KeyEvent e): Invoked when a key is pressed.
keyReleased(KeyEvent e): Invoked when a key is released.
keyTyped(KeyEvent e): Invoked when a key is typed (press and release).
Example:
import [Link].*;
import [Link].*;
import [Link].*;
public class KeyEventExample extends JFrame {
public KeyEventExample() {
setTitle("Key Event Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Type something on the keyboard!", [Link]);
[Link](new Font("Arial", [Link], 16));
add(label);
// Add KeyListener to handle key events
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}
@Override
For internal circulation only 45
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]());
}
@Override
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
});
setVisible(true);
setFocusable(true); // Ensure the frame receives key events
}
public static void main(String[] args) {
new KeyEventExample();
}
}
4. GUI Components and Layout Managers
Frame : A Frame is a top-level window with a title and border, used as the main
container for the graphical user [Link] is the foundation for other components
like buttons, labels, etc.
Syntax
Frame frame = new Frame("Title");
Common Methods:
setSize(int width, int height): Sets the size of the frame.
setVisible(boolean flag): Makes the frame visible.
setTitle(String title): Sets the title of the frame.
setLayout(LayoutManager layout): Sets the layout of the frame.
Example:
import [Link].*;
public class FrameExample {
public static void main(String[] args) {
Frame f = new Frame("AWT Frame Example");
For internal circulation only 46
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link](400, 300);
[Link](true);
}
}
Button : A Button is a clickable component that triggers an action when pressed.
Syntax
Button button = new Button("Click Me");
Common Methods:
setLabel(String label): Sets the button's label.
addActionListener(ActionListener listener): Adds an action listener to the
button.
Example:
import [Link].*;
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
Frame frame = new Frame("Button Example");
Button btn = new Button("Click Me");
[Link](100, 100, 100, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
});
[Link](btn);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
Label: A Label is a non-editable text component used to display text.
Syntax
Label label = new Label("Hello, World!");
Common Methods:
setText(String text): Sets the label's text.
For internal circulation only 47
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
setAlignment(int alignment): Sets the alignment of the text (e.g.,
[Link], [Link]).
Example:
import [Link].*;
public class LabelExample {
public static void main(String[] args) {
Frame f = new Frame("Label Example");
Label label = new Label("This is a label.");
[Link](100, 100, 150, 30);
[Link](label);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
TextField: A TextField is a single-line text input field where users can type data.
Syntax
TextField textField = new TextField();
Common Methods:
setText(String text): Sets the text in the text field.
getText(): Retrieves the text entered in the field.
setEditable(boolean flag): Sets whether the text field is editable.
Example:
import [Link].*;
import [Link].*;
public class TextFieldExample {
public static void main(String[] args) {
Frame f = new Frame("TextField Example");
TextField tf = new TextField();
[Link](100, 100, 150, 30);
[Link](tf);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
For internal circulation only 48
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
TextArea : A TextArea is a multi-line text input area that can hold a large amount of
text.
Syntax
TextArea textArea = new TextArea();
Common Methods:
setText(String text): Sets the content of the text area.
getText(): Retrieves the text content.
append(String text): Appends text to the text area.
Example:
import [Link].*;
public class TextAreaExample {
public static void main(String[] args) {
Frame f = new Frame("TextArea Example");
TextArea ta = new TextArea();
[Link](100, 100, 200, 100);
[Link](ta);
[Link](400, 300);
[Link](null);
[Link](true);
}
}
Checkbox : A Checkbox allows the user to select or deselect an option.
Syntax
Checkbox checkbox = new Checkbox("Accept Terms and Conditions");
Common Methods:
setState(boolean state): Sets the state of the checkbox (selected or
deselected).
getState(): Retrieves the state (true or false).
Example:
import [Link].*;
import [Link].*;
public class CheckboxExample {
public static void main(String[] args) {
Frame frame = new Frame("Checkbox Example");
Checkbox checkbox = new Checkbox("Agree to terms");
[Link](100, 100, 150, 30);
For internal circulation only 49
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Checkbox state: " + ([Link]() ?
"Checked" : "Unchecked"));
}
});
[Link](checkbox);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
List : A List is a GUI component that allows users to select one or more items from a
list of options.
Syntax
List list = new List();
Common Methods:
add(String item): Adds an item to the list.
getItem(int index): Retrieves the item at a specific index.
getSelectedItem(): Retrieves the selected item.
Example:
import [Link].*;
public class ListExample {
public static void main(String[] args) {
Frame f = new Frame("List Example");
List list = new List();
[Link](100, 100, 150, 100);
[Link]("Option 1");
[Link]("Option 2");
[Link]("Option 3");
[Link](list);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
Choice : A Choice is a dropdown list where the user can select one option from a list
of choices.
For internal circulation only 50
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Syntax
Choice choice = new Choice();
Common Methods:
add(String item): Adds an item to the list.
getSelectedItem(): Gets the selected item.
Example:
import [Link].*;
public class ChoiceExample {
public static void main(String[] args) {
Frame f = new Frame("Choice Example");
Choice choice = new Choice();
[Link](100, 100, 150, 30);
[Link]("Option 1");
[Link]("Option 2");
[Link]("Option 3");
[Link](choice);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
Panel : A Panel is a container used to group components together.
Syntax
Panel panel = new Panel();
Common Methods:
setLayout(LayoutManager layout): Sets the layout manager of the panel.
add(Component comp): Adds a component to the panel.
Example:
import [Link].*;
public class PanelExample {
public static void main(String[] args) {
Frame frame = new Frame("Panel Example");
Panel panel = new Panel();
[Link](50, 50, 200, 100);
Label label = new Label("Label inside Panel");
For internal circulation only 51
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link](label);
[Link](panel);
[Link](400, 300);
[Link](null);
[Link](true);
}
}
ComboBox (Choice): A Choice (ComboBox) is a dropdown list that allows users to
select one option from a list of choices.
Syntax
Choice choice = new Choice();
Common Methods:
add(String item): Adds an item to the combo box.
getSelectedItem(): Retrieves the selected item.
select(int index): Selects the item at the specified index.
getItem(int index): Retrieves the item at the specified index.
Example:
import [Link].*;
public class ComboBoxExample {
public static void main(String[] args) {
Frame frame = new Frame("ComboBox Example");
Choice choice = new Choice();
[Link](100, 100, 150, 30);
[Link]("Option 1");
[Link]("Option 2");
[Link]("Option 3");
[Link](choice);
[Link](300, 200);
[Link](null);
[Link](true);
}
}
Scroll Bars (Scrollbar) : A Scrollbar is used to provide a vertical or horizontal
scrolling mechanism for content that exceeds the visible area.
Syntax
Scrollbar scrollbar = new Scrollbar();
Common Methods:
For internal circulation only 52
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
setOrientation(int orientation): Sets the orientation
([Link] or [Link]).
setValues(int value, int visible, int minimum, int maximum): Sets the
initial value, visible size, and range of the scrollbar.
getValue(): Retrieves the current position of the scrollbar.
Example:
import [Link].*;
public class ScrollbarExample {
public static void main(String[] args) {
Frame frame = new Frame("Scrollbar Example");
Scrollbar scrollbar = new Scrollbar();
[Link](100, 100, 200, 50);
[Link](scrollbar);
[Link](400, 300);
[Link](null);
[Link](true);
}
}
Menus (Menu, MenuBar, MenuItem) : Menus allow users to select options from a list
of commands or actions. It includes MenuBar (a container for menus), Menu (a
menu containing items), and MenuItem (individual items in a menu).
Syntax
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("File");
MenuItem item = new MenuItem("Open");
Common Methods:
add(MenuItem item): Adds a menu item to a menu.
setMenuBar(MenuBar mb): Sets the menu bar for the frame.
addActionListener(ActionListener listener): Adds an action listener to
menu items.
Example:
import [Link].*;
import [Link].*;
public class MenuExample {
public static void main(String[] args) {
Frame frame = new Frame("Menu Example");
// Create Menu and Menu Items
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("File");
For internal circulation only 53
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");
// Add ActionListener for "Open"
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Open menu item clicked.");
}
});
// Add ActionListener for "Exit"
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link](0);
}
});
[Link](openItem);
[Link](exitItem);
[Link](menu);
// Set the menu bar
[Link](menuBar);
[Link](400, 300);
[Link](true);
}
}
Dialog Boxes (Dialog):A Dialog is a pop-up window used to provide information or
ask for user input. It can be modal (blocking) or non-modal (non-blocking).
Syntax
Dialog dialog = new Dialog(parentFrame, "Dialog Box", true); // true for
modal
Common Methods:
setSize(int width, int height): Sets the size of the dialog.
setVisible(boolean flag): Shows or hides the dialog.
setLayout(LayoutManager layout): Sets the layout of the dialog.
Example:
import [Link].*;
import [Link].*;
public class DialogBoxExample {
public static void main(String[] args) {
Frame parentFrame = new Frame("Parent Frame");
[Link](400, 300);
[Link](true);
For internal circulation only 54
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
// Create a Dialog Box
Dialog dialog = new Dialog(parentFrame, "Sample Dialog", true);
[Link](200, 150);
[Link](new FlowLayout());
Button closeButton = new Button("Close");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link](false);
}
});
[Link](closeButton);
[Link](true); // Show dialog
}
}
TextArea: A TextArea is a multi-line text input area that can hold a large amount of
text. It is used when the user needs to enter or display multiple lines of text, such as in
a note-taking app or an editor.
Syntax
TextArea textArea = new TextArea();
Common Methods:
setText(String text): Sets the content of the text area.
getText(): Retrieves the current text content from the text area.
append(String text): Appends the given text at the end of the existing
content.
setEditable(boolean editable): Specifies whether the text area can be edited
by the user.
setColumns(int columns): Sets the width of the text area in terms of the
number of columns.
setRows(int rows): Sets the number of visible rows (height) of the text area.
setForeground(Color color): Sets the text color in the text area.
setBackground(Color color): Sets the background color of the text area.
Example:
import [Link].*;
public class TextAreaExample {
public static void main(String[] args) {
// Create a Frame
Frame frame = new Frame("TextArea Example");
// Create a TextArea and set its properties
For internal circulation only 55
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
TextArea textArea = new TextArea("Hello, this is a TextArea
example.");
[Link](50, 50, 300, 150); // Position and size of the
TextArea
[Link](true); // Make the text area editable
// Add the TextArea to the Frame
[Link](textArea);
// Frame settings
[Link](400, 300);
[Link](null); // Use null layout to manually set position
[Link](true); // Display the frame
}
}
5. Applet Programming: An Applet is a special type of Java program that runs inside a web
browser or applet viewer, rather than being run as a standalone application. Applets are
mainly used to provide interactive features and graphics in web pages. They are written in the
Java programming language and are executed on the client side, meaning that the browser
needs to have a Java runtime environment (JRE) installed to execute them.
6. Applet Vs Appliation Program :
Feature Applet Application
Execution Runs inside a web browser or Runs as a standalone program on
Environment applet viewer the computer
Need for Web Yes, requires a web browser with No, it runs independently of a
Browser Java plugin browser
Deployed as part of a web page
Deployment Deployed as a .jar file or executable
(HTML)
More restricted due to security More control, fewer restrictions on
Security
concerns OS access
Access to System
Limited access to OS resources Full access to system resources
Resources
Can be embedded into a web page Can have a standalone GUI (AWT,
User Interface
with GUI (AWT or Swing) Swing, JavaFX)
Controlled by the browser (init, Controlled by the user (program
Lifecycle
start, stop, destroy) main method)
Requires a main() method to start
Main Method No main() method required
execution
Generally slower due to the Faster as it runs directly on the
Performance
browser's overhead system
Platform Depends on the browser and Java Can be run on any machine with the
Dependency plugin compatibility correct Java runtime environment
Used for interactive web content Used for standalone applications
Example Use
like games, charts, and animations like utilities, games, etc.
For internal circulation only 56
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
7. Applet Lifecycle: The applet life cycle can be defined as the process of how the object is
created, started, stopped, and destroyed during the entire execution of its application. It
basically has five core methods namely init(), start(), stop(), paint() and destroy().These
methods are invoked by the browser to execute.
Methods of Applet Life Cycle
There are five methods of an applet life cycle, and they are:
init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
start(): The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the
applet is maximized, restored, or moving from one tab to another in the browser. It is
in an inactive state until the init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage is
closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
For internal circulation only 57
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
8. Developing and running Applets
Example:
import [Link];
import [Link];
public class AppletLifecycleExample extends Applet {
// The init() method is called when the applet is first loaded
public void init() {
[Link]("init() method called: Applet initialized.");
}
// The start() method is called when the applet is started or brought to the foreground
public void start() {
[Link]("start() method called: Applet started.");
}
// The stop() method is called when the applet is stopped or moved to the background
public void stop() {
[Link]("stop() method called: Applet stopped.");
}
// The destroy() method is called when the applet is destroyed
public void destroy() {
[Link]("destroy() method called: Applet destroyed.");
}
// The paint() method is used to display text or graphics on the applet window
public void paint(Graphics g) {
[Link]("Applet Lifecycle Example", 50, 60);
}
}
HTML code:
<html>
<body>
For internal circulation only 58
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
<applet code="[Link]" width="300" height="200">
</applet>
</body>
</html>
9. String Handling and its Operations:
In Java, the String class is used to handle and manipulate sequences of characters. Java
provides a variety of methods for string manipulation, such as searching, comparing,
replacing, and extracting substrings. The String class is immutable, meaning once a String
object is created, its value cannot be changed.
Key Concepts in String Handling:
String Creation:
1. Using string literals: The string is stored in a pool.
2. Using the new keyword: The string is created in heap memory.
Example:
String str1 = "Hello"; // String literal
String str2 = new String("World"); // Using new keyword
Immutable Nature of Strings: Since String objects are immutable, any
operation that modifies a string will result in the creation of a new string
object, and the original string remains unchanged.
Example:
String str = "Hello";
str = [Link](" World"); // Creates a new string "Hello World"
Commonly Used String Methods:
Length of String:length() returns the length of the string (number of characters).
Concatenating Strings: appends one string to another.
Character at Specific Index: returns the character at the specified index.
Substring:
substring(int beginIndex): returns a new string starting from the
specified index.
substring(int beginIndex, int endIndex): returns a substring from
beginIndex to endIndex - 1.
Searching for Substring:
contains(CharSequence sequence) checks if the string contains the
specified sequence.
For internal circulation only 59
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
indexOf(String str) returns the index of the first occurrence of the
specified substring.
Replacing Characters:
replace(char oldChar, char newChar) replaces all occurrences of a
character.
replace(CharSequence target, CharSequence replacement) replaces all
occurrences of a substring.
Converting Case:
toLowerCase() converts all characters to lowercase.
toUpperCase() converts all characters to uppercase.
Trimming Whitespaces: removes any leading and trailing whitespace from the
string.
String Comparison:
equals(String anotherString) compares two strings for equality.
equalsIgnoreCase(String anotherString) compares two strings ignoring
case differences.
Splitting a String:
split(String regex) splits the string into an array of substrings based on
a regular expression.
Example Code for String Handling:
public class StringHandlingExample {
public static void main(String[] args) {
String str = " Hello World ";
// Length of the string
[Link]("Length: " + [Link]()); // Output: 13
// Trim spaces
String trimmed = [Link]();
[Link]("Trimmed: '" + trimmed + "'"); // Output: 'Hello
World'
// Convert to lowercase
String lower = [Link]();
[Link]("Lowercase: " + lower); // Output: hello world
// Substring
String sub = [Link](1, 5);
For internal circulation only 60
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
[Link]("Substring: " + sub); // Output: ello
// String concatenation
String newStr = [Link](" - Java");
[Link]("Concatenated: " + newStr); // Output: Hello
World - Java
// Replace
String replaced = [Link]("World", "Java");
[Link]("Replaced: " + replaced); // Output: Hello Java
// Split
String[] words = [Link](" ");
[Link]("Split: ");
for (String word : words) {
[Link](word); // Output: "Hello", "World"
}
}}
Output:
Length: 13
Trimmed: 'Hello World'
Lowercase: hello world
Substring: ello
Concatenated: Hello World - Java
Replaced: Hello Java
Split:
Hello
World
For internal circulation only 61
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
UNIT- IV
For internal circulation only 62
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
UNIT – IV
EXCEPTION HANDLING AND THREADS
1. Concept of Exception handling
2. Checked and Unchecked Exception
3. Try-catch and finally blocks
4. Multi-threading
5. Multi-threading Vs Multi-tasking
6. Life Cycle of thread
7. Various methods to create thread
8. Thread Synchronization
9. Advanced concepts of Java- Introduction to JavaBeans, Security Manager
10. Importance of generic programming in java
********
1 . Concept of Exception Handling
An exception is a runtime error. The compile time errors are not exceptions. Every
exception is predefined class in java. The predefined classes are part of [Link]
package and whose objects are created by JVM whenever it encounters a runtime error.
Exception Handling in Java is a mechanism that allows a program to deal with runtime
errors (exceptions) gracefully without crashing. It provides a way to respond to exceptional
conditions (like errors) during the execution of the program, ensuring the normal flow of the
application is maintained.
2 . Types of Exceptions:
Checked Exceptions:
These exceptions are checked at compile-time. The programmer is required to
handle them explicitly using try-catch blocks or declare them using the throws
keyword in method signatures.
Example: IOException, SQLException
Unchecked Exceptions (Runtime Exceptions):
These exceptions are not checked at compile-time, meaning the programmer is not
required to handle them. They usually indicate programming bugs (like logic
errors or invalid operations).
For internal circulation only 63
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
3 . Try-catch and finally block:
Java provides five keywords that are used to handle the exception.
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.
The try-catch Block
For internal circulation only 64
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
One of the primary mechanisms for handling exceptions in Java is the try-catch block.
The try block contains the code that may throw an exception, and the catch block is
used to handle the exception if it occurs. Here's a basic Example:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
Handling Multiple Exceptions
You can handle multiple types of exceptions by providing multiple catch blocks, each
catching a different type of exception. This allows you to tailor your exception
handling logic based on the specific type of exception thrown. Here's an Example:
try {
// Code that may throw an exception
} catch (IOException e) {
// Handle IOException
} catch (NumberFormatException e) {
// Handle NumberFormatException
} catch (Exception e) {
// Handle any other exceptions
The finally Block
In addition to try and catch, Java also provides a finally block, which allows you to
execute cleanup code, such as closing resources, regardless of whether an exception
occurs or not. The finally block is typically used to release resources that were
acquired in the try block. Here's an Example:
try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling code
} finally {
// Cleanup code
}
For internal circulation only 65
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Example to demonstrate Exception handling using try-catch block
public class JavaExceptionExample{
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
4 . Multi-threading: Multithreading in Java is a process of executing multiple threads
simultaneously. A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
Threads are considered a lightweight because they make use of limited resources of the
system.
Types of Threads: It is classified into two types:
User threads: User threads are the normal threads that the application creates and
runs. These threads are crucial for the program’s execution, and the JVM waits for
all user threads to finish before terminating the program.
Eg: Threads created by calling the start() method on a Thread object or by
implementing the Runnable interface.
Daemon Threads: Daemon threads are background threads that serve the purpose
of assisting or performing low-priority tasks, such as garbage collection, logging,
or monitoring system health. The JVM doesn't wait for daemon threads to finish
before terminating the program.
5 . Multi-threading Vs Multi-tasking
Aspect Multithreading Multitasking
Multitasking refers to the ability of
Definition Multithreading refers to the ability an operating system to execute
of a CPU to execute multiple multiple processes concurrently.
For internal circulation only 66
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Aspect Multithreading Multitasking
threads concurrently within a
single process.
It involves multiple threads It involves multiple independent
Scope running within a single program or programs (processes) running
process. concurrently.
Multiple threads share the same Multiple processes run in their own
Concurrency
memory space and resources of a separate memory spaces and
Level
single process. resources.
Threads within a process share the Each process operates in its own
Resource
same resources, such as memory memory space and does not directly
Sharing
and file handles. share resources with others.
Lower overhead compared to Higher overhead as each process runs
Overhead multitasking because threads share in its own memory space, requiring
resources within the same process. more resources.
Context switching between Context switching between processes
Context threads is faster because they takes more time and resources as
Switching share the same memory and each process has its own memory
resources. space.
Running multiple tasks in a Running different programs like a
Examples program (e.g., downloading files, web browser, text editor, and music
processing data simultaneously). player at the same time.
Processes communicate through
Threads can communicate easily
inter-process communication (IPC)
Communication with each other since they share
mechanisms like pipes, sockets, or
the same memory space.
shared memory.
More efficient for tasks that are
Suitable for running multiple
Efficiency closely related and need to share
unrelated applications concurrently.
data.
Multitasking uses the CPU's time by
Multithreading can improve CPU
switching between different
CPU Usage utilization by making use of idle
processes, which may not always
CPU cycles.
lead to optimal CPU usage.
An error in one process does not
An error in one thread can affect
Error Handling directly affect other processes, as
the entire process.
each process is isolated.
For internal circulation only 67
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Aspect Multithreading Multitasking
A web browser that loads multiple A user running a word processor
Example in Real
web pages in parallel (using while listening to music and
Life
different threads). browsing the web simultaneously.
6 . Life cycle of Thread: A thread in Java goes through several stages during its lifetime:
New: The thread is created but not yet started.
Runnable: The thread is ready to run and waiting for CPU time to be assigned.
Blocked: The thread is waiting for a resource (e.g., I/O operations, synchronization).
Waiting: The thread is waiting indefinitely for another thread to perform a specific
action (e.g., wait()).
Timed Waiting: The thread is waiting for a specified period (e.g., sleep()).
Terminated: The thread has finished executing.
A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant:
New State: When a new thread is created, it is in the new state. The thread has not
yet started to run when the thread is in this state. When a thread lies in the new state,
its code is yet to be run and hasn’t started to execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In this
state, a thread might actually be running or it might be ready to run at any instant of
time. It is the responsibility of the thread scheduler to give the thread, time to run.
Blocked State: The thread will be in blocked state when it is trying to acquire a
lock but currently the lock is acquired by the other thread. The thread will move
from the blocked state to runnable state when it acquires the lock.
Waiting State: The thread will be in waiting state when it calls wait() method or
join() method. It will move to the runnable state when other thread will notify or
that thread will be terminated.
Timed Waiting State: A thread lies in a timed waiting state when it calls a method
with a time-out parameter. A thread lies in this state until the timeout is completed
For internal circulation only 68
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
or until a notification is received. For example, when a thread calls sleep or a
conditional wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following reasons:
a. Because it exits normally. This happens when the code of the thread has
been entirely executed by the program.
b. Because there occurred some unusual erroneous event, like a
segmentation fault or an unhandled exception.
7. Methods to Create Threads: Basically there are Two ways to create and use threads:
Extending the Thread class:A class can extend the Thread class and override its
run() method. When the thread is started using start(), the run() method is
executed in a new thread.
Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
[Link](); // Start the thread
}
}
Implementing the Runnable interface:A class can implement the Runnable
interface and override its run() method. Then, it can be passed to a Thread object, and
the thread is started.
Example:
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
[Link](); // Start the thread
}
For internal circulation only 69
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
}
8 . Thread Synchronization: Thread Synchronization in Java is a mechanism used to control
access to shared resources by multiple threads. It is used to avoid race conditions, where two
or more threads try to update shared data simultaneously, leading to unpredictable results.
Synchronization ensures that only one thread can access a shared resource at a time,
preventing conflicting operations.
It is achieved by two ways:
Synchronized Methods: You can declare a method as synchronized to allow
only one thread to execute it at any given time.
Synchronized Blocks: You can synchronize a specific block of code within a
method to control access to a particular section of the code.
Example:
class Table {
// Synchronized method to print the table
synchronized void printTable(int n) {
for(int i = 1; i <= 5; i++) {
// Print the multiplication result
[Link](n * i);
try {
// Pause execution for 400 milliseconds
[Link](400);
} catch(Exception e) {
// Handle any exceptions
[Link](e);
class MyThread1 extends Thread {
For internal circulation only 70
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 5
[Link](5);
class MyThread2 extends Thread {
Table t;
// Constructor to initialize Table object
MyThread2(Table t) {
this.t = t;
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 100
[Link](100);
public class TestSynchronization2 {
public static void main(String args[]) {
For internal circulation only 71
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2 objects with the same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
[Link]();
[Link]();
Output:
5
10
15
20
25
100
200
300
400
500
9. Advanced Concepts in Java
Collection in Java:
The Java Collection Framework is a set of classes and interfaces that implement
commonly reusable collection data structures such as lists, sets, maps, and queues. It
provides a way to store and manipulate a group of data as a single unit.
Core Interfaces:
Collection: The root interface in the collection hierarchy.
List: An ordered collection that allows duplicates. Examples: ArrayList,
LinkedList.
Set: A collection that does not allow duplicates. Examples: HashSet, TreeSet.
Map: A collection that stores key-value pairs. Examples: HashMap, TreeMap.
Queue: A collection designed for holding elements before processing.
Examples: LinkedList, PriorityQueue.
Common Implementations:
For internal circulation only 72
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
ArrayList: Resizable array implementation of the List interface.
HashSet: Hash table-based implementation of the Set interface.
HashMap: Hash table-based implementation of the Map interface.
Utility Classes:
Collections: A class providing static methods for sorting, searching, and
synchronizing collections.
Java Bean:
A JavaBean is a reusable software component that follows a particular convention for
defining classes. It is typically used in Java applications to encapsulate data and logic
in a structured, easy-to-use way.
Key Features:
Private fields: All properties of a JavaBean must be private.
Public getters and setters: JavaBeans provide public getter and setter
methods for accessing properties.
Default constructor: JavaBeans must have a no-argument constructor.
Serializable: JavaBeans should implement the Serializable interface, which
allows them to be persisted or transferred over a network.
Example:
public class Employee implements [Link] {
private String name;
private int age;
// Default constructor
public Employee() {}
// Getter and Setter methods
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
}
For internal circulation only 73
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Security Manager:
The SecurityManager class in Java provides a framework for controlling access to
resources like files, network connections, and system properties. It is part of Java's
security architecture and is used to enforce security policies by restricting certain
operations.
Role:
The SecurityManager checks if a certain operation, such as reading a file or
establishing a network connection, is allowed based on the current security
policy.
Security policies can be defined in a policy file, which dictates which
operations are permitted.
Usage:
You can set a SecurityManager using [Link](new
SecurityManager()).
Custom security policies can be defined by extending the SecurityManager
class and overriding its methods to specify security checks.
Example:
public class CustomSecurityManager extends SecurityManager {
public void checkRead(String file) {
if ([Link]("[Link]")) {
throw new SecurityException("Access Denied to file: " + file);
}
}
}
public class SecurityManagerExample {
public static void main(String[] args) {
[Link](new CustomSecurityManager());
// This would throw a SecurityException
[Link]("Reading restricted file...");
[Link]("[Link]");
}
}
Generic Programming in Java:
Generics in Java allow classes, interfaces, and methods to operate on objects of
various types while providing compile-time type safety. Generics enable you to write
more reusable and type-safe code.
Core Concepts:
For internal circulation only 74
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Generic Classes: Classes that can operate on any data type, defined with type
parameters. Example: ArrayList<T>.
Generic Methods: Methods that can operate on objects of various types,
defined with type parameters. Example: public <T> void print(T obj).
Bounded Type Parameters: You can restrict the types that can be used with
generics. Example: <T extends Number> restricts T to be a subtype of
Number.
Advantages:
Type Safety: Generics eliminate the need for casting and catch errors at
compile time.
Code Reusability: With generics, you can write classes and methods that
work with any type.
Example:
public class GenericExample<T> {
private T value;
public GenericExample(T value) {
[Link] = value;
}
public T getValue() {
return value;
}
public static void main(String[] args) {
GenericExample<Integer> intObj = new GenericExample<>(100);
[Link]([Link]()); // Outputs: 100
GenericExample<String> strObj = new GenericExample<>("Hello");
[Link]([Link]()); // Outputs: Hello
}
}
10 . Importance of Genric Programming:
Type Safety: Generics ensure that type-related errors are caught at compile time,
preventing runtime issues like ClassCastException.
Elimination of Type Casting: With generics, explicit type casting is unnecessary,
reducing the chances of errors.
Reusability: Generics allow you to write code that works with any data type,
promoting code reusability and reducing duplication.
Improved Code Readability and Maintainability: Generics make code clearer by
specifying types explicitly, improving its readability and ease of maintenance.
Performance: By eliminating the need for type casting at runtime, generics help
improve performance.
For internal circulation only 75
Subject Name: OOPs Using Java
Faculty Name: Prof. Anjana U
Consistency: Generics ensure that collections and data structures are used
consistently with the correct types, preventing potential type mismatches.
Interoperability: Generics enable seamless integration with Java’s built-in
collections and libraries that use generics.
Increased Flexibility: Generics allow for more adaptable and flexible code that can
work with any type of data.
Code Reduction: Generics reduce the need for writing multiple versions of the same
code for different data types, leading to less code duplication.
Enhanced Debugging: Type errors are detected at compile time, making debugging
easier compared to runtime errors.
For internal circulation only 76