0% found this document useful (0 votes)
63 views118 pages

Java Programming Concepts Overview

The document provides a comprehensive overview of Java programming, covering object-oriented concepts, Java buzzwords, and the architecture of the Java Virtual Machine (JVM). It discusses key features of Java such as platform independence, simplicity, robustness, and security, as well as core OOP principles like inheritance and polymorphism. Additionally, it details Java's multithreading capabilities, exception handling, and the structure of Java applications, including user-defined classes and event handling in Swing.

Uploaded by

lydialongston
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views118 pages

Java Programming Concepts Overview

The document provides a comprehensive overview of Java programming, covering object-oriented concepts, Java buzzwords, and the architecture of the Java Virtual Machine (JVM). It discusses key features of Java such as platform independence, simplicity, robustness, and security, as well as core OOP principles like inheritance and polymorphism. Additionally, it details Java's multithreading capabilities, exception handling, and the structure of Java applications, including user-defined classes and event handling in Swing.

Uploaded by

lydialongston
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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

126C2A : JAVA PROGRAMMING

1
UNIT - 1

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

****************************************************************
Introduction to Java
Java is a class-based, object-oriented programming language that is designed to have as
few implementation dependencies as possible
Java is known for its simplicity, robustness, and security features, making it a popular choice
for enterprise-level applications. Java applications are compiled to byte code that can run on
any Java Virtual Machine. The syntax of Java is similar to C/C++.
Java makes writing, compiling, and debugging programming easy. It helps to create reusable
code and modular programs.
Key Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode
generated by the compiler. This byte code can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes.
The four main concepts of Object-Oriented programming are:
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
3. Simplicity
 Java’s syntax is simple and easy to learn, especially for those familiar with C or C+
+. It eliminates complex features like pointers and multiple inheritances, making it
easier to write, debug, and maintain code.

2
[Link]
 Java language is robust which means reliable. It is developed in such a way that
it puts a lot of effort into checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not easy to detect by another
programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation
5. Security
 In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several
security flaws like stack corruption or buffer overflow are impossible to exploit in
Java. Also, java programs run in an environment that is independent of
the os(operating system) environment which makes java programs more secure.
6. Distributed
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed
applications in java. The java programs can be easily distributed on one or more
systems that are connected to each other through an internet connection.

7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a
program. This feature is particularly useful for applications that require high
performance, such as games and real-time simulations.

8. Portability
java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to
any platform for execution makes java portable

9. High Performance
java uses Just In Time (JIT) compiler where the compiler compiles code on-demand
basis where it only compiles those methods that are called making applications to
execute faster.

3
OOPs Concepts:

 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of
properties or methods that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage
are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated. An object has an identity, state,
and behavior. Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to know the type
of message accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.

Object

4
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation. Consider a real-life
example of a man driving a car. The man only knows that pressing the accelerators will
increase the speed of the car or applying brakes will stop the car, but he does not know about
how on pressing the accelerator the speed is increasing, he does not know about the inner
mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is
what abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. In Encapsulation, the variables or data of
a class are hidden from any other class and can be accessed only through any member
function of their class in which they are declared. As in encapsulation, the data in a class is
hidden from other classes, so it is also known as data-hiding.

Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section, etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly access the
data of the sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here the data
of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.

5
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When
we write a class, we inherit properties from other classes. So when we create a class, we do
not need to write all the properties and functions again and again, as these can be inherited
from another class that possesses it. Inheritance allows the user to reuse the code whenever
possible and reduce its redundancy.

6. Polymorphism:

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the same
time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.

6
7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at
runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main
advantages of inheritance is that some derived class D has all the members of its base class B.
Once D is not hiding any of the public members of B, then an object of D can represent B in
any context where a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information
to each other. A message for an object is a request for execution of a procedure and therefore
will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the
information to be sent.

Why do we need object-oriented programming


 To make the development and maintenance of projects more effortless.
 To provide the feature of data hiding that is good for security concerns.
 We can solve real-world problems if we are using object-oriented programming.
 It ensures code reusability.

7
 It lets us write generic code: which will work with a range of data, so we don’t have
to write basic stuff over and over again.
Java Buzzwords
The Java programming language can be characterized by the following buzzwords:
1. Simple
2. Object-Oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-Neutral
8. Portable
9. High Performance
10. Multithreaded
11. Dynamic
1. Simple
 Java is designed to be easy for beginners and professional programmers to learn and
use effectively.
 It’s simple and easy to learn if you already know the basic concepts of Object-
Oriented Programming.
 Java has removed many complicated and rarely-used features, such as explicit
pointers and operator overloading.
2. Object-Oriented
 Everything in Java revolves around objects and classes.
 Java allows you to model real-world entities (like a car or a bank account) as objects
in your program, making it easier to manage and build complex applications.
 Key Object-Oriented Programming (OOP) concepts include:
o Object: An instance of a class.
o Class: A blueprint for creating objects.
o Inheritance: Allows one class to inherit the properties of another.
o Polymorphism: The ability of objects to take on multiple forms.
o Abstraction: Hides the complex details and shows only the essentials.
o Encapsulation: Keeps the data safe by restricting access to it.

8
9
3. Distributed
 Java is designed to create distributed applications on networks.
 Java applications can access remote objects on the Internet as easily as they can do in
the local system.
 Java enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
4. Compiled and Interpreted
 Java combines both compiled and interpreted approaches, making it a two-stage
system.
 Compiled: Java compiles programs into an intermediate representation called Java
Bytecode.
 Interpreted: Bytecode is then interpreted, generating machine code that can be
directly executed by the machine that provides a JVM.
5. Robust
 Java provides many features that make programs execute reliably in a variety of
environments.
 Java is a strictly typed language that checks code at compile time and runtime.
 Java handles memory management with garbage collection and captures serious errors
through exception handling.
6. Secure
 Java does not use pointers, which helps prevent unauthorized memory access.
 The JVM verifies Java bytecode before execution, ensuring that it adheres to Java’s
security constraints.
 Java applications run in a restricted environment (sandbox) that limits their access to
system resources and user data, enhancing security.
7. Architecture-Neutral
 Java language and JVM help achieve the goal of “write once; run anywhere, any time,
forever.”
 Changes and upgrades in operating systems, processors, and system resources do not
force any changes in Java programs.
8. Portable
 Java provides a way to download programs dynamically to various types of platforms
connected to the Internet.

10
 Java is portable because of the JVM, which provides a consistent runtime
environment across different platforms.
9. High Performance
 Java performance is high because of the use of bytecode.
 The bytecode can be easily translated into native machine code.
10. Multithreaded
 Multithreaded programs handle multiple tasks simultaneously, which is helpful in
creating interactive, networked programs.
 Java run-time system supports multiprocess synchronization for constructing
interactive systems.
11. Dynamic
 Java can link in new class libraries, methods, and objects dynamically.
 Java programs carry substantial amounts of run-time type information, enabling
dynamic linking in a safe and expedient manner.
How JVM Works – JVM Architecture
What is JVM?
JVM stands for Java Virtual Machine. It is essentially a virtual machine or runtime
environment that allows Java programs to run and operate on multiple devices and operating
systems.
Java programs cannot run on machines that don’t have JVM support. It is an integral part of
the Java Runtime Environment (JRE). JVM features many specifications that work together
to run Java programs. It is platform-dependent by nature, i.e., every operating system has a
different JVM.
JVM Architecture
There are three notions of JVM in Java:
 Implementation,
 Specification,
 Instance.
Implementation: Also known as JRE (Java Runtime Environment).
Specification: A document that describes the requirements for JVM implementation.
Instance: A JVM instance is created whenever you run a java class file.
JVM architecture can be divided into three major subsystems:
 ClassLoader
 Memory area / Runtime memory

11
 Execution engine
ClassLoader:
JVM loads the compiled .class files to run Java applications, and to perform this action; a
JVM relies on its ClassLoader.
Method area
There is only one method area per JVM, and this runtime area is common to all threads. It
stores the structure of each class, such as class name, method data, methods, variables
information, etc.
Heap
The Heap memory area stores the object and its instance variable. Every time you create an
object in Java, it gets moved into the heap. The Heap area denotes a shared memory area.
Stack
Stack (also known as thread stack) is a data area within the JVM memory created for one
execution thread.
JVM stacks stores partial results, local variables, and data for method invocations and returns.
PC register
The PC register stores the address of the Java Virtual Machine instruction address currently
being executed. Each thread is assigned a separate PC register.
Native method stack
It contains all native methods needed for an application. Native methods use languages other
than Java.

Structure of Java Program

12
1. Class Declaration:
 Every Java program is built around classes, which act as blueprints for creating
objects.
 A class defines the properties (data) and behaviors (methods) of objects.
 Example: public class MyClass { ... }
2. Objects:
 Objects are instances of classes, representing real-world entities or concepts.
 You create objects using the new keyword: MyClass myObject = new MyClass();
3. Methods:
 Methods are blocks of code that perform specific actions or operations.
 They can take input (parameters) and return output (return type).
 Example: public int add(int a, int b) { return a + b; }
4. main Method:
 The main method is the entry point for program execution.
 It's a special method with the signature: public static void main(String[] args).
 The program starts executing from the code within the main method.
5. Packages and Imports:

13
 Packages: Organize classes into logical groups, preventing naming conflicts and
improving code organization.
 Import Statements: Allow you to use classes from other packages without having to
specify their full names.
 Example: import [Link];
6. Comments:
 Comments are used to explain the code and are ignored by the compiler.
 Single-line comments start with //.
 Multi-line comments are enclosed in /* ... */.
