2nd Bca C Java Notes
2nd Bca C Java Notes
Year: II Semester: IV
Java Programming 220C4A
Common for B.C.A. , [Link].-SA , [Link].-CSc , [Link].-CSc-wAI , [Link].-CSc-wDS
Credits 5 Lecture Hours:4 per week
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.
Learning Resources:
Recommended Texts
Herbert Schildt, The Complete Reference, Tata McGraw Hill, New Delhi, 7th Edition, 2010.
Gary Cornell, Core Java 2 Volume I – Fundamentals, Addison Wesley, 1999.
Reference Books
Head First Java, O’Rielly Publications, Y. Daniel Liang, Introduction to Java Programming,
7th Edition, Pearson Education India, 2010.
Unit - I Java Programming II BCA
Unit -I
Concepts of OOPS:
Class
Object
Method and method passing
Abstraction
Encapsulation
Inheritance
Polymorphism
Compile-time polymorphism
Runtime polymorphism
Class:
A class is a user-defined blueprint or prototype from which objects are created.
1
Unit - I Java Programming II BCA
It represents the set of properties or methods that are common to all objects of one
type.
Using classes, you can create multiple objects with the same behavior instead of
writing their code multiple times. Class declarations can include these components
in order:
Object:
An object is a basic unit of Object-Oriented Programming that represents real-life entities.
A typical Java program creates many objects, which as you know, interact by invoking
methods.
The objects are what perform your code; they are the part of your code visible to the
viewer/user. An object mainly consists of:
Abstraction
Data Abstraction is the property by virtue of which only the essential details are
displayed to the user.
The trivial or non-essential units are not displayed to the user. Ex: A car is viewed as a
car rather than its individual components.
Encapsulation
It is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together the code and the data it manipulates. Another way to think about
encapsulation is that it is a protective shield that prevents the data from being accessed
by the code outside this shield.
Inheritance
It is the mechanism in Java by which one class is allowed to inherit the features (fields
and methods) of another class.
We are achieving inheritance by using extends keyword. Inheritance is also known as
“is-a” relationship.
Super class: The class whose features are inherited is known as superclass (also known as base
or parent class).
Subclass: The class that inherits the other class is known as subclass (also known as derived or
extended or child class). The subclass can add its own fields and methods in addition to the
super class fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
2
Unit - I Java Programming II BCA
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Polymorphism
It refers to the ability of object-oriented programming languages to differentiate
between entities with the same name efficiently.
This is done by Java with the help of the signature and declaration of these entities.
The ability to appear in many forms is called polymorphism.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
3
Unit - I Java Programming II BCA
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of
objects that incorporate both data and behavior.
Backward Skip 10sPlay Video
Platform Independent
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language.
There are two types of platforms software-based and hardware-based.
Java provides a software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms.
Runtime Environment
API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Robust
Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It
doesn't require any implementation.
4
Unit - I Java Programming II BCA
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
5
Unit - I Java Programming II BCA
JVM Architecture
1) Class loader
Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the class loader. There are three built-in class loaders in Java.
1. Bootstrap Class Loader: This is the first class loader which is the super class of Extension
class loader.
It loads the [Link] file which contains all class files of Java Standard Edition like [Link]
package classes, [Link] package classes, [Link] package classes, [Link] package classes,
[Link] package classes etc.
2. Extension Class Loader: This is the child class loader of Bootstrap and parent class loader of
System class loader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application Class Loader: This is the child class loader of Extension class loader. It
loads the class files from class path. By default, class path is set to current directory. You can
change the class path using "-cp" or "-class path" switch. It is also known as Application class
loader.
Example:
public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=[Link];
6
Unit - I Java Programming II BCA
[Link]([Link]());
//If we print the classloader name of String, it will print null because it is an
//in-built class which is found in [Link], so it is loaded by Bootstrap classloader
[Link]([Link]());
}
}
Documentation Section
7
Unit - I Java Programming II BCA
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's name, date
of creation, version, program name, company name, and description of the program. It improves the
readability of the program.
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
Package Declaration
//save as [Link]
package mypack;
public class Simple
{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
Interface Section
Interface car
{
void start();
void stop();
}
Class Definition
It is vital part of a Java program. Without the class, we cannot create any Java
program. A Java program may conation more than one class definition.
8
Unit - I Java Programming II BCA
We use the class keyword to define the class. The class is a blueprint of a Java
program. It contains information about user-defined methods, variables, and
constants.
Every Java program has at least one class that contains the main () method. For example:
In this section, we define variables and constants that are to be used later in the
program.
In a Java program, the variables and constants are defined just after the class
definition.
The variables and constants store values of the parameters. It is used during the
execution of the program
In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method.
In other words, it is an entry point of the class. It must be inside the class. Inside the
main method, we create objects and call the methods. We use the following statement
to define the main () method:
9
Unit - I Java Programming II BCA
{
//statements
}
}
Java Console Class
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.
The [Link] class is attached with system console internally. The Console class is
introduced since 1.5.
Method Description
Reader reader() It is used to retrieve the reader object associated with the console
String readLine() It is used to read a single line of text from the console.
String readLine(String fmt, Object... It provides a formatted prompt then reads the single line of text
args) from the console.
char[] readPassword() It is used to read password that is not being displayed on the
console.
char[] readPassword(String fmt, It provides a formatted prompt then reads the password that is not
Object... args) being displayed on the console.
Console format(String fmt, Object... It is used to write a formatted string to the console output stream.
args)
Console printf(String format, It is used to write a string to the console output stream.
Object... args)
System class provides a static method console() that returns the singleton instance of Console class.
10
Unit - I Java Programming II BCA
1. Console c=[Link]();
import [Link];
class ReadStringTest{
public static void main(String args[]){
Console c=[Link]();
[Link]("Enter your name: ");
String n=[Link]();
[Link]("Welcome "+n);
}
}
class Simple {
public static void main(String args[]){
[Link]("Hello Java");
}
}
Data types in Java are of different sizes and values that can be stored in the variable that is made
as per convenience and circumstances to cover up all test cases.
Java has two categories in which data types are segregated.
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
11
Unit - I Java Programming II BCA
12
Unit - I Java Programming II BCA
In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically.
The automatic conversion is done by the compiler and manual conversion performed by the
programmer.
13
Unit - I Java Programming II BCA
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no chance
to lose data. It takes place when:
byte -> short -> char -> int -> long -> float -> double
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
Type conversion:
Java provides various data types just like any other dynamic languages such as boolean, char, int,
unsigned int, signed int, float, double, long, etc in total providing 7 types where every datatype
acquires different space while storing in memory.
When you assign a value of one data type to another, the two types might not be compatible with each
other. If the data types are compatible, then Java will perform the conversion automatically known as
Automatic Type Conversion, and if not then they need to be cast or converted explicitly. For example,
assigning an int value to a long variable.
14
Unit - I Java Programming II BCA
A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the
input and to support the mark and reset methods. When the BufferedInputStream is created, an
internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is
refilled as necessary from the contained input stream, many bytes at a time.
Constructor and Description
BufferedInputStream(InputStream in) : Creates a BufferedInputStream and saves its
argument, the input stream in, for later use.
BufferedInputStream(InputStream in, int size) : Creates a BufferedInputStream with the
specified buffer size, and saves its argument, the input stream in, for later use.
Methods:
int available() : Returns an estimate of the number of bytes that
can be read (or skipped over) from this input stream without
blocking by the next invocation of a method for this input stream.
Syntax:public int available()
throws IOException
Returns:
an estimate of the number of bytes that can be
read (or skipped over) from this input stream without blocking.
Throws:
IOException
void close() : Closes this input stream and releases any system resources associated with the
stream.
Syntax:public void close()
throws IOException
Overrides:
close in class FilterInputStream
Throws:
IOException
void mark(int readlimit) : Marks the current position in this input stream.
Syntax:public void mark(int readlimit)
Overrides:
mark in class FilterInputStream
Parameters:
readlimit - the maximum limit of bytes that can be read
before the mark position becomes invalid.
booleanmarkSupported() : Tests if this input stream supports the mark and reset methods.
Syntax:publicbooleanmarkSupported()
Overrides:
markSupported in class FilterInputStream
Returns:
a boolean indicating if this stream type supports the mark and reset methods.
int read() : Reads the next byte of data from the input stream.
Syntax:public int read()
throws IOException
Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException
int read(byte[] b, int off, int len) : Reads bytes from this byte-input stream into the specified
byte array, starting at the given offset.
Syntax:public int read(byte[] b,
int off,
int len)
throws IOException
Parameters:
15
Unit - I Java Programming II BCA
b - destination buffer.
off - offset at which to start storing bytes.
len - maximum number of bytes to read.
Returns:
the number of bytes read, or -1 if the end of the stream has been reached.
Throws:
IOException
void reset() : Repositions this stream to the position at the time the mark method was last
called on this input stream.
Syntax:public void reset()
throws IOException
Overrides:
reset in class FilterInputStream
Throws:
IOException
long skip(long n) :Skips over and discards n bytes of data from this input stream
Syntax:public long skip(long n)
throws IOException
Parameters:
n - the number of bytes to be skipped.
Returns:
the actual number of bytes skipped.
Throws:
IOException
Program:
import [Link];
import [Link];
import [Link];
class BufferedInputStreamDemo
16
Unit - I Java Programming II BCA
[Link]());
boolean b=[Link]();
if (b)
[Link]([Link]());
[Link](4);
[Link]("FileContents :");
// write them
int ch;
[Link]((char)ch);
17
Unit - I Java Programming II BCA
[Link]();
[Link]((char)ch);
[Link]();
Output:
Number of remaining bytes:47
FileContents :
is my first line
This is my second line
This is my first line
This is my second line
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
18
Unit - I Java Programming II BCA
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
19
Unit - I Java Programming II BCA
Output:
10
12
12
10
}}
Output:
22
21
Output:
-11
9
false
true
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.
20
Unit - I Java Programming II BCA
int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}
Output:
15
5
50
2
0
Output:
21
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
Output:
40
80
80
240
21
Unit - I Java Programming II BCA
The Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.
Output:
2
5
2
Output:
5
5
-5
1073741819
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used to
control the flow of Java code. Such statements are called control flow statements. It is one of the
fundamental features of Java, which provides a smooth flow of program.
22
Unit - I Java Programming II BCA
Decision-Making statements:
There are two types of decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either
true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
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.
1. if(condition) {
23
Unit - I Java Programming II BCA
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
[Link]
24
Unit - I Java Programming II BCA
int x = 10;
int y = 12;
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
ADVERTISEMENT
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
}
[Link]
25
Unit - I Java Programming II BCA
[Link]("city is meerut");
}else if (city == "Noida") {
[Link]("city is noida");
}else if(city == "Agra") {
[Link]("city is agra");
}else {
[Link](city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
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
}
}
[Link]
if([Link]("India")) {
if([Link]("Meerut")) {
26
Unit - I Java Programming II BCA
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
switch (expression){
case value1:
statement1;
break;
27
Unit - I Java Programming II BCA
.
.
.
case valueN:
statementN;
break;
default:
default statement;
1. }
Consider the following example to understand the flow of the switch statement.
[Link]
Output:
While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.
28
Unit - I Java Programming II BCA
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++.. It enables us to initialize the loop variable, check the
th
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.
Consider the following example to understand the proper functioning of the for loop in java.
[Link]
29
Unit - I Java Programming II BCA
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}
Output:
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
Output:
Java
C
C++
Python
30
Unit - I Java Programming II BCA
JavaScript
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in while
loop.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Calculation .java
31
Unit - I Java Programming II BCA
Output:
0
2
4
6
8
10
The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.
ADVERTISEMENT
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
32
Unit - I Java Programming II BCA
[Link]
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
33
Unit - I Java Programming II BCA
ADVERTISEMENT
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks only
the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
[Link]
Output:
0
1
2
3
4
5
6
[Link]
34
Unit - I Java Programming II BCA
}
}
Output:
0
1
2
3
4
5
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
35
Unit - I Java Programming II BCA
if(j == 4) {
continue;
}
[Link](j);
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
36
Unit - I Java Programming II BCA
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
37
Unit - I Java Programming II BCA
//[Link]="BBDIT";
[Link]();
[Link]();
}
}
Output:
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each
object will have the value 1 in the count variable.
Counter(){
count++;//incrementing value
[Link](count);
}
Output:
1
1
1
38
Unit - I Java Programming II BCA
As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.
Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}
public static void main(String args[]){
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
39
Unit - I Java Programming II BCA
class Calculate{
static int cube(int x){
return x*x*x;
}
40
Unit - I Java Programming II BCA
int result=[Link](5);
[Link](result);
}
}
Output:125
There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A{
int a=40;//non static
class A3{
41
Unit - I Java Programming II BCA
static{
[Link]("static block is invoked");
[Link](0);
}
}
Output:
Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend [Link]
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in
Java is the same as String class except it is mutable i.e. it can be changed.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.
public insert(int offset, String s) It is used to insert the specified string with this string at
synchronized the specified position. The insert() method is overloaded
StringBuffer like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public replace(int startIndex, It is used to replace the string from specified startIndex
synchronized int endIndex, String str) and endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified startIndex
42
Unit - I Java Programming II BCA
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total
number of characters.
public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int beginIndex, It is used to return the substring from the specified
int endIndex) beginIndex and endIndex.
(Unit – I Completed)
43
Unit - II Java Programming II BCA
UNIT 2
Java user defined Classes and Objects – Arrays – constructors - Inheritance: Basic concepts -
Types of inheritance - Member access rules - Usage of this and Super key word - Method
Overloading - Method overriding - Abstract classes - Dynamic method dispatch - Usage of
final keyword -Packages: Definition - Access Protection - Importing Packages - Interfaces:
Definition – Implementation – Extending Interfaces
Java Classes
1
Unit - II Java Programming II BCA
Dog tuffy;
2
Unit - II Java Programming II BCA
// Class Declaration
publicclassDog {
// Instance Variables
String name;
String breed;
intage;
String color;
// method 1
publicString getName() { returnname; }
// method 2
3
Unit - II Java Programming II BCA
// method 3
publicintgetAge() { returnage; }
// method 4
publicString getColor() { returncolor; }
@OverridepublicString toString()
{
return("Hi my name is "+ [Link]()
+ ".\nMy breed,age and color are "
+ [Link]() + ","+ [Link]()
+ ","+ [Link]());
}
publicstaticvoidmain(String[] args)
{
Dog tuffy
= newDog("tuffy", "papillon", 5, "white");
[Link]([Link]());
}
}
Output
Hi my name is tuffy.
My breed,age and color are papillon,5,white
Array in java:
Java array is an object which contains elements of a similar data type. Additionally,
the elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
4
Unit - II Java Programming II BCA
1. arrayRefVar=new datatype[size];
Example of Java Array
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
int a[]={33,3,4,5};//declaration, instantiation and initialization
5
Unit - II Java Programming II BCA
3
4
5
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.
for(data_type variable:array){
//body of the loop
}
Output:
6
Unit - II Java Programming II BCA
33
3
4
5
We can pass the java array to method so that we can reuse the same logic on any array.
[Link](min);
}
Output:
In such case, data is stored in row and column based index (also known as matrix form).
7
Unit - II Java Programming II BCA
dataType []arrayRefVar[];
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Constructor
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
Every time an object is created using the new () keyword, at least one constructor is
called.
8
Unit - II Java Programming II BCA
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated
fferentiated by the compiler by the number of parameters in the list
and their types.
9
Unit - II Java Programming II BCA
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
} Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an A method is used to expose the behavior of
object. an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if The method is not provided by the compiler
you don't have any constructor in a class. in any case.
The constructor name must be same as the class The method name may or may not be same
name. as the class name.
10
Unit - II Java Programming II BCA
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
11
Unit - II Java Programming II BCA
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
12
Unit - II Java Programming II BCA
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
13
Unit - II Java Programming II BCA
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
1. Dog d=new Dog();
2. [Link]();
3. [Link]();
4. }}
Output:
barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
14
Unit - II Java Programming II BCA
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
15
Unit - II Java Programming II BCA
meowing...
eating...
16
Unit - II Java Programming II BCA
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
17
Unit - II Java Programming II BCA
A class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
We have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}} Output:
22
33
18
Unit - II Java Programming II BCA
Output:
22
24.9
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)
class Vehicle{
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
19
Unit - II Java Programming II BCA
Vehicle is running
A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Java, as an object-oriented programming language, supports one of the key features of OOP -
polymorphism. It allows objects to take on multiple forms, and one way it achieves this is
through a mechanism called dynamic method dispatch. The feature plays a crucial role in
achieving flexibility and extensibility in Java programs.
Dynamic method dispatch or run-time polymorphism is the mechanism through which the
correct version of an overridden method is called at runtime. When a subclass overrides a
method from its super class, the overridden method in the subclass is executed when called
on an instance of the subclass, even if the reference to the object is of the super class type.
[Link]
class Animal {
void makeSound() {
[Link]("Generic Animal Sound");
}
}
20
Unit - II Java Programming II BCA
Output:
Bark
Meow
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
If you make any variable as final, you cannot change the value of final variable(It will
be constant).
21
Unit - II Java Programming II BCA
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
22
Unit - II Java Programming II BCA
//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
23
Unit - II Java Programming II BCA
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e.
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
24
Unit - II Java Programming II BCA
}
}
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
25
Unit - II Java Programming II BCA
Interface in Java
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{
26
Unit - II Java Programming II BCA
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
interface Printable{
void print();
}
interface Showable{
void show();
27
Unit - II Java Programming II BCA
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
(Unit – II completed)
28
Unit - III[Type here] Java Programming II BCA
Unit –III
Exception Handling: try – catch - throw - throws –- finally – Built-in exceptions - Creating
own Exception classes - garbage collection, finalise -Multithreaded Programming: Thread Class
- Runnable interface – Synchronization – Using synchronized methods – Using synchronized
statement - Interthread Communication – Deadlock.
Exception Handling:
1. ClassNotFoundException,
2. IOException,
3. SQLException,
4. RemoteException, etc.
An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
1
Unit - III[Type here] Java Programming II BCA
Checked Exception
Unchecked Exception
Error
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means
we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an
exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception
in the method. It doesn't throw an exception. It is always used with method signature.
[Link]
2
Unit - III[Type here] Java Programming II BCA
Output:
Exception in thread main [Link]:/ by zero
rest of the code...
Built in Exceptions:
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in exceptions
in Java.
Output:
3
Unit - III[Type here] Java Programming II BCA
ArrayIndexOutOfBoundsException :
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
Java program to demonstrate.
FileNotFoundException
import [Link];
import [Link];
import [Link];
class File_notFound_Demo {
public static void main(String args[])
{
try {
// Following file does not exist
File file = new File("E:// [Link]");
FileReaderfr = new FileReader(file);
}
catch (FileNotFoundException e) {
[Link]("File does not exist");
}
}
}
Output:
Array Index is Out Of Bounds
} class Geeks {
} class MyClass {
public static void main(String[] args)
{
Object o = [Link](args[0]).newInstance();
[Link]("Class created for" + [Link]().getName());
}
}
Output:
ClassNotFoundException
FileNotFoundException : This Exception is raised when a file is not accessible or does not
open.
4
Unit - III[Type here] Java Programming II BCA
Output:
File does not exist
IOException : It is thrown when an input-output operation failed or interrupted
JAVA
Output:
error: unreported exception IOException; must be caught or declared to be thrown
InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
error: unreported exception InterruptedException; must be caught or declared to be thrown
NoSuchMethodException : t is thrown when accessing a method which is not found.
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
NullPointerException : This exception is raised when referring to the members of a null
object. Null represents nothing .
JAVA
5
Unit - III[Type here] Java Programming II BCA
[Link](c);
}
catch (StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
}
}
Output:
NullPointerException..
NumberFormatException : This exception is raised when a method could not convert a string
into a numeric format.
Output:
StringIndexOutOfBoundsException
An exception is an issue (run time error) that occurred during the execution of a
program.
When an exception occurred the program gets terminated abruptly and, the code
past the line that generated the exception never gets executed.
In order to create a custom exception, we need to extend the Exception class that belongs
to [Link] package.
6
Unit - III[Type here] Java Programming II BCA
public MyException(String s)
super(s);
// Driver Program
try {
[Link]("Caught");
7
Unit - III[Type here] Java Programming II BCA
[Link]([Link]());
Output
Caught
GeeksGeeks
Java Garbage Collection
In java, garbage means unreferenced objects.
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
8
Unit - III[Type here] Java Programming II BCA
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight processes within
a process.
Threads can be created by using two mechanisms :
Extending the Thread class
Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the [Link] class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We create
an object of our new class and call start() method to start the execution of a thread. Start()
invokes the run() method on the Thread object.
Java
9
Unit - III[Type here] Java Programming II BCA
classMultithreadingDemo extendsThread {
publicvoidrun()
try{
[Link](
+ " is running");
catch(Exception e) {
// Throwing an exception
[Link]("Exception is caught");
// Main Class
publicclassMultithread {
publicstaticvoidmain(String[] args)
10
Unit - III[Type here] Java Programming II BCA
MultithreadingDemo object
= newMultithreadingDemo();
[Link]();
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
11
Unit - III[Type here] Java Programming II BCA
try{
// Displaying the thread that is running
[Link](
"Thread "+ [Link]().getId()
+ " is running");
}
catch(Exception e) {
// Throwing an exception
[Link]("Exception is caught");
}
}
}
// Main Class
classMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
Thread object
= newThread(newMultithreadingDemo());
[Link]();
}
}
}
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
If we extend the Thread class, our class cannot extend any other class because Java
doesn’t support multiple inheritance.
But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it
provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.
Using runnable will give you an object that can be shared amongst multiple threads.
12
Unit - III[Type here] Java Programming II BCA
Synchronization in Java
Multi-threaded programs may often come to a situation where multiple threads try to
access the same resources and finally produce erroneous and unforeseen results.
Types of Synchronization
There are two synchronizations in Java mentioned below:
Process Synchronization
Thread Synchronization
Types of Synchronization
There are two synchronizations in Java mentioned below:
Process Synchronization
Thread Synchronization
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. There are three types of Mutual Exclusive mentioned below:
Synchronized method.
Synchronized block.
Static synchronization.
Example of Synchronization
import [Link].*;
import [Link].*;
13
Unit - III[Type here] Java Programming II BCA
// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);
Output
Sending Hi
14
Unit - III[Type here] Java Programming II BCA
Hi Sent
Sending Bye
Bye Sent
1. wait()
2. notify()
3. notifyAll()
4. wait() method
The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws InterruptedException It waits for the specified amount of time.
2) notify () method
The notify () method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax:
3) notifyAll() method
15
Unit - III[Type here] Java Programming II BCA
Syntax:
After completion of the task, thread releases the lock and exits the monitor state of the object.
[Link]
class Customer{
int amount=10000;
16
Unit - III[Type here] Java Programming II BCA
if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link]-=amount;
[Link]("withdraw completed...");
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){[Link](15000);}
}.start();
new Thread(){
public void run(){[Link](10000);}
}.start();
}}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
17
Unit - III[Type here] Java Programming II BCA
Deadlock in Java
synchronized (resource2) {
[Link]("Thread 1: locked resource 2");
}
}
}
};
18
Unit - III[Type here] Java Programming II BCA
synchronized (resource1) {
[Link]("Thread 2: locked resource 1");
}
}
}
};
[Link]();
[Link]();
}
}
Output:
Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:
Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason for
a deadlock condition. It normally happens when you give locks to multiple threads.
Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to
the unnecessary threads that cause the deadlock condition.
Using Thread Join: A deadlock usually happens when one thread is waiting for the other to
finish. In this case, we can use join with a maximum time that a thread will take.
19
Unit - IV Java Programming II BCA
Unit – IV
The AWT class hierarchy - Swing: Introduction to Swing - Hierarchy of swing components.
Containers - Top level containers - JFrame - JWindow - JDialog - JPanel - JButton -
JToggleButton - JCheckBox - JRadioButton - JLabel,JTextField - JTextArea - JList -
JComboBox – JscrollPane - Event Handling: Events - Event sources - Event Listeners - Event
Delegation Model (EDM) - Handling Mouse and Keyboard Events
Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
Layout Managers: Layout Managers are responsible for arranging data in the
containers some of the layout managers are BorderLayout, FlowLayout, etc.
Event Handling: AWT allows the user to handle the events like mouse clicks, key
presses, etc. using event listeners and adapters.
Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert
images and write text in the components of a Java Application.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI] components as AWT and is
part of the standard Java distribution. By today’s application GUI requirements, AWT is a
limited implementation, not quite capable of providing the components required for
developing complex GUIs required in modern commercial applications. The AWT
component set has quite a few bugs and does take up a lot of system resources when
compared to equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with programmers
creating GUI’s for commercial applications.
Swing is a Set of API (API
(API- Set of Classes and Interfaces)
Swing is Provided to Design Graphical User Interfaces
Swing is an Extension library to the AWT (Abstract Window Toolkit)
Includes New and improved Components that have been enhancing the he looks and
Functionality of GUIs’
Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets
1
Unit - IV Java Programming II BCA
It Employs model/view design architecture.
Swing is more portable and more flexible than AWT, the Swing is built on top of the
AWT.
Swing is Entirely written in Java.
Java Swing Components are Platform-independent, and The Swing Components are
lightweight.
Swing Supports a Pluggable look and feel and Swing provides more powerful
components.
such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
Further Swing Follows MVC.
Difference between Java Swing and Java AWT
There are certain points from which Java Swing is different than Java AWT as mentioned
below:
Java AWT Java Swing
Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.
Execution Time is more than Swing. Execution Time is less than AWT.
2
Unit - IV Java Programming II BCA
Method Description
The methods of Component class are widely used in Java swing that are given below.
1. Window: Window is a top-level container that represents a graphical window or dialog box.
2. The Window class extends the Container class, which means it can contain other components,
3. such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for
3. grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have menu bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.
3
Unit - IV Java Programming II BCA
JComponent
to build unique components that are suited to the particular requirements of their applications.
Syntax of JComponent
public abstract class JComponent extends
Container implements Serializable
Java Swing was introduced as part of the Java Foundation Classes (JFC) in the late 1990s,
aiming to address the limitations of the earlier Abstract Window Toolkit (AWT).
Let's see a simple swing example where we are creating one button and adding it on the JFrame
import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
4
Unit - IV Java Programming II BCA
We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.
import [Link].*;
public class Demo {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
[Link](130,100,100, 40);
[Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500 height
10. [Link](null);//using no layout managers
11. [Link](true);//making the frame visible
12. }
13. public static void main(String[] args) {
14. new Demo();
15. }
16. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
5
Unit - IV Java Programming II BCA
import [Link].*;
public class DemoSwing extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
[Link](130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
10. setVisible(true);
11. }
12. public static void main(String[] args) {
13. new Simple2();
14. }}
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot edit it directly.
Constructor Description
6
Unit - IV Java Programming II BCA
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. [Link](50,100, 100,30);
12. [Link](l1); [Link](l2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. }
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
A key element of graphical user interfaces (GUIs) in Java that is used to create interactive buttons
is the JButton class. Users can click these labelled buttons to initiate particular operations within the
it can be used in a variety of settings and operating systems. It is descended from the AbstractButton class,
which offers shared functionality for all button kinds in the Swing GUI framework and Java's
Abstract Window Toolkit (AWT). Developers can improve the usability and interactivity of their
Java programmes by adding sensible user interface components to their JButton objects through
configuration.
Constructor Description
7
Unit - IV Java Programming II BCA
JButton() It creates a button with no text and icon.
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
10. [Link](true);
11. }
12. }
Output:
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
8
Unit - IV Java Programming II BCA
public class JTextField extends JTextComponent implements SwingConstants
Constructor Description
import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. [Link](50,150, 200,30);
12. [Link](t1); [Link](t2);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. }
17. }
Output:
9
Unit - IV Java Programming II BCA
Java JTextArea
The object of a JTextArea class is a multi-line region that displays text. It allows the editing
multi-line text component in Java is represented by the JTextArea class, which is a component
Constructor Description
10
Unit - IV Java Programming II BCA
import [Link].*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
10. [Link](null);
11. [Link](true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. }}
Output:
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry.
11
Unit - IV Java Programming II BCA
Constructor Description
import [Link].*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
[Link](20,100, 80,30);
[Link](100,100,100,30);
[Link](value); [Link](l1);
10. [Link](300,300);
11. [Link](null);
12. [Link](true);
13. }
14. }
Output:
12
Unit - IV Java Programming II BCA
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".
Constructor Description
13
Unit - IV Java Programming II BCA
Methods Description
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
10. [Link](checkBox1);
11. [Link](checkBox2);
12. [Link](400,400);
13. [Link](null);
14. [Link](true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}
Output:
14
Unit - IV Java Programming II BCA
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one
Constructor Description
15
Unit - IV Java Programming II BCA
Methods Description
void setIcon(Icon b)
It is used to set the specified Icon on the button.
import [Link].*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
[Link](75,50,100,30);
[Link](75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. [Link](r1);[Link](r2);
12. [Link](r1);[Link](r2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
16
Unit - IV Java Programming II BCA
Output
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by
Constructor Description
Methods Description
17
Unit - IV Java Programming II BCA
void addItem(Object anObject) It is used to add an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
10. [Link](null);
11. [Link](400,500);
12. [Link](true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }
Output:
18
Unit - IV Java Programming II BCA
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click,
cursor movement, keypress through keyboard or page scrolling, etc.
The [Link] package can be used to provide various event classes.
Classification of Events
Foreground Events
Background Events
Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to
interaction by the user on components in Graphic User Interface (GUI). Interactions
nteractions are nothing
but clicking on a button,
scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background
19
Unit - IV Java Programming II BCA
events. Examples of these events are operating system failures/interrupts,
operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation
Event model.
Delegation Event model
It has Sources and Listeners.
Source: Events are generated from the source. There are various sources
like buttons, checkboxes, list, menu
menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source.
Each of these listeners represents interfaces that are responsible for handling
events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
20
Unit - IV Java Programming II BCA
ActionListener actionPerformed()
21
Unit - IV Java Programming II BCA
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
mouseMoved()
MouseMotionListener
mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
windowActivated()
windowDeactivated()
windowOpened()
WindowListener windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
22
Unit - IV Java Programming II BCA
Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
Within Class
Other Class
Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may
throw errors due to the unavailability of some packages.
Event Handling Within Class
Java
[Link].*;
[Link].*;
TextFieldtextField;
GFGTop()
// Component Creation
textField = newTextField();
23
Unit - IV Java Programming II BCA
[Link](this);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
publicvoidactionPerformed(ActionEvent e)
24
Unit - IV Java Programming II BCA
[Link]("GFG!");
publicstaticvoidmain(String[] args)
newGFGTop();
Output
[Link].*;
[Link].*;
25
Unit - IV Java Programming II BCA
classGFG1 extendsFrame {
TextFieldtextField;
GFG2()
// Component Creation
textField = newTextField();
[Link](other);
26
Unit - IV Java Programming II BCA
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
publicstaticvoidmain(String[] args)
newGFG2();
Java
[Link].*;
27
Unit - IV Java Programming II BCA
classOther implementsActionListener
lementsActionListener {
GFG2 gfgObj;
Other(GFG1 gfgObj) {
[Link] = gfgObj;
publicvoidactionPerformed(ActionEvent e)
[Link]("Using Different Cl
Classes");
Output
28
Unit - IV Java Programming II BCA
Event Handling By Anonymous Class
Java
[Link].*;
[Link].*;
classGFG3 extendsFrame {
TextFieldtextField;
GFG3()
// Component Creation
textField = newTextField();
29
Unit - IV Java Programming II BCA
[Link](newActionListener() {
publicvoidactionPerformed(ActionEvent e)
[Link]("Anonymous");
});
// add Components
add(textField);
add(button);
setSize(300,300);
// set visibility
setVisible(true);
30
Unit - IV Java Programming II BCA
publicstaticvoidmain(String[] args)
newGFG3();
Output
Handling anonymously
Mouse Events
To handle mouse events, you can use
the MouseListener and MouseMotionListener interfaces. The MouseListener interface
handles events like mouse clicks, presses
presses,, releases, and when the mouse enters or exits a
component. The MouseMotionListener interface handles events when the mouse is moved or
dragged.
Example of MouseListener:
Java
import [Link];
import [Link];
import [Link];
@Override
public void mouseClicked(MouseEvent
MouseEvent e) {
31
Unit - IV Java Programming II BCA
[Link]("Mouse Clicked");
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
32
Unit - IV Java Programming II BCA
@Override
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}
@Override
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]());
}
(Unit – IV completed)
33
Unit - V Java Programming III BCA
Unit – 5
Adapter classes - Inner classes -Java Util Package / Collections Framework:Collection &
Iterator Interface- Enumeration- List and ArrayList Vector- Comparator
Adapter Classes
Adapter Classes Java provides a special feature, called an adapter class, that can simplify the
creation of event handlers in certain situations. An adapter class provides an empty implementation
of all methods in an event listener interface. Adapter classes are useful when you want to receive
and process only some of the events that are handled by a particular event listener interface. You
can define a new class to act as an event listener by extending one of the adapter classes and
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you were
interested in only mouse drag events, then you could simply extend MouseMotionAdapter and
override mouseDragged( ).
As you can see by looking at the program, not having to implement all of the methods defined by
the MouseMotionListener and MouseListener interfaces saves you a considerable amount of effort
and prevents your code from becoming cluttered with empty methods. As an exercise, you might
want to try rewriting one of the keyboard input examples shown earlier so that it uses a KeyAdapter
1
Unit - V Java Programming III BCA
Inner Classes
An inner class is a class defined within another class, or even within an expression. This section
illustrates how inner classes can be used to simplify the code when using event adapter classes. To
understand the benefit provided by inner classes, consider the applet shown in the following listing.
It does not use an inner class.
s. Its goal is to display the string “Mouse Pressed” in the status bar of
the applet viewer or browser when the mouse is pressed. There are two :The The Java Library top-level
top
classes in this program. MousePressedDemo extends Applet, and MyMouseAdapter extends
MouseAdapter. The init( ) method of MousePressedDemo instantiates MyMouseAdapter and
provides this object as an argument to the addMouseListener( ) method.
2
Unit - V Java Programming III BCA
2. Reduces programming effort: A programmer doesn’t have to worry about the design of the
Collection but rather he can focus on its best use in his program. Therefore, the basic
concept of Object-oriented
oriented programming (i.e.) abstraction has been successfully
implemented.
3. Increases program speed and quality: Increases performance by providing high- high
performance implementations of useful data structures and algorithms beca
because in this case,
the programmer need not think of the best implementation of a specific data structure. He
can simply use the best implementation to drastically boost the performance of his
algorithm/program.
Hierarchy of the Collection Framework in Java
The utility package, ([Link]) contains all the classes and interfaces that are required by the
collection framework. The collection framework contains an interface named an iterable interface
which provides the iterator to iterate through all the collec
collections.
tions. This interface is extended by the
main collection interface which acts as a root for the collection framework. All the collections
extend this collection interface thereby extending the properties of the iterator and the methods of
this interface. The
he following figure illustrates the hierarchy of the collection framework.
4
Unit - V Java Programming III BCA
Before understanding the different components in the above framework, let’s first understand a
class and an interface.
Class: A class is a user-defined
defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
Interface: Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, nobody). Interfaces
specify what a class must do and not how. It is the blueprint of the class.
Methods of the Collection Interface
This interface contains various methods which can be directly used by all the collections which
implement this interface. They are:
5
Unit - V Java Programming III BCA
1. Iterable Interface
This is the root interface for the entire collection framework. The collection interface extends the
iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The
main functionality of this interface is to provide an iterator for the collections. Therefore, this
interface contains only one abstract method which is the iterator. It returns the
Iterator iterator();
2. Collection Interface
This interface extends the iterable interface and is implemented by all the classes in the collection
framework. This interface contains all the basic methods which every collection has like adding the
data into the collection, removing the data, clearing the data, etc. All these methods are
implemented in this interface because these methods are implemented by all the classes irrespective
of their style of implementation. And also, having these methods in this interface ensures that the
names of the methods are universal for all the collections. Therefore, in short, we can say that this
interface builds a foundation on which the collection classes are implemented.
3. List Interface
This is a child interface of the collection interface. This interface is dedicated to the data of the list
type in which we can store all the ordered collections of the objects. This also allows duplicate data
to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack,
etc. Since all the subclasses implement the list, we can instantiate a list object with any of these
classes.
For example:
List <T> al = new ArrayList<> ();
List <T>ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
The classes which implement the List interface are as follows:
i). ArrayList
ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. The size of an
ArrayList is increased automatically if the collection grows or shrinks if the objects are removed
from the collection. Java ArrayList allows us to randomly access the list. ArrayListcan not be used
for primitive types, like int, char, etc. We will need a wrapper class for such cases.
Let’s understand the ArrayList with the following example:
// Java program to demonstrate the
// working of ArrayList
import [Link].*;
import [Link].*;
6
Unit - V Java Programming III BCA
class GFG {
// Main Method
public static void main(String[] args)
{
// Printing elements
[Link](al);
7
Unit - V Java Programming III BCA
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
Vector
A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed. This is identical to
ArrayList in terms of implementation. However, the primary difference between a vector and an
ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized.
Let’s understand the Vector with an example:
// Java program to demonstrate the
// working of Vector
import [Link].*;
import [Link].*;
class GFG {
// Main Method
public static void main(String[] args)
{
// Printing elements
[Link](v);
Enumerations or popularly known as enum serve the purpose of representing a group of named
constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named
Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with
the enumeration type. A few important features of EnumSet are as follows:
It extends AbstractSet class and implements Set Interface in Java.
EnumSet class is a member of the Java Collections Framework & is not synchronized.
It’s a high-performance set implementation, much faster than HashSet.
All of the elements in an EnumSet must come from a single enumeration type that is
specified when the set is created either explicitly or implicitly.
It does not allow null Objects and throws NullPointerException if we do so.
It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the
collection is modified while iterating.
The Hierarchy of EnumSet is as follows:
[Link]
↳[Link]<E>
↳[Link]<E>
↳[Link]<E>
9
Unit - V Java Programming III BCA
Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type.
Benefits of using EnumSet
Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in
an EnumSet are implemented using bitwise arithmetic operations.
EnumSet is faster
ster than HashSet because we no need to compute any hashCode to find the
right bucket.
The computations are executed in constant time and the space required is very little.
// Java Program to Illustrate Working
// of EnumSet and its functions
// Enum
enumGfg{ CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };
// Main class
// EnumSetExample
public class GFG {
10
Unit - V Java Programming III BCA
// Main driver method
public static void main(String[] args) {
// Creating a set
EnumSet<Gfg> set1, set2, set3, set4;
// Adding elements
set1 = [Link]([Link], [Link],
[Link], [Link]);
set2 = [Link](set1);
set3 = [Link]([Link]);
set4 = [Link]([Link], [Link]);
The EnumSet Class EnumSet extends AbstractSet and implements Set. It is specifically for use with
keys of an enum type. It is a generic class that has this declaration: class EnumSet> Here, E
specifies the elements. Notice that E must extend Enum, which enforces the requirement that the
elements must be of the specified enum type. EnumSet defines no constructors. Instead, it uses the
factory methods shown in Table 17-7 to create objects. All methods can throw
NullPointerException. The copyOf( ) and range( ) methods can also throw
IllegalArgumentException. Notice that the of( ) method is overloaded a number of times. This is in
the interest of efficiency. Passing a known number of arguments can be faster than using a vararg
parameter when the number of arguments is small.
Java Comparator Interface
The Comparator interface is essential for custom sorting in Java. Understanding its proper
implementation can help you write cleaner and more efficient code Java Comparator interface
Java Comparator interface is used to order the objects of a user-defined class.
11
Unit - V Java Programming III BCA
This interface is found in [Link] package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Method Description
public boolean
It is used to compare the current object with the specified object.
equals(Object obj)
public boolean
It is used to compare the current object with the specified object.
equals(Object obj)
A comparator interface is used to order the objects of user-defined classes. A comparator object is
capable of comparing two objects of the same class. Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name,
address, DOB, etc, and we need to sort the array based on Roll no or name?
The Comparator interface is essential for custom sorting in Java. Understanding its proper
implementation can help you write cleaner and more efficient code.
Method 1: One obvious approach is to write our own sort() function using one of the standard
algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll
No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects of a
user-defined class. This interface is present in [Link] package and contains 2 methods
compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort
the elements based on data members. For instance, it may be on roll no, name, age, or anything
else.
Method of Collections class for sorting List elements is used to sort the elements of List by the
given comparator. .
// Comparator Interface
import [Link].*;
import [Link].*;
import [Link].*;
// Class 1
// A class to represent a Student
class Student {
// Attributes of a student
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address)
{
// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
13
Unit - V Java Programming III BCA
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return [Link]([Link]);
}
}
// Class 4
// Main class
class GFG {
(Unit – V Completed)
15