7. Basic Syntax:
 Statements in Java end with a semicolon (;).
 Code blocks are enclosed in curly braces ({ ... }).
 Identifiers (names for classes, variables, methods) follow specific rules (e.g., cannot
start with a digit).
8. Object-Oriented Programming (OOP) Concepts:
 Java is an object-oriented programming language, meaning it relies heavily on classes
and objects.
 Key OOP concepts include:
o Encapsulation: Bundling data and methods that operate on that data within a
class.
o Inheritance: Allowing classes to inherit properties and methods from other
classes.
o Polymorphism: Enabling objects of different classes to be treated as objects
of a common type.

A basic Java program consists of several components that create a functional application. We
can learn about basic Java Syntax using the following program:
// FileName : "[Link]".
public class Geeks {

// Program begins with a call to main() method


// main method is the entry point of a Java Program
public static void main(String args[])

14
{

// Prints "Hello World" to the console


[Link]("Hello World");
}
}

Output
Hello World
Syntax of main() Method
Syntax of the main() method is always written as:

1. Public
It is an Access modifier, which specifies from where and who can access the method.
Making the main() method public makes it globally available. It is made public so that JVM
can invoke it from outside the class as it is not present in the current class.
2. Static
It is a keyword that is when associated with a method, making it a class-related method.
The main() method is static so that JVM can invoke it without instantiating the class. This
also saves the unnecessary wastage of memory which would have been used by the object
declared only for calling the main() method by the JVM.
3. Void
It is a keyword and is used to specify that a method doesn’t return anything. As
the main() method doesn’t return anything, its return type is void. As soon as
the main() method terminates, the Java program terminates too. Hence, it doesn’t make any
sense to return from the main() method as JVM can’t do anything with its return value of it.

15
4. main
It is the name of the Java main method. It is the identifier that the JVM looks for as
the starting point of the Java program. It’s not a keyword.
If we change the name while initiating main method, we will get an error.
Example:
5. String[] args
It stores Java command-line arguments and is an array of type [Link] class.
Here, the name of the String array is args but it is not fixed and the user can use any name in
place of it.
JAVA CONSOLE OUTPUT([Link])
[Link] in Java
Java [Link]() is used to print an argument that is passed to it.
Parts of [Link]()
The statement can be broken into 3 parts which can be understood separately:
1. System: It is a final class defined in the [Link] package.
2. out: This is an instance of PrintStream type, which is a public and static member field
of the System class.
3. println(): As all instances of the PrintStream class have a public method println(), we
can invoke the same on out as well. This is an upgraded version of print(). It prints
any argument passed to it and adds a new line to the output. We can assume that
[Link] represents the Standard Output Stream.

Example of Java [Link]()


Example 1:

16
Below is the implementation of [Link] :
import [Link].*;

class GFG {
public static void main(String[] args)
{
[Link]("Welcome");
[Link]("To");
[Link]("GeeksforGeeks");
}
}

Output
Welcome
To
GeeksforGeeks

Java Data Types


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.
The Boolean with uppercase B is a wrapper class for the primitive data type boolean
in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

17
18
Primitive Data Types

1. boolean Data Type


he boolean data type represents a logical value that can be either true or false.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)

2. byte Data Type


The byte data type is an 8-bit signed two’s complement integer
Syntax:
byte byteVar;
Size : 1 byte (8 bits)

3. short Data Type


The short data type is a 16-bit signed two’s complement integer.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)

4. int Data Type


It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )

5. long Data Type


The long data type is a 64-bit signed two’s complement integer.
Syntax:
long longVar;
Size : 8 bytes (64 bits)

6. float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating-point.

19
Syntax:
float floatVar;
Size : 4 bytes (32 bits)

7. double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating-point.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)

8. char Data Type


The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)

Java Variables
Variables are the containers for storing the data values or you can also call it a memory
location name for the data. Every variable has a:
 Data Type – The kind of data that it can hold. For example, int, string, float, char, etc.
 Variable Name – To identify the variable uniquely within the scope.
 Value – The data assigned to the variable.
There are three types of variables in Java – Local, Instance, and Static.
Example:
int age = 27; // integer variable having value 27

String name = "gfg" // string variable


TYPE CONVERSION and TYPE CASTING
There are two ways we can change the type from one to another.
1. Type casting
2. Type conversion
Type Casting means to change one state to another state and is done by the programmer
using the cast operator. Type Casting is done during the program design time by the
programmer. Typecasting also refers to Narrow Conversion.

20
Because in many cases, We have to Cast large datatype values into smaller datatype values
according to the requirement of the operations. We can also convert large datatype values
into smaller datatype values that’s why Type Casting called Narrow Casting.

Syntax: () is Cast Operator

RequiredDatatype=(TargetType)Variable

Type Conversion is a type conversion that is done by compiler done by a compiler without
the intention of the programmer during the compile time. This Conversion sometimes creates
an error or incorrect answer if the proper resultant data type does not mention at the end of
the multiple expression of the datatype that’s why Type Conversion is less efficient than Type
Casting.
The working mechanism of type conversion is as follows:
double > float > long > int > short > byte

JAVA CONSOLE INPUT: BUFFERED INPUT


Ways to Read Input from Console in Java
In Java, there are four different ways to read input from the user in the command line
environment(console).
1. Using Buffered Reader Class
Buffered Reader Class is the classical method to take input, Introduced in JDK 1.0. This
method is used by wrapping the [Link] (standard input stream) in an InputStreamReader
which is wrapped in a BufferedReader, we can read input from the user in the command line.
 The input is buffered for efficient reading.
 The wrapping code is hard to remember.
[Link] DataInputStream Class
DataInputStream class in Java, introduced in JDK 1.0, is used to read
primitive data types like int, float, boolean, and strings from an input stream in a
way that works across different machines. It is part of the [Link] package and wraps
an existing input stream. It’s commonly used with DataOutputStream or similar
sources to ensure the data is read correctly.

21
Java Operators

Java operators are special symbols that perform operations on variables or values. They can
be classified into several categories based on their functionality
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-
primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate a
value.
 - , Negates the value.
 + , Indicates a positive value (automatically converts byte, char, or short to int).
 ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
 -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
 ! , Inverts a boolean value.

22
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable.
The general format of the assignment operator is:
variable = value;
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less than.
Relational operators compare values and return boolean results:
 == , Equal to.
 != , Not equal to.
 < , Less than.
 <= , Less than or equal to.
 > , Greater than.
 >= , Greater than or equal to.
5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR” operations,
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is ,
condition ? if true : if false

7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a number and
with any of the integer types. They are used when performing update and query operations of
the Binary indexed trees.
 & (Bitwise AND) – returns bit-by-bit AND of input values.
 | (Bitwise OR) – returns bit-by-bit OR of input values.
 ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
 ~ (Bitwise Complement) – inverts all bits (one’s complement).
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right

23
 << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
 >> (Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with
the leftmost bit depending on the sign.
 >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always
0
9. instanceof operator
The instance of operator is used for type checking. It can be used to test if an object is an
instance of a class, a subclass, or an interface. The general format ,
object instance of class/subclass/interface

CONTROL STRUCTURES IN JAVA

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:
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

24
3. if-else-if ladder
4. Nested if-statement
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.
if(condition) {
statement 1; //executes when condition is true
}

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
}

25
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.
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
}

26
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
}
}

27
Loop Statements
In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop

1. for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code.
for(initialization, condition, increment/decrement) {
//block of statements
}

28
Java while loop
The while loop is also used to iterate over the number of statements multiple times
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.

29
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.
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);

Jump Statements
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.
Example
1. public class Main {
2. public static void main(String[] args) {
3. for(int i = 0; i<= 10; i++) {
4. [Link](i);

30
5. if(i==6) {
6. break;
7. }
8. }
9. }
10. }

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.
Example
1. public class Main {
2. public static void main(String[] args) {
3. for(int i = 0; i<= 2; i++) {
4.
5. for (int j = i; j<=5; j++) {
6.
7. if(j == 4) {
8. continue;
9. }
10. [Link](j);
11. }
12. }
13. }
14. }
Static Keyword in Java
The static keyword in Java is mainly used for memory management. The static keyword in
Java is used to share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes.
The static keyword is a non-access modifier in Java that is applicable for the following:
1. Blocks
2. Variables
3. Methods
4. Classes

31
Static variables
When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at the class level. Static variables are, essentially, global variables.
All instances of the class share the same static variable.
Important points for static variables:
 We can create static variables at the class level only.
 static block and static variables are executed in the order they are present in a
program.
Static methods
When a method is declared with the static keyword, it is known as the static method.
The most common example of a static method is the main( ) method. As discussed
above, Any static member can be accessed before any objects of its class are created,
and without reference to any object. Methods declared as static have several
restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.

StringBuffer class in Java


StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing you to modify the contents of a string
without creating a new object every time.
Features of StringBuffer Class
Here are some important features and methods of the StringBuffer class:
 StringBuffer objects are mutable, meaning that you can change the contents of the
buffer without creating a new object.
 The initial capacity of a StringBuffer can be specified when it is created, or it can be
set later with the ensureCapacity() method.
 The append() method is used to add characters, strings, or other objects to the end of
the buffer.
 The insert() method is used to insert characters, strings, or other objects at a specified
position in the buffer.

32
Methods of Java StringBuffer Class

Methods Action Performed

append() Used to add text at the end of the existing text.

The length of a StringBuffer can be found by the length( )


length()
method.

the total allocated capacity can be found by the capacity( )


capacity()
method.

This method returns the char value in this sequence at the


charAt()
specified index.

delete() Deletes a sequence of characters from the invoking object.

deleteCharAt() Deletes the character at the index specified by the loc.

ensureCapacity() Ensures capacity is at least equal to the given minimum.

insert() Inserts text at the specified index position.

length() Returns the length of the string.

reverse() Reverse the characters within a StringBuffer object.

Replace one set of characters with another set inside a


replace()
StringBuffer object.

33
StringBuffer Class

 [Link] extends (or inherits from) Object class.


 All Implemented Interfaces of StringBuffer class: Serializable, Appendable,
CharSequence.
 public final class StringBuffer extends Object implements Serializable,
CharSequence, Appendable.
 String buffers are safe for use by multiple threads. The methods can be synchronized
wherever necessary so that all the operations on any particular instance behave as if
they occur in some serial order.

Difference between String and StringBuffer in Java


Below is a table showing the differences between String and StringBuffer in Java
Aspect String StringBuffer

Immutable - once created, its Mutable - can be modified after it is


Mutability
value cannot be changed. created.

Less efficient in cases where many More efficient for frequent


Performanc
modifications are needed, as each modifications, as it doesn't create new
e
modification creates a new string. instances on modification.

StringBuffer is thread-safe and


Thread Strings are inherently thread-safe
synchronized, ensuring safe use in
Safety due to immutability.
multi-threaded environments.

Consumes more memory when Consumes less memory in a scenario of


Memory
altered frequently because every frequent alterations as it modifies the
Usage
alteration creates a new instance. same instance.

Limited to operations that don't Provides methods for altering the


alter the strings, content,
Methods
like concat(), substring(), replace() like append(), insert(), delete(), reverse()
, which all return new strings. , directly altering the buffer.

34
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 Class
A Java classes is a blueprint or template used to create object. It serves as a fundamental
building block in Java programming, encapsulating data (fields) and behaviors (methods) into
a single unit.
a Java class defines the structure and behavior of objects, serving as a blueprint for creating
instances of that class.
Properties of Java Classes
 A Java class serves as a blueprint for creating objects and doesn’t take up memory.
 It comprises variables of various types and methods. You can include data members,
methods, constructors, nested classes, and interfaces within a class.
 It acts as a template for organizing and defining the behaviour of objects in your
program.
Syntax of Java Classes
package [Link];
import [Link];
public class MyClass {
private int age;
public MyClass(int age) {
[Link] = age;
}
public void display() {
[Link]("Age: " + age);
}
}

35
This syntax defines a class named MyClass in the [Link] package, with a
private field age, a constructor that initializes age, and a method display() to print the age.

Components of Java Class


In Java, a class serves as a blueprint for creating objects. It encapsulates data and
behavior into a single unit. Here are the main components of a Java class:
 Class Declaration: The class declaration defines the name of the class and any
inheritance or interfaces it implements.
public class MyClass {
// class body
}
 Fields (Instance Variables): Fields represent the state or attributes of objects created
from the class.
private int age;
 Constructors: Constructors initialize objects of the class. They have the same name
as the class and are called when objects are created.
public MyClass(int age) {
[Link] = age;
}
 Methods define the behavior or actions that objects of the class can perfor
public void display() {
[Link]("Age: " + age);
}
 Access Modifiers: Access modifiers control the accessibility of class members
(fields, constructors, methods).
public class MyClass {
private int age;
public MyClass(int age)
[Link] = age;
}
public void display() {
[Link]("Age: " + age);
}
}

Rules for creating a class


In order to create a class, these rules must be followed-
 The “class” keyword should be used.
 The name of the class should start with an uppercase letter.

36
 The Java file can contain any number of classes but should not have more than one
public class. The file name should be named after the public class followed by the
“.java” extension.
 One class should only inherit another single class.

Types of classes
There are two types of classes-
1. Built-in classes
2. User-defined classes

 Built-in classes- The built-in classes are those which are pre-defined by the
developers in JDK.
Examples include-
[Link]
[Link]

 User-defined classes- So as the name suggests, user-defined classes are the classes
created by the user. We can add our functionality to the classes.

Java Objects

 A Java object is an instance of a class. It represents a specific realization of the class


blueprint, with its own unique set of data values for the fields defined in the class.
 Objects are created using the new keyword followed by the class name, along with
any required arguments to initialize the object’s state. Each object created from a class
has its own separate memory space allocated for its fields, allowing it to maintain its
own state independent of other objects created from the same 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.

Syntax of an object
The syntax for creating an object in Java is:
ClassName objectName = new ClassName();
Car myCar = new Car();

37
Here, Car is the class name, myCar is the object name, and new Car() instantiates a new
object of the Car class.
Initializing an object
In Java, we can initialize objects in 3 ways-
 By reference variable
 By method
 By constructor
By reference variable– Initialization of an object means storing the data in the object.
Let us understand this with an example-
public class MyClass {
public static void main(String[] args) {
// Initialize the object by reference variable in a single line
MyClass myObject = new MyClass();
// Access methods or fields of the object
[Link]();
}
public void myMethod() {
[Link]("Object initialized successfully!");
}
}

38
Difference Between Java Classes and Object

Arrays in Java
What is an Array in Java?

An array refers to a data structure that contains homogeneous elements. This means
that all the elements in the array are of the same data type. Let's take an example:

There are three main features of an array:

1. Dynamic allocation: In arrays, the memory is created dynamically, which reduces the
amount of storage required for the code.
2. Elements stored under a single name: All the elements are stored under one name.
This name is used any time we use an array.
3. Occupies contiguous location: The elements in the arrays are stored at adjacent
positions. This makes it easy for the user to find the locations of its elements.

Advantages of Arrays in Java


 Java arrays enable you to access any element randomly with the help of indexes
 It is easy to store and manipulate large data sets
Disadvantages of Arrays in Java
 The size of the array cannot be increased or decreased once it is declared—arrays
have a fixed size
 Java cannot store heterogeneous data. It can only store a single type of primitives

39
Now that we understand what Java arrays are- let us look at how arrays in Java are
declared and defined.

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:


String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it,
you can place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

You can access an array element by referring to the index number.


This statement accesses the value of the first element in cars:

Example:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


[Link](cars[0]);
// Outputs Volvo

Change an Array Element

To change the value of a specific element, refer to the index number:


Example
cars[0] = "Opel";

Array Length
To find out how many elements an array has, use the length property:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


[Link]([Link]);
// Outputs 4

40
Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of
the program. These are:
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row. For example:

In this example, we have an array of five elements. They are stored in a single line or
adjacent memory locations.

Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We
use a for loop to print the elements of the array. The output of this is as follows:

41
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:

In this, the array has two rows and five columns. The index starts from 0,0 in the left-
upper corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three
columns. Brackets separate the rows, and the number of elements separates the
columns. For this, we use two for loops: one for rows and one for each element in the
row. When we execute this program, the result will be as follows:

3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more
than two rows and columns using the following code:

42
Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will
always be two.
The above program will add all the elements defined in my_array[] and produce the
result.

Constructors in Java
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 the constructor, memory for the
object is allocated in the memory. It is a special type of method that is used to
initialize the object. Every time an object is created using the new() keyword, at least
one constructor is called.
Syntax
public class MyClass {
// Constructor
public MyClass() {
// Initialization code goes here
}

// Other methods and variables can be defined here


}

Rules for creating Java constructor


There are two rules defined for the constructor.
1. The 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

43
Types of Java Constructors

 Default constructor: These constructors do not accept any parameters.


 Parameterized constructor: These constructors accept a specific number of
parameters.
Default Constructor
 In Java, if a class does not explicitly define any constructors, the compiler
automatically provides a default constructor. This default constructor is parameterless
(i.e., it takes no arguments) and initializes member variables to their default values.
 Here’s an example of a default constructor in Java:

public class MyClass {


private int myInt;
private String myString;
// This class does not define any constructors
public static void main(String[] args) {
// Creating an object of MyClass using the default constructor
MyClass obj = new MyClass();
// Accessing member variables
[Link]("Default value of myInt: " + [Link]);
// Output: Default value of myInt: 0
[Link]("Default value of myString: " + [Link]);
// Output: Default value of myString: null
}
}

Parameterized Constructor

A parameterized constructor in Java is a constructor that accepts one or more


parameters, allowing you to initialize objects with specific values. Unlike the default

44
constructor, which takes no arguments, a parameterized constructor allows you to pass
values at the time of object creation to set initial states.
Here’s an example of a parameterized constructor in Java:

public class MyClass {


private int myInt;
private String myString;

// Parameterized constructor
public MyClass(int intValue, String stringValue) {
myInt = intValue;
myString = stringValue;
}

// Method to display values


public void displayValues() {
[Link]("myInt: " + myInt);
[Link]("myString: " + myString);
}

public static void main(String[] args) {


// Creating an object of MyClass using the parameterized constructor
MyClass obj = new MyClass(10, "Hello");

// Displaying the initialized values


[Link]();
}
}

Constructor Overloading in Java

In Java, constructors are similar to methods but without a return type. They can be
overloaded, just like methods, allowing for the creation of multiple constructors with
different parameter lists. Each constructor can serve a distinct purpose, with the
compiler distinguishing them based on the number and types of parameters they
accept. This technique, known as constructor overloading, enables flexibility in
initializing objects based on varying sets of input parameters.

class Dogs {

private String name;


private String breed;

public Dogs() {
// No initialization parameters
}

45
public Dogs(String breed) {
[Link] = breed;
}

public Dogs(String name, String breed) {


[Link] = name;
[Link] = breed;
}

void isRunning(int runStatus) {


if (runStatus == 1) {
[Link]("Dog is running");
} else {
[Link]("Dog is not running");
}
}

public class Main {

public static void main(String[] args) {


Dogs dog1 = new Dogs();
Dogs dog2 = new Dogs("Bulldog");

[Link](0);
[Link]("Woof");

// A dog with both name and breed initialized at the time of object creation.
Dogs dog3 = new Dogs("Snoopy", "German Shepherd");
}
}

Output:
Dog is not running
Dog is wagging its tail

Copy Constructor in Java

A Copy Constructor in Java is used to create an object with the help of another object
of the same Java class.

46
The copy constructor has at least one object of the same class as an argument. The
primary objective of the copy constructor is to create a new object with the same
properties as that of the passed argument.

public class MyClass {


private int myInt;
private String myString;

// Copy constructor
public MyClass(MyClass original) {
[Link] = [Link];
[Link] = [Link];
}

// Parameterized constructor
public MyClass(int intValue, String stringValue) {
[Link] = intValue;
[Link] = stringValue;
}

// Method to display values


public void displayValues() {
[Link]("myInt: " + myInt);
[Link]("myString: " + myString);
}

public static void main(String[] args) {


// Creating an object of MyClass
MyClass originalObj = new MyClass(10, "Hello");

// Creating a copy of originalObj using the copy constructor


MyClass copiedObj = new MyClass(originalObj);

// Displaying values of both objects


[Link]("Original Object:");
[Link]();

[Link]("nCopied Object:");
[Link]();
}
}

Java Inheritance (Subclass and Superclass)

47
In Java, it is possible to inherit attributes and methods from one class to another. We
group the "inheritance concept" into two categories:
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object
[Link]();

// Display the value of the brand attribute (from the Vehicle class) and the value of
the modelName from the Car class
[Link]([Link] + " " + [Link]);
}
}

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
final class Vehicle {
...
}

class Car extends Vehicle {


...
}

The 5 types of inheritance related to Java are given below:


 Single-level inheritance
 Multi-level Inheritance
 Hierarchical Inheritance

48
 Multiple Inheritance
 Hybrid Inheritance

49
1. Single-level inheritance
Single-level inheritance in Java is a fundamental concept where a subclass inherits
from only one superclass. This means that the subclass can acquire the properties and
methods of the superclass, enabling code reuse and the extension of existing
functionality.

A graphical illustration of single-level inheritance is given below:

2. Multi-level Inheritance
Multilevel inheritance in Java is a feature that allows a class to inherit properties
and behaviours from another class, which in turn inherits from another class, forming
a "chain" of inheritance. This mechanism enables a class to inherit methods and fields
from multiple ancestors but in a direct line, where each class in the chain inherits from
one class directly above it.

A graphical illustration of multi-level inheritance is given below:

3. Hierarchical Inheritance
Hierarchical inheritance in Java occurs when one base class (superclass) is
inherited by multiple subclasses. In this type of inheritance, all the features that are
common in child classes are included in the base class. This way, the code becomes
more manageable and reusable.

50
A graphical illustration of hierarchical inheritance is given below:

4. Multiple Inheritance
Multiple inheritance refers to a feature in object-oriented programming where a
class can inherit properties and methods from more than one parent class. This
concept allows a subclass to inherit behaviours and attributes from multiple base (or
super) classes, creating a rich, multifaceted hierarchy.

A graphical illustration of multiple inheritance is given below:

Instead of multiple inheritance for classes, Java provides a mechanism to achieve


polymorphism and code reuse through interfaces.

An interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructor methods.

A class in Java can implement multiple interfaces, allowing it to inherit abstract


methods from multiple sources.

51
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance, such as
hierarchical, multiple, multilevel, or single inheritance. It integrates various
inheritance mechanisms to achieve a specific design or functionality

A graphical illustration of hybrid inheritance is given below:

Java Access Modifiers

What are Access Modifiers?


In Java, access modifiers are used to set the accessibility (visibility)
of classes, interfaces, variables, methods, constructors, data members, and the setter
methods.

Types of Access Modifier

Modifier Description

declarations are visible only


Default within the package (package
private)

declarations are visible within the


Private
class only

declarations are visible within the


Protected
package or all subclasses

declarations are visible


Public
everywhere

52
53
Public Access Modifier

When methods, variables, classes, and so on are declared public, then we can access
them from anywhere. The public access modifier has no scope restriction.

// [Link] file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
[Link]("I am an animal.");
[Link]("I have " + legCount + " legs.");
}
}

// [Link]
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


[Link] = 4;
// accessing the public method
[Link]();
}
}

Output:
I am an animal.
I have 4 legs.

Private Access Modifier

When variables and methods are declared private, they cannot be accessed outside of
the class.

For example,
class Data {
// private variable
private String name;
}

54
public class Main {
public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


[Link] = "Programiz";
}
}

Output:
The name is Programiz

Protected Access Modifier

When methods and data members are declared protected, we can access them within
the same package as well as from subclasses.

For example,

class Animal {
// protected method
protected void display() {
[Link]("I am an animal");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
[Link]();
}
}

Output:
I am an animal
Default Access Modifier

If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered.

package defaultPackage;

55
class Logger {
void message(){
[Link]("This is a message");
}
}

Usage of Super and This Keywords in Java

“Super” Keyword in Java


In Java, the super keyword is a reference variable that refers to the
immediate superclass/parent class objects if using the keyword inside the child
class.

Uses of super Keyword in Java:

 Access Parent Class Variables: When a child class has a variable with the same
name as its parent class, super helps access the parent’s variable.
 Call Parent Class Methods: If a child class overrides a method from its parent, super
allows calling the parent class’s version of the method.
 Invoke Parent Class Constructor: super() can be used to call the parent class
constructor from a child class constructor.
 Differentiate Between Parent and Child Class Members: It helps when both parent
and child classes have members with the same name.
 Improve Code Reusability: By using super, we can reuse parent class functionalities
instead of rewriting code in the child class.

Syntax
super();
[Link]();
[Link];

1. Calling Superclass Constructor

In this example, the super() call in the Dog constructor invokes the constructor of
the Animal class.
Example 1: Calling Superclass Constructor
class Animal {

class Animal {
Animal() {
[Link]("Animal constructor called");
}
}

class Dog extends Animal {


Dog() {

56
super(); // Calls the constructor of Animal class
[Link]("Dog constructor called");
}
}

public class TestSuper {


public static void main(String[] args) {
Dog d = new Dog(); // Output: Animal constructor called
// Dog constructor called
}
}

Example 2: Accessing Superclass Method

Here, the [Link]() call in the Dog class method sound() invokes
the sound() method of the Animal class.

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link](); // Calls the sound() method of Animal class
[Link]("Dog barks");
}
}

public class TestSuper {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Output: Animal makes a sound
// Dog barks
}
}

Example 3: Accessing Superclass Field

In this example, [Link] is used to access the color field of the Animal class,
which is hidden by the color field in the Dog class.

class Animal {

57
String color = "white";
}
class Dog extends Animal {
String color = "black";

void displayColor() {
[Link]("Dog color: " +// Prints the color of Dog class
[Link]("Animal color: " + super.// Prints the color of Animal class
}
}
public class TestSuper {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Output: Dog color: black
// Animal color: white
}

this keyword:
It is a reserved keyword in Java that is used to refer to the current class object. It is a
reference variable through which the method is called. Other uses of this keyword are:
o We can use it to refer current class instance variable.
o We can use it to invoke the current class method (implicitly).
o We can pass it as an argument in the method and constructor calls.
o We can also use it for returning the current class instance from the method.

Difference Between this and super keyword


o The following table describes the key difference between this and super:

this super

The current instance of the class is The current instance of the parent class is
represented by this keyword. represented by the super keyword.

In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.

It can be referred to from a static context. It It can't be referred to from a static context. It
means it can be invoked from the static means it cannot be invoked from a static
context. context.

We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.

58
Java Method Overriding
Method overriding allows us to achieve run-time polymorphism and is used for writing
specific definitions of a subclass method that is already defined in the superclass.
The method is superclass and overridden method in the subclass should have the same
declaration signature such as parameters list, type, and return type.
Usage of Java Method Overriding
Following are the two important usages of method overriding in Java:
 Method overriding is used for achieving run-time polymorphism.
 Method overriding is used for writing specific definition of a subclass method (this
method is known as the overridden method).
Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level.
For example: If the superclass method is declared public then the overridding method
in the sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared
public or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However, the overriding method should
not throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions
than the overridden method.
 Constructors cannot be overridden.

59
Java Method Overriding: Using the super Keyword
Example: Using the super Keyword

class Animal {
public void move()
{
[Link]("Animals can move");
}
}
class Dog extends Animal { public void move()
{
[Link]();
// invokes the super class method
[Link]("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[])
{
Animal b = new Dog();
// Animal reference but Dog object
[Link]();
// runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run

60
Java Method Overloading
In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here are different ways to perform method overloading:
1. Overloading by changing the number of parameters
class MethodOverloading {
private static void display(int a){
[Link]("Arguments: " + a);
}

private static void display(int a, int b){


[Link]("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}
Output:
Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of parameters
class MethodOverloading {

// this method accepts int

61
private static void display(int a){
[Link]("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
[Link]("Got String object.");
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}
Output:
Got Integer data.
Got String object.
Here, both overloaded methods accept one argument. However, one accepts the argument of
type int whereas other accepts String object.

Important Points
 Two or more methods can have the same name inside the same class if they accept
different arguments. This feature is known as method overloading.
 Method overloading is achieved by either:
o changing the number of arguments.
o or changing the data type of arguments.
 It is not method overloading if we only change the return type of methods. There must
be differences in the number of parameters.

62
Difference between method overloading and method overriding:

Java Abstraction
Abstract Classes and Methods
The abstract keyword is a non-access modifier, used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal {

public abstract void animalSound();

public void sleep() {

63
[Link]("Zzz");

Java Polymorphism
Polymorphism in Java is a core concept of object-oriented programming (OOP) that allows
objects to be treated as instances of their parent class. It facilitates flexibility and the ability to
define methods in multiple forms. Polymorphism is primarily achieved through method
overriding and method overloading.
Usage
Polymorphism is used to perform a single action in different ways. It allows for the
implementation of dynamic method dispatch, where the method to be executed is determined
at runtime. This is beneficial for implementing a cleaner and more maintainable codebase.
Types of Polymorphism
1. Compile-time Polymorphism (Method Overloading): Achieved by defining
multiple methods with the same name but different parameters within the same class.
2. Runtime Polymorphism (Method Overriding): Achieved when a subclass provides
a specific implementation of a method already defined in its superclass.

Examples
Example 1: Method Overloading

public class OverloadingExample {


public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
OverloadingExample obj = new OverloadingExample();
[Link]("Sum of integers: " + [Link](5, 10));
[Link]("Sum of doubles: " + [Link](5.5, 10.5));

64
}
}
In this example, the add method is overloaded with two different parameter lists. The
appropriate method is called based on the arguments passed.
Example 2: Method Overriding
class Animal {
public void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
[Link]("Dog barks");
}
}
public class OverridingExample {
public static void main(String[] args) {
Animal myAnimal = new Dog();
[Link](); // Outputs "Dog barks"
}
}
Here, the Dog class overrides the sound method of the Animal class. The sound method of
the Dog class is invoked at runtime.
final Keyword in Java
The final keyword in Java is a non-access modifier that can be applied to variables, methods,
and classes. It is used to restrict the user from further modifying the entity to which it is
applied. This keyword plays a crucial role in ensuring immutability and preventing
inheritance or method overriding.
Usage:
1. final Variables
A final variable is a constant; once initialized, its value cannot be changed.

65
final int MAX_VALUE = 100;
Initialization of final Variables
A final variable must be initialized when it is declared or within a constructor if it is an
instance variable.
public class FinalInitialization {
final int MAX_VALUE;

public FinalInitialization() {
MAX_VALUE = 100;
}
}
Examples
Example 1: final Variable
public class FinalVariableExample {
public static void main(String[] args) {
final int MAX_VALUE = 100;
[Link]("MAX_VALUE: " + MAX_VALUE);
// MAX_VALUE = 200; // This will cause a compilation error
}
}
2. final Methods
A final method cannot be overridden by subclasses, ensuring that the method's
implementation remains unchanged.
class Parent {
public final void display() {
[Link]("This is a final method.");
}
}
Example 2: final Method
class Parent {
public final void display() {

66
[Link]("This is a final method.");
}
}

class Child extends Parent {


// public void display() { // This will cause a compilation error
// [Link]("Attempting to override.");
// }
}

public class FinalMethodExample {


public static void main(String[] args) {
Child obj = new Child();
[Link]();
}
}

3. final Classes
A final class cannot be subclassed, preventing inheritance.
public final class FinalClass {
// Class implementation
}
Example 3: final Class
public final class FinalClass {
public void show() {
[Link]("This is a final class.");
}
}
// class SubClass extends FinalClass { // This will cause a compilation error
// }

67
public class FinalClassExample {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
[Link]();
}
}

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

Organise Classes: For organizing the class, interfaces and other components, packages are
used.

o Control Access: It is the package that controls the access of the protected and default
members. Think what would be the use of default and protected access specifiers if
packages were absent?
o Reusability: Java enhances the reusability management of code and does the
promotion of data encapsulation with the help of packages.
Types of Packages
There are two types of packages in Java.
1. Built-in Packages
2. User-defined Packages
[Link]-in Packages
Some of the built-in packages that are used commonly are:
[Link]: It contains those classes that are required for language support, such as classes for
primitive data types and math operations. This package is automatically imported into Java.

68
[Link]: It contains all those classes that are required for the input/output operations.
[Link]: It contains utility classes that are needed for the data structures, such
as Array, List, Map, etc.
[Link]: All those classes that are required for finding applets are found in this package.
[Link]: It contains all those classes that are required for creating components of GUI
(Graphical User Interface).
[Link]: It includes classes that are used for doing tasks in the field of networking.
[Link]-defined Packages
In this section, we will create two Java files in two different packages (or folders). We will
also create three files. One file each for both the folders, and the last file is of the main class.
How to Create a Package?
To create a package in Java, you use the `package` keyword. The package statement must be
the first line in the source file (excluding comments).
Creating a Package:
//File:com/example/[Link]
[Link];
Public class HelloWorld {
public void greet() {
[Link]("Hello from the [Link] package!");
}
}
In this example:
- The `package [Link];` statement defines that the class `HelloWorld` belongs to the
`[Link]` package.
- The folder structure should mirror the package name (`com/example/`).
5. Accessing Classes from Packages
To access a class from a package, the fully qualified name of the class (including the package
name) should be used, or the class should be imported.
Accessing Without Import:
[Link] hello = new [Link]();
[Link]();
6. Importing Packages
Java provides the `import` statement to import classes or entire packages.
1. Importing a Single Class:
import [Link];

69
2. Importing All Classes in a Package:
import [Link].*;
In the second example, all classes within the `[Link]` package will be imported.
7. Sub-packages in Java
Java supports sub-packages, which are simply packages within other packages. There is no
special syntax for sub-packages; they are treated like regular packages, but the hierarchy is
created by adding dots in the package name.
Example:
package [Link];
8. Package Naming Conventions
Java follows certain conventions for naming packages to ensure uniqueness and clarity:
1. Reverse Domain Name: Use your domain name in reverse as the base of your package
names. For example, if your domain is `[Link]`, start your package with
`[Link]`.
2. Lowercase Names: Use lowercase letters to avoid conflicts with class names.
3. Meaningful Names: Use descriptive and meaningful names to reflect the content of the
package.
9. Java Built-in Packages
Java comes with several built-in packages that provide a wide range of functionalities. Some
common built-in packages are:
- [Link]: Provides classes fundamental to the Java language (automatically imported).
- [Link]: Contains utility classes, including collections framework, date, time facilities, and
more.
- [Link]: Contains classes for input/output operations (e.g., file handling).
- [Link]: Contains classes for networking operations.
- [Link]: Contains classes for database access and processing.
Java Interface
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface

70
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
Relationship Between Class and Interface
A class can extend another class, and similarly, an interface can extend another interface.
However, only a class can implement an interface, and the reverse (an interface implementing
a class) is not allowed.

Notes on Interfaces:
 Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).

71
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
[Link]("Some text..");
}
public void myOtherMethod() {
[Link]("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
[Link]();
[Link]();
}
}

72
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
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications.
Java AWT Basics
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface
(GUI) or Windows-based Java programs and Java AWT components are platform-dependent,
which means they are shown in accordance with the operating system’s view. AWT is
heavyweight, which means that its components consume resources from the underlying
operating system (OS). The [Link] package contains AWT API classes such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List, and so on.
Why AWT is Platform Independent?
AWT is platform independent even after the AWT components are platform dependent
because of the points mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through
Abstract API which are platform independent. Abstract API allows Java to isolate platform-
specific details, making code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent.
Because of this, it ensures that AWT functionality remains consistent across different
environments.

73
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.
Types of Containers in Java AWT
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or
dialog box. The Window class extends the Container class, which means it can
contain other components, 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 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.

74
Introduction to Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-drop support.
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.

Swing components requires [Link]


AWT components require [Link] package.
package.

Features Of Swing Class


 Pluggable look and feel.
 Uses MVC architecture.
 Lightweight Components
 Platform Independent
 Advanced features such as JTable, JTabbedPane, JScollPane, etc.
 Java is a platform-independent language and runs on any client machine, the GUI
look and feel, owned and delivered by a platform-specific O/S, simply does not affect
an application’s GUI constructed using Swing components.
 Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not

75
depend on any non-Java [O/s based) system classes. Swing components have their
own view supported by Java’s look and feel classes.
 Pluggable Look and Feel: This feature enable the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
 Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
 Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.

The MVC Connection


 In general, a visual component is a composite of three distinct aspects:
1. The way that the component looks when rendered on the screen.
2. The way such that the component reacts to the user.
3. The state information associated with the component.
 Over the years, one component architecture has proven itself to be exceptionally
effective: – Model-View-Controller or MVC for short.
 In MVC terminology, the model corresponds to the state information associated with
the Component.
 The view determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.
 The controller determines how the component reacts to the user.

76
77
Java JComponent

Here is the information about top-level and intermediate containers, basic


components, layout managers, event handling, and MVC in Java.
Top-Level Containers
These are the main windows of an application. They include:
 JFrame: For creating the main application window.
 JDialog: For creating dialog boxes.
 JApplet: For creating applets that run in a web browser (deprecated).

Intermediate Containers

These containers hold other components and help organize the GUI. They include:
 JPanel: A general-purpose container.
 JScrollPane: Provides scrollbars for components that exceed the display area.
 JSplitPane: Allows dividing the window into resizable panels.

Basic Components

These are the building blocks of the user interface:


 JLabel: Displays static text or images.
 JButton: Triggers actions when clicked.
 JTextField: Allows single-line text input.
 JTextArea: Allows multi-line text input.
 JCheckBox: Allows binary selection (on/off).
 JRadioButton: Allows single selection from a group of options.
 JComboBox: Provides a drop-down list of options.

Layout Managers
Layout managers control the arrangement of components within a container:
 FlowLayout: Arranges components in a row, wrapping to the next row if necessary
(default for JPanel).
 BorderLayout: Arranges components in five regions: North, South, East, West, and
Center (default for JFrame).

78
 GridLayout: Arranges components in a grid of rows and columns.
 CardLayout: Allows switching between different components in the same space.
 GridBagLayout: Provides a flexible grid-based layout with advanced customization
options.
Event Handling
Event handling is the process of responding to user interactions, such as button clicks
or mouse movements. The delegation event model is commonly used, where event
listeners are attached to components to handle specific events.

Model-View-Controller (MVC)
MVC is an architectural pattern for separating the application logic into three
interconnected parts:
 Model: Represents the data and business logic.
 View: Displays the data to the user.
 Controller: Handles user input and updates the model and view.
Swing components are often used in the view part of an MVC architecture, while
event handling mechanisms facilitate the interaction between the controller and the
other parts.

SWING COMPONENTS CLASS IN JAVA

JAVA SWING CONTROLS


Swing components are the basic building blocks of an application. We know that Swing is a
GUI widget toolkit for Java. Every application has some basic interactive interface for the

79
user. For example, a button, check-box, radio-button, text-field, etc. These together form the
components in Swing.
Components of Swing in Java
Below are the different components of swing in java:
1. ImageIcon
The ImageIcon component creates an icon sized-image from an image residing at the source
URL.
Example:
ImageIcon homeIcon = new ImageIcon("src/images/[Link]");
This returns an icon of a home button. The string parameter is the path at which the source
image is present.
2. JButton
JButton class is used to create a push-button on the UI. The button can contain some display
text or image. It generates an event when clicked and double-clicked. A JButton can be
implemented in the application by calling one of its constructors.
Example:
JButton okBtn = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton homeBtn = new JButton(homeIcon);
It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, "Home");
It returns a button with the home icon and text Home.
3. JLabel
JLabel class is used to render a read-only text label or images on the UI. It does not generate
any event.
Example:
JLabel textLbl = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);
It returns a label with a home icon.
4. JTextField
JTextField renders an editable single-line text box. A user can input non-formatted text in the
box. To initialize the text field, call its constructor and pass an optional integer parameter to

80
it. This parameter sets the width of the box measured by the number of columns. It does not
limit the number of characters that can be input in the box.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
5. JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-
formatted text in the field. The constructor for JTextArea also expects two integer parameters
which define the height and width of the text-area in columns. It does not restrict the number
of characters that the user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with
default text initialized in the text-area.
6. JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that masks the user
input text with bullet points. This is used for inserting passwords into the application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = [Link]();
It returns a password field of 15 column width. The getPassword method gets the value
entered by the user.
7. JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states – on/off. When
selected, the state is on and a small tick is displayed in the box.
Example:
CheckBox chkBox = new JCheckBox("Show Help", true);
It returns a checkbox with the label Show Help. Notice the second parameter in the
constructor. It is a boolean value that indicates the default state of the check-box. True means
the check-box is defaulted to on state.
8. JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can select one
choice from the group.

81
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
[Link](rb1);
[Link](rb2);
[Link](rb3);
The above code creates a button group and three radio button elements. All three elements are
then added to the group. This ensures that only one option out of the available options in the
group can be selected at a time. The default selected option is set to Easy.
9. JList
JList component renders a scrollable list of elements. A user can select a value or multiple
values from the list. This select behavior is defined in the code by the developer.
Example:
DefaultListItem cityList = new DefaultListItem();
[Link]("Mumbai"):
[Link]("London"):
[Link]("New York"):
[Link]("Sydney"):
[Link]("Tokyo"):
JList cities = new JList(cityList);
[Link](ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection restriction is set
to SINGLE_SELECTION. If multiple selections is to be allowed, set the behavior to
MULTIPLE_INTERVAL_SELECTION.
10. JComboBox
JComboBox class is used to render a dropdown of the list of options.
Example:
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };
JComboBox cities = new JComboBox(cityList);
[Link](3);

82
The default selected option can be specified through the setSelectedIndex method. The above
code sets Sydney as the default selected option.
11. JFileChooser
JFileChooser class renders a file selection utility. This component lets a user select a file
from the local system.
Example:
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton("Select File");
[Link](new ActionListner(){
[Link]();
})
var selectedFile = [Link]();
The above code creates a file chooser dialog and attaches it to the button. The button click
would open the file chooser dialog. The selected file is returned through the getSelectedFile
method.
12. JTabbedPane
JTabbedPane is another very useful component that lets the user switch between tabs in an
application. This is a highly useful utility as it lets the user browse more content without
navigating to different pages.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
[Link]("Tab 1", new JPanel());
[Link]("Tab 2", new JPanel());
The above code creates a two tabbed panel with headings Tab 1 and Tab 2.
13. JSlider
JSlider component displays a slider which the user can drag to change its value. The
constructor takes three arguments – minimum value, maximum value, and initial value.
Example:
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = [Link]();
The above code creates a slider from 0 to 100 with an initial value set to 50. The value
selected by the user is returned by the getValue method.
Event Handling in Java

83
An event is a change in the state of an object triggered by some action such as Clicking a
button, Moving the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the [Link] package provides various event classes to handle these actions.
Classification of Events

Events in Java can be broadly classified into two categories based on how they are generated:
1. Foreground Events: Foreground events are the events that require user interaction to
generate. Examples of these events include Button clicks, Scrolling the scrollbar,
Moving the cursor, etc.
2. 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.
Event Handling Mechanism
Event handling is a mechanism that allows programs to control events and define what should
happen when an event occurs. Java uses the Delegation Event Model to handle events. This
model consists of two main components:
 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.

84
Registering the Source With Listener
To handle events, the source must be registered with a listener. Java provides specific
methods for registering listeners based on the type of event.
Syntax:
addTypeListener()
For example,
 addKeyListener() for KeyEvent
 addActionListener() for ActionEvent
Event Classes and Listener Interfaces
Java provides a variety of event classes and corresponding listener interfaces. Below
table demonstrates the most commonly used event classes and their associated
listener interfaces:

Event Class Listener Interface Description

An event that indicates that a


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

The adjustment event is emitted by


AdjustmentEvent AdjustmentListener
an Adjustable object like Scrollbar.

ComponentEvent ComponentListener An event that indicates that a


component moved, the size changed

85
Event Class Listener Interface Description

or changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
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 the
keyboard.

The events that occur due to the user


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

An event that specifies that the


MouseWheelEvent MouseWheelListener mouse wheel was rotated in a
component.

An event that occurs when an


TextEvent TextListener
object’s text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

Methods in Listener Interfaces

86
Each listener interface contains specific methods that must be implemented to handle events.
Below table demonstrates the key methods for each interface:

Listener Interface Methods

ActionListener actionPerformed()

AdjustmentListene adjustmentValueChang
r ed()

componentResized()

ComponentListene componentShown()
r componentMoved()
componentHidden()

componentAdded()
ContainerListener
componentRemoved()

focusGained()
FocusListener
focusLost()

ItemListener itemStateChanged()

keyTyped()
KeyListener keyPressed()
keyReleased()

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

87
Listener Interface Methods

MouseMotionListe mouseMoved()
ner mouseDragged()

MouseWheelListen
mouseWheelMoved()
er

TextListener textChanged()

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

Approaches For Event Handling


Java provides three main approaches to implement event handling
1. Event Handling Within the Class
// Java program to demonstrate the
// event handling within the class
import [Link].*;
import [Link].*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

88
GFGTop()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of the component
[Link](60, 50, 180, 25);
Button button = new Button("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


public void actionPerformed(ActionEvent e)
{
// Setting text to field
[Link]("GFG!");
}

89
public static void main(String[] args)
{
new GFGTop();
}
}
Output:

Explanation:
 Firstly extend the class with the applet and implement the respective listener.
 Create Text-Field and Button components.
 Registered the button component with respective event. i.e. ActionEvent by
addActionListener().
 In the end, implement the abstract method.

2. Event Handling by Another Class


// Java program to demonstrate the
// event handling by the other class
import [Link].*;
import [Link].*;
class GFG1 extends Frame {

90
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
[Link](100, 120, 80, 30);
Other other = new Other(this);
// Registering component with listener
// Passing other class as reference
[Link](other);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
public static void main(String[] args)
{
new GFG2();
}
}

91
Separate class implementing ActionListener to handle events:
/// import necessary packages
import [Link].*;
// implements the listener interface
class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {
[Link] = gfgObj;
}

public void actionPerformed(ActionEvent e)


{
// setting text from different class
[Link]("Using Different Classes");
}
}
Output:

92
3. Event Handling By Anonymous Classes
// Java program to demonstrate the
// event handling by the anonymous class

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

class GFG3 extends Frame {

TextField textField;

GFG3()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
[Link](100, 120, 80, 30);

// Registering component with listener anonymously


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Setting text to field
[Link]("Anonymous");
}
});

93
// add Components
add(textField);
add(button);

//make size viewable


setSize(300,300);
// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}
Output:

94
UNIT- V
Adapter classes - Inner classes -Java Util Package / Collections
Framework:Collection & Iterator Interface- Enumeration- List and ArrayList-
Vector- Comparator

Adapter Class In Java


In Java programming, event handling is a basic concept of developing interactive
applications. When developers are working with applications, they often find themselves
implementing event listener interfaces to respond to various events like button clicks, mouse
movements, or keyboard inputs. While this approach works well, it can result in lengthy
code, especially when dealing with interfaces containing multiple methods.
Enter the “Adapter Class in Java”, the best solution to streamline event handling and
improve code readability. The adapter class serves as a useful tool, offering an elegant way to
tackle event listener interfaces effortlessly.
What is an Adapter Class?
An adapter class (wrapper class) acts as a mediator between two incompatible interfaces. It
allows classes with different interfaces to work together seamlessly by converting the
interface of one class into another, making them compatible. In simpler terms, an adapter
class enables communication between two entities that would otherwise be unable to interact
due to differences in their interfaces.
Types Of Adapter Class In Java
In Java, there are two commonly used types of adapter classes:
1. Class adapters
2. Object adapters

Class Adapter
A class adapter uses inheritance to adapt the interfaces of two different classes. It
extends the class that needs to be adapted and implements the interface expected by
the client class. As a result, it inherits the functionality of the adapter class and makes
it available through the interface required by the client.
public interface Target {
void request();
} public class Adaptee {

95
public void specificRequest() {
// Specific implementation
}
} public class ClassAdapter extends Adaptee implements Target {
public void request() {
specificRequest(); // Reusing adaptee's functionality
}
}
In the example above, the “Target” interface defines the expected interface for the
client class. The “Adaptee class” represents the existing functionality that needs to be
adapted. The ClassAdapter class extends “Adaptee” and implements Target,
providing the necessary adaptation by calling the specific method of the “Adaptee”
within the request() method.
Object Adapter
An object adapter uses composition to adapt the interfaces of two different classes. It holds an
instance of the “adaptee class” and implements the interface expected by the client class. By
doing so, it delegates the method calls from the client to the “adaptee”, effectively adapting
the functionality.
public interface Target {
void request();
} public class Adaptee {
public void specificRequest() {
// Specific implementation
}
} public class ObjectAdapter implements Target {
private Adaptee adaptee; public ObjectAdapter(Adaptee adaptee) {
[Link] = adaptee;
} public void request() {
[Link](); // Delegating to adaptee's functionality
}
}
In this example, the “Target” interface defines the expected interface for the client class,
while the “Adaptee class” represents the existing functionality. The ObjectAdapter class
implements Target and holds an instance of “Adaptee”. By implementing

96
the “request()” method and delegating the call to the “specificRequest()” method of
the adaptee, the object adapter achieves the desired adaptation.

Creating an Adapter Class


To create an adapter class in Java, follow these steps:
Step 1: Identify the incompatible interfaces:- Determine the interfaces of the classes that need
to be connected.
Step 2: Create an adapter class:- Declare a new class that implements the interface expected
by the client class (the class that requires the desired functionality).
Step 3: Implement the adapter class:- Implement the interface methods in the adapter class by
calling the corresponding methods from the adapter class (the class that provides the existing
functionality).
Step 4: Connect the classes:- Create an instance of the adapter class and pass it to the client
class, enabling communication between the two interfaces.
Example Of Adapter Class
Let’s take an one example that demonstrates the usage of adapter classes. Suppose you have a
legacy class, Square, which provides a method called “calculateArea()”. However, a new
class, Circle, expects a different method called “computeArea()”. We can bridge this gap
using an adapter class.

public interface Circle {


double computeArea();
} public class Square {
public double calculateArea() {
// Calculation logic for square area
}
} public class SquareToCircleAdapter implements Circle {
private Square square; public SquareToCircleAdapter(Square square) {
[Link] = square;
} public double computeArea() {
return [Link]();
}
} public class Main {

97
public static void main(String[] args) {
Square square = new Square();
Circle circle = new SquareToCircleAdapter(square);
double area = [Link]();
[Link]("Area: " + area);
}
}
In the example above, we create an adapter class called “SquareToCircleAdapter” that
implements the Circle interface. This adapter class takes an instance of the Square class as a
constructor argument. By implementing the “computeArea()” method in the adapter class
and delegating the call to the square’s “calculateArea()” method, we establish compatibility
between the two classes.
Benefits of Adapter Classes
1) Code reusability: Adapter classes enable the reuse of existing classes that have
incompatible interfaces, saving development time and effort.
2) Seamless integration: Adapter classes facilitate the integration of legacy or third-party
code into new systems, even when the interfaces differ.
3) Modularity: Adapter classes allow you to keep existing code intact while adapting it to
new requirements, promoting modular and maintainable codebases.
4) Flexibility: Through adapters, you can extend the functionality of existing classes without
modifying their original implementation.
Inner Classes in Java (Nested Classes)
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data members
and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

98
Advantage of Java inner classes
There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Difference between nested class and inner class in Java
An inner class is a part of a nested class. Non-static nested classes are known as inner classes.
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-
static nested classes are also known as inner classes.
1. Non-static nested class (inner class)
 Member inner class
 Anonymous inner class
 Local inner class
2. Static nested class

Type Description

Member Inner A class created within class and outside method.


Class

Anonymous Inner A class created for implementing an interface or extending class.


Class The Java compiler decides its name.

Local Inner Class A class was created within the method.

Static Nested Class A static class was created within the class.

Nested Interface An interface created within class or interface.

99
Collection Frameworks in Java
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
What is Collection?
A Collection represents a single unit of objects, i.e., a group.
What is a framework?
A framework provides a ready-made structure of classes and interfaces for building software
applications efficiently. It simplifies adding new features by offering reusable components that
perform similar tasks, eliminating the need to create a framework from scratch for each new
project. This approach enhances object-oriented design, making development quicker, more
consistent, and reliable.
o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It enhances code efficiency and readability by offering various data
structures, including arrays, linked lists, trees, and hash tables, tailored to different
programming needs. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Why Collection Framework?
Before the Collection Framework was introduced in JDK 1.2, Java's approach to collections
was using Arrays, Vectors, and Hash tables lacked a common interface. This meant each type
of collection had its own set of methods, syntax, and constructors, with no standardization or
correlation between them.
This made it difficult for users to remember the diverse functionalities of each collection type
and hindered code consistency and reusability. The disparate nature of these collections
highlighted the need for a unified Collection Framework to simplify and standardize collection
operations in Java.
Advantages of the Java Collection Framework

100
The Java Collections Framework offers significant advantages that enhance development
practices, code quality, and application performance:
1. Reusability: The framework provides a comprehensive set of common classes and
utility methods applicable across various types of collections. This feature promotes code
reusability, sparing developers the need to write duplicate code for common operations.
2. Quality: Leveraging the Java Collections Framework elevates the quality of
programs. The components within the framework have been extensively tested and are widely
used by a vast community of developers, ensuring reliability and stability in your
applications.
3. Speed: Developers often report an increase in development speed when using the
Collections Framework. It allows them to concentrate on the core business logic of their
applications rather than on implementing generic collection functionalities, thus speeding up
the development process.
4. Maintenance: The open-source nature of the Java Collections Framework, coupled
with readily available API documentation, facilitates easier code maintenance. Code written
using the framework can be easily understood and taken over by other developers, ensuring
continuity and ease of maintenance.
5. Reduces Effort to Design New APIs: An additional benefit is the reduced necessity
for API designers and implementers to create new collection mechanisms for each new API.
They can instead rely on the standard collection interfaces provided by the framework,
streamlining the API development process and ensuring consistency across Java applications.

101
Hierarchy of Collection Framework
Let's see the hierarchy of Collection framework. The [Link] package contains all
the classes and interfaces for the Collection framework.

o Class: A class is a blueprint from which individual objects are created. It encapsulates
data for objects through fields (attributes) and defines behavior via methods. Classes
support inheritance, allowing one class to inherit the properties and methods of
another, facilitating code reuse and polymorphism.
o Interface: An interface is a reference type in Java that can contain constants and
abstract methods (methods without a body). Interfaces specify what a class must do
but not how it does it, enforcing a set of methods that the class must implement.
Interfaces are used to achieve abstraction and multiple inheritance in Java.

102
Methods of Collection interface
There are many methods declared in the Collection interface. The Collection interface in Java
provides basic methods to work with groups of objects, such as adding, removing, and iterate
through each element. They are as follows:

o No. o Method o Description

o 1 o public boolean add(E e) o It is used to insert an element


in this collection.

o 2 o public boolean o It is used to insert the


addAll(Collection<? specified collection elements
extends E> c) in the invoking collection.

o 3 o public boolean o It is used to delete an element


remove(Object element) from the collection.

o 4 o public boolean o It is used to delete all the


removeAll(Collection<?> elements of the specified
c) collection from the invoking
collection.

o 5 o default boolean o It is used to delete all the


removeIf(Predicate<? super elements of the collection
E> filter) that satisfy the specified
predicate.

o 6 o public boolean o It is used to delete all the


retainAll(Collection<?> c) elements of invoking
collection except the
specified collection.

o 7 o public int size() o It returns the total number of


elements in the collection.

o 8 o public void clear() o It removes the total number

103
of elements from the
collection.

o 9 o public boolean o It is used to search an


contains(Object element) element.

o 10 o public boolean o It is used to search the


containsAll(Collection<?> specified collection in the
c) collection.

o 11 o public Iterator iterator() o It returns an iterator.

o 12 o public Object[] toArray() o It converts collection into


array.

o 13 o public <T> T[] toArray(T[] o It converts collection into


a) array. Here, the runtime type
of the returned array is that
of the specified array.

o 14 o public boolean isEmpty() o It checks if collection is


empty.

o 15 o default Stream<E> o It returns a possibly parallel


parallelStream() Stream with the collection as
its source.

o 16 o default Stream<E> stream() o It returns a sequential Stream


with the collection as its
source.

o 17 o default Spliterator<E> o It generates a Spliterator over


spliterator() the specified elements in the
collection.

104
o 18 o public boolean o It matches two collections.
equals(Object element)

o 19 o public int hashCode() o It returns the hash code


number of the collection.

Iterator interface
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:

No Method Description
.

1 public boolean It returns true if the iterator has more


hasNext() elements otherwise it returns false.

2 public Object It returns the element and moves the cursor


next() pointer to the next element.

3 public void It removes the last elements returned by the


remove() iterator. It is less used.

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection interface
also implement the Iterable interface.
It contains only one abstract method. i.e.,
1. Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.

105
Some of the methods of Collection interface are Boolean add (Object obj), Boolean addAll
(Collection c), void clear(), etc. that are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use:
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.

import [Link].*;
class Main{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}

106
}
}
Output:
1. Ravi
2. Vijay
3. Ravi
4. Ajay

Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, it
is synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
import [Link].*;
public class Main{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

Output:
Ayush
Amit
Ashish
Garima

Basics Of Enumeration

107
What Is Enumeration in Java?
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, you should always
represent them in UPPERCASE letters.
The following characteristics make enum a ‘special’ class:
 enum constants cannot be overridden
 enum doesn’t support the creation of objects
 enum can’t extend other classes
 enum can implement interfaces like classes
Syntax:
In Java, to define an Enum type, the ‘enum’ keyword is used rather than ‘class’ or ‘interface’.
Mentioned below is the syntax.
enum Variable_Name { VALUE_1, VALUE_2, VALUE_3, … }
Why Do We Need Enumeration?
Java supports two types of Data Types:
1. User-Defined Datatypes
2. Inbuilt Data Types- int, float, double, char, etc.
Sometimes inbuilt data types are not sufficient. Let’s suppose that we have data of different
data types required to be stored in a single variable. In such a situation, inbuilt data types
won’t fulfill the need. That’s why there is a requirement for user-defined Data Types, and
enum in Java is one of them.
Examples of Enum in Java:
What Is Enumeration in Java?
Enum, introduced in Java 5, is a special data type that consists of a set of pre-defined named
values separated by commas. These named values are also known as elements or enumerators
or enum instances. Since the values in the enum type are constant, you should always
represent them in UPPERCASE letters.
You can use an Enum type when you need a fixed set of pre-defined constant values that are
known at the compile-time itself. Examples can be days of the week, seasons of the year, etc.
The following characteristics make enum a ‘special’ class:
 enum constants cannot be overridden
 enum doesn’t support the creation of objects

108
 enum can’t extend other classes
 enum can implement interfaces like classes
Syntax:
In Java, to define an Enum type, the ‘enum’ keyword is used rather than ‘class’ or ‘interface’.
Mentioned below is the syntax.
enum Variable_Name { VALUE_1, VALUE_2, VALUE_3, … }
Want a Top Software Development Job? Start Here!
Full Stack Developer - MERN StackExplore Program

Why Do We Need Enumeration?


Java supports two types of Data Types:
1. User-Defined Datatypes
2. Inbuilt Data Types- int, float, double, char, etc.
Sometimes inbuilt data types are not sufficient. Let’s suppose that we have data of different
data types required to be stored in a single variable. In such a situation, inbuilt data types
won’t fulfill the need. That’s why there is a requirement for user-defined Data Types, and
enum in Java is one of them.

In the example depicted above, TicketCategory is of the enum type with 4 predefined values
which are CRITICAL, HIGH, MEDIUM, and LOW.
Constants in Enum can be referred to in the code later using the ‘dot’ notation operator like
below.
TicketCategory category = [Link];
How To Define Java Enum?

109
Enum in Java can be defined outside or within the class.
Syntax: enum Name{constants}
With the following example, we will learn how to define an enum in Java.
Code:
package definition;
enum Car{
MARUTI,HONDA,TESLA;
}
public classExample{
public static void main(String [] args) {
Carc1= [Link];
[Link](c1);
}
}
Vector Class in Java

The Vector class in Java implements a growable array of objects. Vectors were legacy
classes, but now it is fully compatible with collections. It comes under [Link] package and
implement the List interface.
Key Features of Vector:
 It expands as elements are added.
 Vector class is synchronized in nature means it is thread-safe by default.
 Like an ArrayList, it maintains insertion order.
 It allows duplicates and nulls.
 It implements List, RandomAccess, Cloneable, and Serializable.

110
Vector Class Declaration
public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
Here, E is the type of element.
 It extends AbstractList and implements List interfaces.
 It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>,
RandomAccess interfaces.
 The directly known subclass is Stack.
 We can use all the methods of the List interface as shown below as follows:

Constructors of Vector
1. Vector(): Creates a default vector of the initial capacity is 10.
Vector<E> v = new Vector<E>();

2. Vector(int size): Creates a vector whose initial capacity is specified by size.


Vector<E> v = new Vector<E>(int size);

111
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and
increment is specified by incr. It specifies the number of elements to allocate each time a
vector is resized upward.
Vector<E> v = new Vector<E>(int size, int incr);

4. Vector(Collection c): Creates a vector that contains the elements of collection c.


Vector<E> v = new Vector<E>(Collection c);

Methods in Vector Class

Method Description

Appends the specified element to the end of this


add(E e)
Vector.

Inserts the specified element at the specified


add(int index, E element)
position in this Vector.

Appends all of the elements in the specified


addAll(Collection<?
Collection to the end of this Vector, in the order
that they are returned by the specified
extends E> c)
Collection’s Iterator.

addAll(int index, Insert all of the elements in the specified


Collection into this Vector at the specified
Collection<? extends E> c) position.

Adds the specified component to the end of this


addElement(E obj)
vector, increasing its size by one.

capacity() Returns the current capacity of this vector.

clear() Removes all of the elements from this Vector.

112
Method Description

clone() Returns a clone of this vector.

Returns true if this vector contains the specified


contains(Object o)
element.

Returns true if this Vector contains all of the


containsAll(Collection<?> c)
elements in the specified Collection.

Copies the components of this vector into the


copyInto(Object[] anArray)
specified array.

elementAt(int index) Returns the component at the specified index.

Returns an enumeration of the components of this


elements()
vector.

Increases the capacity of this vector, if necessary,


to ensure that it can hold at least the number of
ensureCapacity(int minCapacity)
components specified by the minimum capacity
argument.

Compares the specified Object with this Vector


equals(Object o)
for equality.

Returns the first component (the item at index 0)


firstElement()
of this vector.

forEach(Consumer<? Performs the given action for each element of the


Iterable until all elements have been processed or
super E> action) the action throws an exception.

113
Method Description

Returns the element at the specified position in


get(int index)
this Vector.

hashCode() Returns the hash code value for this Vector.

Returns the index of the first occurrence of the


specified element in this vector,
indexOf(Object o)

or -1 if this vector does not contain the element.

Returns the index of the first occurrence of the


specified element in this vector, searching
indexOf(Object o, int index)
forwards from the index, or returns -1 if the
element is not found.

Inserts the specified object as a component in this


insertElementAt(E obj, int index)
vector at the specified index.

isEmpty() Tests if this vector has no components.

Returns an iterator over the elements in this list in


iterator()
a proper sequence.

lastElement() Returns the last component of the vector.

Returns the index of the last occurrence of the


specified element in this vector,
lastIndexOf(Object o)

or -1 if this vector does not contain the element.

lastIndexOf(Object o, int index) Returns the index of the last occurrence of the

114
Method Description

specified element in this vector, searching


backward from the index, or returns -1 if the
element is not found.

Returns a list iterator over the elements in this list


listIterator()
(in proper sequence).

Returns a list iterator over the elements in this list


(in proper sequence),
listIterator(int index)

starting at the specified position in the list.

Removes the element at the specified position in


remove(int index)
this Vector.

Removes the first occurrence of the specified


remove(Object o) element in this Vector. If the Vector does not
contain the element, it is unchanged.

Removes from this Vector all of its elements


removeAll(Collection<?> c)
contained in the specified Collection.

Removes all components from this vector and sets


removeAllElements()
its size to zero.

Removes the first (lowest-indexed) occurrence of


removeElement(Object obj)
the argument from this vector.

removeElementAt(int index) Deletes the component at the specified index.

removeIf(Predicate<? super E> Removes all of the elements of this collection that

115
Method Description

filter) satisfy the given predicate.

removeRange(int fromIndex, Removes from this list all of the elements whose
index is between fromIndex, inclusive, and
int toIndex) toIndex, exclusive.

replaceAll(UnaryOperator<E> Replaces each element of this list with the result


operator) of applying the operator to that element.

Retains only the elements in this Vector contained


retainAll(Collection<?> c)
in the specified Collection.

Replaces the element at the specified position in


set(int index, E element)
this Vector with the specified element.

Sets the component at the specified index of this


setElementAt(E obj, int index)
vector to be the specified object.

setSize(int newSize) Sets the size of this vector.

size() Returns the number of components in this vector.

Sorts this list according to the order induced by


sort(Comparator<? super E> c)
the specified Comparator.

Creates a late-binding and fail-fast Spliterator


spliterator()
over the elements in this list.

Returns a view of the portion of this List between


subList(int fromIndex, int toIndex)
fromIndex, inclusive, and toIndex, exclusive.

116
Method Description

Returns an array containing all of the elements in


toArray()
this Vector in the correct order.

Returns an array containing all of the elements in


toArray(T[] a) this Vector in the correct order; the runtime type
of the returned array is that of the specified array.

Returns a string representation of this Vector,


toString() containing the String representation of each
element.

Trims the capacity of this vector to be the vector’s


trimToSize()
current size.

Java Comparator Interface


The Comparator interface in Java is used to sort the objects of user-defined classes. The
Comparator interface is present in [Link] package. This interface allows us to define custom
comparison logic outside of the class for which instances we want to sort. The comparator
interface is useful when,
 We need multiple sorting strategies for a class.
 When we want to keep the sorting logic separate from the class.
A comparator object is capable of comparing two objects of the same class. The following
function compares obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
 It will return a negative integer if obj1 < obj2.
 It will return 0 if both objects are equal.
 It will return a positive integer if obj1 > obj2.

117
118

You might also like