Java Programming Study Material BCA IV
Java Programming Study Material BCA IV
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle) Approved by
UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
STUDY MATERIAL
PROGRAMMING IN JAVA
(II BCA)
LIST OF CONTENTS
1
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
Review of Object Oriented concepts – History of Java – Java buzzwords – JVM architecture -
Datatypes - Variables - Scope and life time of variables - arrays - operators – control
statements - type conversion and casting - simple java program - constructors - methods -
Static block - Static Data – Static Method String and StringBuffer Classes.
Object
Any entity that has state and behavior is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
An Object can be defined as an instance of a class. An object contains an
address and takes up some space in memory.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent
object, it is known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
4
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
Encapsulation
Binding (or wrapping) code and data together into a single unit are known
as encapsulation. For example, a capsule, it is wrapped with different
medicines.
HISTORY OF JAVA
Java History
Java is a high-level programming language originally developed by Sun
Microsystems and released in 1991.
Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX. So java is platform independent.
Java was designed for the development of software for consumer
electronic devices like TVs, VCRs, toasters and such other electronic
devices.
1990 → A team of Sun Microsystems headed by James Gosling was
decided to develop a special software that can be used to manipulate
consumer electronic devices.
1991 → The team announced a new language named “oak”.
1992 → The team demonstrated the application of their new language
to control a list of home applications.
1993 → The team known as Green Project team came up with the
idea of developing web applets.
1994 → The team developed a web browser called “HotJava” to locate
and run applet programs on internet.
1995 → Oak was renamed Java.
1996 → Sun releases Java Development Kit 1.0.
1997→ Sun releases Java Development Kit 1.1.
5
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
JAVA BUZZWORDS
Object Oriented:
Java is truly object-oriented language. Almost everything in Java is an object.
All program code and data reside within objects and classes.
Java comes with an extensive set off classes, arranged in packages
that we can use in our programs by inheritance.
The object model in java is simple and easy to extend.
6
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
High performance
Java performance is impressive for an interpreted language, mainly due
to the use of intermediate byte code. According to sun, java speed is
comparable to the native C/C++.
Java architecture is also designed to reduce overheads during runtime.
Further, the incorporation of multithreading enhances the overall
execution speed of java programs.
JVM ARCHITECTURE
7
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
8
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
DATA TYPES
Data types specify the size and type of values that can be stored.
Numeric
Floating Point Types
✓ Floating point type contains fractional parts such as 26.78 and -7.890.
✓ The float type values are single-precision numbers while the
double types represent double-precision numbers.
✓ Floating point numbers are treated as double-precision quantities.
We must append f or F to the numbers. Example: 1.23f 7.675
9
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
Character Type
✓ Java provides a character data type called char.
✓ The char type assumes a size of 2 bytes but, basically, it can hold
only a single character.
Boolean Type
✓ It is used to test a particular condition during the execution of the program.
✓ There are only two values that a boolean type can take: true or false.
✓ Boolean type is denoted by the keyword boolean and uses only one bit of storage.
VARIABLES
1
0
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
1
1
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
ARRAYS
Creating An Array
Creation of array includes three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
One-dimensional array
A list of items can be given one variable name using only one subscript
and such variable is called a single-subscripted variable or a one-
dimensional array.
Ex: int
mark[];
int[ ]
mark;
1
2
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
arrayname = new
Array length : In java, all arrays store the allocated size in a variable named length.
To know the size of an array, it can be accessed as
[Link]
Two-Dimensional Arrays
To store the values in a table form then two dimensional array is used.
Two subscript are needed to access a value in two dimensional array.
1
4
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
OPERATORS
o Relational operators
BCA – SEMESTER IV
1
6
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
o Assignment operators
o Increment and decrement operators
o Conditional operators
o Bitwise operators
o Special operators
RELATIONAL OPERATORS
❖ Compares two quantities depending on their relation.
❖ Java supports six relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
1
7
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
ASSIGNMENT OPERATORS
Used to assign the value of an expression to a variable.
Assignment operators are usually in the form “=”.
v op=exp;
CONDITIONAL OPERATORS
❖ The character pair ?: is used for conditional operator.
❖ It is also called as ternary operator.
General Form exp1 ? exp2:
exp3 where exp1, exp2, exp3 are
expressions The operator ?: works
as follows
exp1 is evaluated first, if its is true then the exp2 is
1
8
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
1
9
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA
❖ Bitwise operators are used to manipulate data at values of bit – SEMESTER IV
level.
These operators are used for testing the bits, or shifting them to the right or left.
❖ Bitwise operators may not to float or double.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
SPECIAL OPERATORS
❖ Java supports special operators
➢ Instance of operator
➢ Dot operator (or) member selection operator (.)
✓ Instance of operator:
❖ Instance of operator is an object reference operator.
❖ Allow us to determine whether the object belongs to a particular
class or not.
❖ Return true, if the object on the left-hand side is an instance of
the class given on the right-hand side.
Dot operator
The dot operator (.) is used to access the instance variables and methods
of class objects.
It is also used to access classes and sub packages from a package.
2
0
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
When a program breaks the sequential flow and jumps to another part of
the code, it is called branching.
❖ When the branching is based on a particular condition, it is known as
conditional branching.
❖ If branching takes place without any decision, it is known as
unconditional branching. if statement
switch statement
Conditional operator statement
if statement
switch statement
Conditional operator statement
IF Statement
The if statement is a powerful decision making statement and is used to
control the flow of execution of statements.
General form if (test expression)
2
1
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
2
2
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
2
3
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
4. Else if ladder
Else If ladder is a chain of ifs in which the statement associated with each
else is an if.
The condition is evaluated from the top to downwards.
➢ As soon as the condition is true, then the statements associated with it are
executed and the control is transferred to the statement -x.
➢ When all the n condition is false, then the final else containing the
default- statement will be executed.
General form Example
If (condition-1) If (marks>79)
statement-1; grade=”honor
else if (condition-2) s”; else if
statement -2; (marks>79)
else if (condition-3) grade=”first”;
statement -3; else if (marks>79)
….. grade=”second”;
else if (condition n) else if (marks>79)
statement -n; grade=”third”;
else else
default-statement; grade=”fail”; // Default-stmt
[Link](“grade=”+grade);
2
4
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
The switch statement tests the value of a given variable against a list of case
values.
Block1, block2 … are statements lists may contain zero or more statements.
If not present, no action takes place when all matches fail and the
control goes to the statement –x.
2
5
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
General form
switch(expression) BCA – SEMESTER IV
{
case value-1:
block-1
break;
case value-2:
block-2
break;
case value-3:
block-3
break;
Example
switch(expression)
{
case ‘1’:
[Link](“ Monday”);
b reak; case ‘2’:
[Link](“Tuesday”);
break; case ‘3’:
[Link](“Wednesday”);
break;
case ‘4’:
[Link](“Thursday”);
break;
………………
………………..
default:
[Link] (“WRONG INPUT”);
break;
………..
……….
default:
default-block break;
}
statement-x;
}
[Link](“ WELCOME TO THIS WEEK”);
2
6
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
SIMPLE JAVA PROGRAM
class SampleOne
{
public static void main (String args[])
{
[Link](“ Java is better than C++”);
}
}
Class declaration
The first line
Class SampleOne declares a class, java is a true object-oriented
language and therefore, everything must be placed inside a class.
class is a keyword and declares that a new class definition follows.
SampleOne is a java identifier that specifies the name of the class to be defined.
Opening Brace
Every class definition in java begins with an opening brace “{“ and
ends with a matching closing brace “}”.
The main line
The third line
public static void main (String args[])
The above line defines a method named main.
2
7
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
23
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
CONSTRUCTORS
ADVANTAGES OF CONSTRUCTORS:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
TYPES OF CONSTRUCTORS:
Based on creating objects in JAVA we have two types of constructors.
They are
Default/parameter less/no argument constructor and Parameterized constructor.
25
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
3 public delete(int start, int end)
Deletes the string starting from the start index until the end index.
4 public insert(int offset, int i)
This method inserts a string s at the position mentioned by the offset.
5 replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with
characters in the specified String.
SUMMARY
The provided document covers a comprehensive overview of Object-Oriented
Concepts, Java History, Java Buzzwords, JVM Architecture, Data Types,
Variables, Operators, Control Statements, Simple Java Program,
Constructors, String and StringBuffer classes. Understand the basic
Object-oriented concepts. Implement the basic constructs of Core Java.
ACTIVITIES
o Identify and list objects and their corresponding classes from everyday
scenarios (e.g., car as an object, Car class).
o Create a hierarchy of classes related to vehicles (e.g., Vehicle -> Car,
Truck) and demonstrate inheritance by sharing properties and
methods.
o Implement method overloading and overriding using simple
scenarios (e.g., Shape class with various subclasses like Circle,
Square).
o Design a Java class that demonstrates encapsulation (private
fields, public methods for access).
o Draw a diagram illustrating the components of the JVM and
explain their functions.
o Simulate scenarios where students must use if-else statements or
switch statements to control program flow based on different
conditions.
26
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
o Create classes with multiple constructors and demonstrate how each
constructor is invoked during object instantiation.
SELF-ASSESSMENT QUESTIONS
1. How would you define an object in your own words?
2. What are the key characteristics of an object? Can you provide examples?
3. How do state and behavior relate to objects? Can you illustrate this with a specific object?
4. Why do objects occupy space in memory, and how does this affect program performance?
5. How is a class like a blueprint? Can you provide a real-world analogy?
6. What types of data and methods are typically included in a class definition?
7. How does inheritance promote code reusability? Can you give an example?
8. What is polymorphism, and why is it a key concept in object-oriented programming?
9. What are the two main types of polymorphism in Java? Can you briefly explain each?
10. How does method overloading demonstrate polymorphism? Can you give a
code example?
11. How does method overriding demonstrate polymorphism? Can you give a code example?
What is encapsulation, and how does it enhance data security in a program?
12. What are conditional statements, and why are they used in programming?
13. How do you structure an if-else statement to handle multiple conditions?
14. What is the purpose of the else if statement, and how does it differ from using multiple
if statements?
15. What are the logical operators (&&, ||, !) in Java, and how are they used in conditional
statements?
16. How would you test the correctness of your conditional statements in your code?
17. What are the different types of constructors in Java? Explain each type briefly.
18. How does a parameterized constructor differ from a default constructor? Provide
an example.
19. What is constructor overloading, and how is it implemented in Java?
20. What are the different types of loops available in Java? Describe each type.
21. What factors can affect the efficiency of a loop? How can you optimize
looping statements?
22. How would you test and debug your loop structures to ensure they function correctly?
27
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
UNIT II
Objective: To equip the student with programming knowledge in Inheritance,
Package, Interface and Exception handling
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. Exception Handling: try – catch- throw - throws –
INHERITANCE
When one class acquires the properties of another class it is known as inheritance.
A class that is inherited is called a super class or base class.
The class that does the inheriting is called a subclass or derived class.
Advantage of inheritance is that it allows reusability of coding.
TYPES OF INHERITANCE
Inheritance may take different forms. They are
Single inheritance (one super class, one sub class)
Multilevel inheritance (derived from a derived class)
Multiple Inheritance
Single inheritance
Single class is one in which there exists single base
class and single derived class.
Multiple Inheritance
Multiple inheritances are one supported by JAVA through classes but it is
supported by JAVA through the concept of interfaces.
Defining a subclass
A subclass is defined as follows:
class subclassname extends superclassname
{
variables declaration;
methods declaration;
}
The keyword extends signifies that the properties of the super
classname are extended to the subclassname.
SUBCLASS CONSTRUCTOR
A subclass constructor is used to construct the instance variables of
both the subclass and the super class.
The sub class constructor uses the keyword super to invoke the
constructor method of the super class.
The keyword super is used in following conditions. Super may only
be used within a subclass constructor method.
The call to super class constructor must appear as the first statement
within the sub class constructor.
The parameter in the super call must match the order and type of
the instance variable declared in the program.
29
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Public Access:
To declare the variable or method as public, it is visible to the entire class
in which it is defined.
Example:
public int number;
public void sum ( ) {................}
Friendly Access:
When no access modifier is specified, the number defaults to a limited
version of public accessibility known as “friendly” level of access.
The difference between the “public” and “friendly” access is that the
public modifier makes fields visible in all classes.
While friendly access makes fields visible only in the same package, but
not in other package.
Protected Access:
The protected modifier makes the fields visible not only to all
classes and subclasses in the same package but also to subclasses in
other packages.
Non-subclasses in other packages cannot access the “protected” members.
Private Access:
Private fields are accessible only with their own class.
They cannot be inherited by subclasses and therefore not accessible in
subclasses. A method declared as private behaves like a method declared
as final.
30
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
private protected int codeNumber;
This gives a visibility level in between the “protected” access and
“private” access. Use public if the field is to be visible everywhere.
Use protected if the field is to be visible everywhere in the current package
and also subclasses in other packages.
Use “default” if the field is to be visible everywhere in the current package only.
METHOD OVERLOADING
Method overloading is creating methods that have same name, but
different parameter lists and different definitions. Method overloading is
used when objects are required to perform similar tasks but using
different input parameters.
When a method is called, java matches up the method name first and
then the number and type of parameters to decide which one of the
definitions to execute. This process is known as polymorphism.
Ex:
class room {
float l,b;
room(float x, float y)
{ l=x;
b=y;
} room(float
x) {
l = b = x;
} int area() {
return(l * b); }
}
METHOD OVERRIDING
A method defined in a super class is inherited by its sub class and is
31
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
used by the objects created by the sub class.
There may be occasions when we want an object to respond to the
same method is called.
This is possible by defining a method in the sub class that has the
same name, same arguments and same return type as a method in
the super class.
When the methods are called, the method defined in the sub class is
invoked and executed instead of the one in the super class. This is
known as overriding.
Example
class Super {
int x;
void display ()
{
[Link](“Super
x=”+x); [Link](“Sub
y=”+y);
}
}
class overridetest {
public static void main (String
args[]) { Sub S1=new Sub (100,
200); [Link] ();
}
}
33
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
ABSTRACT METHODS
When a method is defined as final than that method is not re-
defined in a subclass.
Java allows a method to be re-defined in a sub class and those
methods are called abstract methods.
When a class contains one or more abstract methods, then it should be
declared as abstract class.
When a class is defined as abstract class, it must satisfy following conditions.
o We can’t use abstract classes to instantiate objects directly. For
example Op s = new Op( ) - is illegal because Op is an
abstract class.
o The abstract methods of an abstract class must be defined in its sub class.
o We can’t declare abstract constructors or abstract static methods.
Final allows the methods not redefine in the subclass.
Abstract method must always be redefined in a subclass, thus making
overriding compulsory.
This is done using the modifier keyword abstract in the method definition.
34
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
FINAL CLASSES
• A class that cannot be sub-classed is called a final class.
• It prevents a class being further sub-classed for security reasons.
• Any attempt to inherit these classes will cause
an error. final class Aclass
{ }
Final class Bclass extend someclass
{ }
FINALIZER METHODS
• Initialization→ constructor method is used to initialize an object
when it is declared. This process is called initialization.
• Finalization→finalizer method is just opposite to initialization, it
automatically frees up the memory resources used by the objects. This
process is known as finalization.
• It acts like a destructor.
• The method can be added to any class.
35
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
PACKAGES
A package is a collection of classes, interfaces and sub-packages.
A sub-package in turns divides into classes, interfaces, sub-sub-packages, etc.
Learning about JAVA is nothing but learning about various packages.
By default one predefined package is imported for each and every JAVA
program and whose name is [Link].*.
Whenever we develop any java program, it may contain many
number of user defined classes and user defined interfaces.
If we are not using any package name to place user defined class
interfaces, JVM will assume its own package called NONAME package.
In java we have two types of packages they are
predefined or built-in or core packages and user or secondary or
custom defined packages.
BENEFITS:
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the
package name and the class name.
Packages provide a way to "hide" classes thus preventing other
programs or packages from accessing classes that are meant for
internal use only.
Packages also provide a way for separating "design" form "coding".
36
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
USING PACKAGES
Packages are organized in a hierarchical structure.
o The package named java contains the package awt, which in
turns contain various classes required for implementing graphical
user interface. Best and easiest one to access the class
o Used only once, not possible to access other classes of the
package. There are two ways of accessing the classes stored in a
package
1. Using the fully qualified class name. (Using the package name
containing the class and then appending the class name by using the
dot operator.)
E.g. [Link]
2. Using the import statement, appear at the top of the file. Imported
package class can be accessed anywhere in the program
Syntax:
import [Link];
Or
import packagename.*
These are known as import statements and must appear at the top of the
file, before any class declarations, import is a keyword.
The first statement allows the specified class in the specified
package to be imported. For example, the statement
import [Link];
imports the class Color and therefore the class name can now be directly
used in the program.
The second statement imports every class contained in the specified package.
For example, the statement
import [Link].*;
will bring all classes of [Link] package.
37
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
INTERFACES
Interfaces are basically used to develop user defined data types.
With respect to interfaces we can achieve the concept of multiple inheritances.
With interfaces we can achieve the concept of polymorphism, dynamic
binding and hence we can improve the performance of a JAVA program
in turns of memory space and execution time.
An interface is a construct which contains the collection of purely
undefined methods or an interface is a collection of purely abstract
methods.
interface <InterfaceName>
{
variables declaration;
methods declaration;
}
EXTENDING INTERFACES
Interface can also be extended.
An interface can be sub-interfaced from other interfaces.
The new interface will inherit all the member of the super-interface.
Interface can be extended using the keyword
extends. interface name2 extends name1
{
Body of name2
}
38
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
IMPLEMENTING INTERFACES
Implement the interface using implements keyword.
General form1
General form2
class classname
class classname extends
implements
supperclass implements
interfacename
interface1,interface2,………..
{
{
body of classname
body of classname
}
}
EXCEPTION HANDLING
Exceptions: An exception is a condition that is caused by a run-time error in
the program.
A java exception is an object that descirbes an error condition occurred
in a piece of code. Exceptions can be generated by the Java run-time
system or they can be manually generated by code.
Exceptions thrown by a Java relate to fundamental errors that violate
the rules of the Java language or the constraints of the Java execution
environment.
Manually generated exceptions are typically used to report some error
condition to the caller of a method.
Java exception handling is managed via try, catch, throw, throw and finally.
Exception types
All exceptions are subclasses of Throwable class. There are two
subclasses that partition exception into two distinct branches,
Exception and Error.
Exception – this class is used for exceptional conditions that user
program should catch. The class defined for custom exceptions are
subclass to this class. A special subclass called RuntimeException,
Exception of this class is automatically defined for a program.
Error – This class defines exceptions that are not expected under
39
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
normal circumstances. Exceptions of this type are used by the Java run-
time system to indicate errors having to be deal by the run-time
environment itself.
40
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The try block can have one or more statements that could generate
an exception. If any one statement generate an exception, the
remaining statements in the block are skipped and execution jumps
to the catch block.
The catch block have one or more statements that are necessary to
process the exception. Every try statement should be followed by
atleast one catch statement.
A try statement may have multiple catch blocks.
A finally block is added to a try statement to handle an exception
41
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
that is not handled or caught by the previous catch statements. A
finally block can be
42
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
used to handle any exception within in a try block. A finally block may
be added immediately after the try block or after the last catch
block.
When a finally block is defined, this is guaranteed to executed,
regardless of whether or not an excpetion is thrown.
Nested try statements: the try statement can be nested. Each time a try
statement is entered, the context of that exception is pushed on the
stack. If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and next try statement’s catch
handlers are inspected for a match. This continues until one of the catch
statements succeeds, if no catch statement matches, then the Java run-
time system will handle the exception.
44
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
type method-name(parameter-list) throws exception-list
{
// body of method
}
where exception-list is a comma separated list of the exceptions that a
method can throw.
45
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
SUMMARY
Implement inheritance, packages, interfaces and exception handling of Core Java.
ACTIVITIES
o Create two classes, one as a superclass and the other as a
subclass. Demonstrate inheritance by extending the superclass in the
subclass.
o Discuss scenarios where each type of inheritance would be
useful. Create example classes demonstrating each type of
inheritance.
o Provide a superclass with a parameterized constructor. Create a
subclass that inherits from it and initialize both superclass and subclass
variables using the super keyword.
o Discuss scenarios where overriding is useful and what happens when a
method is called using superclass and subclass references.
o Create an abstract class with one or more abstract methods. Provide
concrete implementations in subclasses. Discuss why abstract classes
are useful compared to concrete classes.
o Create a final class and demonstrate why it cannot be subclassed.
Similarly, create a final method and discuss why it cannot be
overridden.
o Create classes in different packages and demonstrate how access
modifiers (public, protected, default, private) affect visibility across
packages.
o Create interfaces with multiple methods. Implement these interfaces in
classes and discuss how interfaces provide flexibility compared to
classes.
o Provide classes with methods that throw exceptions. Demonstrate how
exceptions propagate up the class hierarchy and how different
exceptions can be handled using try-catch blocks.
SELF-ASSESSMENT QUESTIONS
46
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
1. What are the different types of inheritance supported in Java? Can you explain
each type?
2. How do you define a superclass and a subclass in Java? What is the relationship
between them?
3. What is method overriding, and how does it relate to inheritance? Provide
an example.
4. How does inheritance facilitate polymorphism in Java?
5. How do the public, protected, and private access modifiers affect member
access in inheritance?
6. What is a package in Java, and why is it used?
7. How do you implement an interface in a class? What is the syntax?
8. What are default and static methods in interfaces? How do they differ from
regular interface methods?
9. How do you use try-catch blocks to handle exceptions? Provide a code example.
10. What is the purpose of the finally block in exception handling? When is
it executed?
11. What
of each?
47
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
UNIT III
Objective: To enable the students to understand the concepts Multithreaded Programming and I/O
handling.
Character stream - Reading console Input and Writing Console output - File Handling.
MULTITHREADED PROGRAMMING
A flow of control is known as thread.
If a program contains multiple flow of controls for achieving concurrent
execution then that program is known as multithreaded program.
A program is said to be a multithreaded program if and only if in which
there exist ‘n’ number of sub-programs there exist a separate flow of
control.
All such flow of controls are executing concurrently such flow of
controls are known as threads and such type of applications or
programs is called multithreaded programs.
A thread is similar to a program that has a single flow of control. It has
a beginning a body, and an end, and executes commands sequentially.
CREATING THREADS
Creating threads in Java is simple.
Threads are implemented in the form of objects that contain a method called run( ).
The run( ) method is the heart and soul of any thread. It makes up the
entire body of the thread and is the only method in which the thread’s
behavior can be implemented.
A typical run( ) would appear as
follows: public void run( )
{
48
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
---- ( Statements for implementing thread )
}
The run( ) method should be invoked by an object of the concerned thread.
This can be achieved by creating the thread and initiating it with the help
of another thread method called start( ).
I/O STREAMS
A file is a collection of related records, a record is collection of fields and a
filed is a group of characters. Storing and managing data using files is
50
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
known as file processing which includes tasks such as creating files,
updating files and manipulation of data. Java handles the file processing in
the form of streams. Java also supports to write and read an object from
the secondary storage device, known as object serialization.
Concepts of Streams
In file processing, input refers to the flow of data into a program and output
means the flow of data out of a program.
Java uses the concept of streams to represent the ordered sequence of
data, a common characteristic shared by all the input/output devices.
Stream Classes
Java Stream
classes
Memory File 51
Pipe
Memory File Pipe
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The [Link] package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes are classified
into two categories based on the type of data they can process.
52
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O
operations on characters.
Byte stream and character stream classes contain specialized classes to deal
with input and output operations independently on various types of
devices.
Byte Stream Classes
Byte stream classes provide functional features for creating and
manipulating streams and files for reading and writing bytes. Java
provides two kinds of byte stream classes input stream and output stream
classes.
Input stream classes: Input stream classes are used to read bytes, include a
super class known as InputStream and various subclasses for supporting
various input- related functions.
The super class InputStream is an abstract class. The InputStream class
defines methods for performing input functions such as
Reading bytes
Closing streams
Marking positions in streams
Skipping ahead in a stream
Finding the number of bytes in a stream
53
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Output Stream Classes: Output stream classes are derived from the base clas
OutputStream. The OutputStream is an abstract class. The subclasses of
the OutputStream can be used for performing the output operations.
54
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
writeFloat( ) writeBoolean( ) writeUTF( )
55
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The classes used for various input/output operations in both groups are given below.
Task
Object
Interface Interface
DataInput DataOutput
RandomAccessFile
SUMMARY
Implement multi-threading and I/O Streams of Core Java
58
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
ACTIVITIES
o Implement two classes ThreadClassA and ThreadClassB to demonstrate
thread creation using both extending the Thread class and
implementing the Runnable interface.
o Create a shared resource accessed by multiple threads to demonstrate
synchronization.
o Implement a producer-consumer scenario using wait() and notify()
methods for inter-thread communication.
59
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
UNIT IV
Objective: To enable the students to use AWT controls, Event Handling and
Swing for GUI.
AWT Controls: The AWT class hierarchy - user interface components- Labels - Button - Text
Components - Check Box - Check Box Group - Choice - List Box - Panels – Scroll Pane - Menu -
Scroll Bar. Working with Frame class - Colour - Fonts and layout managers.
Event Handling: Events - Event sources - Event Listeners - Event Delegation Model (EDM)
- Handling Mouse and Keyboard Events - Adapter classes - Inner classes
AWT CONTROLS
COMPONENT
The class Component is the abstract base class for the non menu user-
interface controls of AWT. Component represents an object with graphical
representation.
CONTAINER
The Container is a component in AWT that can contain another components
60
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at
their specific locations. Thus it contains and controls the layout of
components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You
must use frame, dialog or another window for creating a window. We need
to create an instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu
bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have
menu bars. It can have other components like button, text field, scrollbar
etc. Frame is most widely used container while developing an AWT
application.
LABEL
Label is a passive control because it does not create any event when
accessed by the user. The label control is an object of Label. A label
61
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
displays a single line of read- only text. However the text can be changed
by the application programmer but cannot be changed by the end user in
any way.
Field
static int CENTER -- Indicates that the label should be centered.
static int LEFT -- Indicates that the label should be left justified.
static int RIGHT -- Indicates that the label should be right justified.
Constructors
Label(String text) - Constructs a new label with the specified string of text,
left justified.
Label(String text, int alignment) - Constructs a new label that presents the
specified string of text with the specified alignment.
Methods
void setText(String text) It sets the texts for label with the specified text.
BUTTON
A button is basically a control component with a label that generates an
event when pushed. The Button class is used to create a labeled button
that has platform independent implementation. The application result in
62
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
some action when the button is pushed.
When we press a button and release it, AWT sends an instance of
ActionEvent to that button by calling processEvent on the button. The
processEvent method of the button receives the all the events, then it
passes an action event by calling its own method processActionEvent. This
method passes the action event on to action listeners that are interested
in the action events generated by the button.
To perform an action on a button being pressed and
released, the ActionListener interface needs to be implemented. The
registered new listener can receive events from the button by calling
addActionListener method of the button. The Java application can use the
button's action command as a messaging protocol.
CONSTRUCTOR
Button (String text) It constructs a new button with given string as its label.
Methods
void setText (String text) It sets the string message on the button
63
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
TEXT FIELD
The object of a TextField class is a text component that allows a user to
enter a single line text and edit it. It inherits TextComponent class,
which further inherits Component class.
When we enter a key in the text field (like key pressed, key released or
key typed), the event is sent to TextField. Then the KeyEvent is
passed to the registered KeyListener. It can also be done using
ActionEvent; if the ActionEvent is enabled on the text field, then the
ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.
Constructor
64
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
TextField (String text, It constructs a new text field with the given text and
int columns) given number of columns (width).
Methods
65
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
TEXT AREA
The object of a TextArea class is a multiline region that displays text. It
allows the editing of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in
the text area becomes larger than the viewable area, the scroll bar
appears automatically which helps us to scroll the text up and down, or
right and left.
Class constructors:
TextArea (int row, int It constructs a new text area with specified
column)
number of rows and columns and empty string
as text.
TextArea (String text, int It constructs a new text area with the specified
row, int column) text in the text area and specified number
of rows and
columns.
TextArea (String text, int It construcst a new text area with specified
row, int column, int text in text area and specified number of rows
scrollbars) and columns and visibility.
66
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Methods
CHECKBOX
The Checkbox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a Checkbox changes its state
from "on" to "off" or from "off" to "on".
67
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Constructor
Method
68
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
CHECKBOXGROUP
The object of CheckboxGroup class is used to group together a set of
Checkbox. At a time only one check box button is allowed to be in "on"
state and remaining check box button in "off" state. It inherits the object
class.
CHOICE
69
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits Component
class.
Constructor
Methods
String getItem(int index) It gets the item (string) at the given index
position in the choice menu.
70
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
void insert(String item, int Inserts the item into this choice at the
index)
specified position.
LIST
The object of List class represents a list of text items. With the help of the
List class, user can choose either one item or multiple items. It inherits the
Component class.
Constructor
71
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Methods
void add(String item, int index) It adds the specified item into list
at the
72
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
73
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
array of objects.
74
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
PANEL
The Panel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the Container
class.
It doesn't have title bar.
MENU
The object of MenuItem class adds a simple labeled menu item on menu.
The items used in a menu must belong to the MenuItem or any of its
subclass.
The object of Menu class is a pull down menu component which is
displayed on the menu bar. It inherits the MenuItem class.
Constructor
Frame()
Constructs a new instance of Frame that is initially invisible.
Frame(GraphicsConfiguration gc)
Constructs a new, initially invisible Frame with the specified
GraphicsConfiguration.
Frame(String title)
Constructs a new, initially invisible Frame object with the specified title.
Methods
void addNotify()
Makes this Frame displayable by connecting it to a native screen resource.
int getCursorType()
Deprecated. As of JDK version 1.1, replaced by [Link]().
int getExtendedState()
Gets the state of this
frame.
Image getIconImage()
Returns the image to be displayed as the icon for this frame.
Rectangle getMaximizedBounds()
Gets maximized bounds for this
76
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
frame.
MenuBar getMenuBar()
Gets the menu bar for this frame.
int getState()
Gets the state of this frame (obsolete).
String getTitle()
Gets the title of the frame.
boolean isResizable()
Indicates whether this frame is resizable by the user.
boolean isUndecorated()
Indicates whether this frame is undecorated.
void remove(MenuComponent m)
Removes the specified menu bar from this frame.
void removeNotify()
Makes this Frame undisplayable by removing its connection to its
native screen resource.
void setExtendedState(int
state) Sets the state of this
frame.
77
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
void setMaximizedBounds(Rectangle
bounds) Sets the maximized bounds for
this frame.
FONTS
In Java, Font is a class that belongs to the [Link] package. It implements
the Serializable interface. FontUIResource is the direct known subclass of
the Java Font class.
It represents the font that are used to render the text. In Java, there are
two technical terms that are used to represent font are characters and
Glyphs.
There are two types of fonts in Java:
o Physical Fonts
o Logical Fonts
Physical Fonts
Physical fonts are actual Java font library. It contains tables that maps
character sequence to glyph sequences by using the font technology
such as TrueType Fonts (TTF) and PostScript Type 1 Font. Note that all
78
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
implementation of Java must support TTF. Using other font technologies is
implementation dependent. Physical font includes the name such as
Helvetica, Palatino, HonMincho, other font names. The property of the
physical font is that it uses the limited set of writing systems such as Latin
characters or only Japanese and Basic Latin characters. It may vary as to
configuration changes. If any application requires a specific font, user
can bundle and instantiate that font by using the createFont() method of
the Java Font class.
Logical Fonts
Java defines five logical font families that are Serif, SansSerif, Monospaced,
Dialog, and DialogInput. It must be supported by the JRE. Note that JRE
maps the logical font names to physical font because these are not the
actual font libraries. Usually, mapping implementation is locale
dependent. Each logical font name map to several physical fonts in order
to cover a large range of characters.
LAYOUT MANAGER
The Layout managers enable us to control the way in which visual
components are arranged in the GUI forms by determining the size and
position of components within the containers.
Types of LayoutManager
There are 4 layout managers in Java
FlowLayout: It arranges the components in a container like the words
79
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
on a page. It fills the top line from left to right and top to bottom. The
components are arranged in the order as they are added i.e. first
components appears at top left, if the container is not wide enough to
display all the components, it is wrapped around the line. Vertical and
horizontal gap between components can be controlled. The
components can be left, center or right aligned.
BorderLayout: It arranges all the components along the edges or the
middle of the container i.e. top, bottom, right and left edges of the area.
The components added to the top or bottom gets its preferred height,
but its width will be the width of the container and also the
components added to the left or right gets its preferred width, but its
height will be the remaining height of the container. The components
added to the center gets neither its preferred height or width. It covers
the remaining area of the container.
GridLayout: It arranges all the components in a grid of equally sized
cells, adding them from the left to right and top to bottom. Only one
component can be placed in a cell and each region of the grid will have
the same size. When the container is resized, all cells are automatically
resized. The order of placing the components in a cell is determined as
they were added.
GridBagLayout: It is a powerful layout which arranges all the
components in a grid of cells and maintains the aspect ration of the
object whenever the container is resized. In this layout, cells may be
different in size. It assigns a consistent horizontal and vertical gap
among components. It allows us to specify a default alignment for
components within the columns or rows.
EVENT HANDLING
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click
on button, dragging mouse etc. The [Link] package provides
80
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
many event classes and Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
We can put the event handling code into one of the following places:
Within class
Other class
Anonymous class
81
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
One of the key benefits of the Delegation Event Model in Java is that it
allows for a high level of modularity in Java applications. By separating the
event source from the event listener, you can create more flexible and
scalable code. This model also allows for easy customization, as different
event listeners can be created to handle different types of events.
Keyboard Events
The Java KeyListener is notified whenever you change the state of key. It
is notified against KeyEvent. The KeyListener interface is found in
[Link] package, and it has three methods.
Interface declaration
83
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
ADAPTER CLASSES
In Java's event handling mechanism, adapter classes are abstract classes
provided by the Java AWT (Abstract Window Toolkit) package for receiving
various events. These classes contain empty implementations of the
methods in an event listener interface, providing a convenience for
creating listener objects.
The adapter classes in Java are
WindowAdapter
KeyAdapter
MouseAdapter
FocusAdapter
ContainerAdapter
ComponentAdapter
These adapter classes implement interfaces like WindowListener,
KeyListener, MouseListener, FocusListener, ContainerListener, and
ComponentListener respectively, which contain methods related to
specific events.
84
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
INNER CLASSES
A Java inner class is a class that is defined inside another class. The
concept of inner class works with nested Java classes where outer and
inner classes are used.
The main class in which inner classes are defined is known as the outer
class and all other classes which are inside the outer class are known as
Java inner classes.
SUMMARY
Implement AWT and Event handling.
ACTIVITIES
o Represents an object with graphical representation.
SELF–ASSESSMENT QUESTIONS
1. What is AWT, and how does it differ from Swing?
2. What are the primary components provided by AWT?
3. What is the purpose of the `Frame` class in AWT?
4. What are layout managers in AWT? Name and explain a few common ones.
5. How do you set a layout manager for a container in AWT?
6. How do you perform custom painting in AWT?
7. What is the role of the `Graphics` class in AWT?
8. What is Swing, and how does it enhance AWT?
9. Explain the concept of "lightweight" components in Swing.
10. What is the "look and feel" of a Swing application, and how can it be changed?
11. How do you set a custom look and feel for a Swing application?
12. Discuss the advantages and disadvantages of using Swing over AWT.
13. Can you use AWT components in a Swing application? If so, how?
14. What is event handling in Java?
15. What is an event listener, and how do you implement one in Java?
16. How do you use ActionListener, MouseListener, and KeyListener in
your applications?
17. How do you register an event listener with a component?
18. What is the Event Dispatch Thread, and why is it important in Swing?
19. How do you create and handle custom events in Java?
20. What is the difference between using built-in events and custom events?
85
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
UNIT V
Objective: To equip the student with programming knowledge SWING
components.
Swing: Introduction to Swing - Hierarchy of swing components. Containers - Top level containers -
JFrame - JWindow – Jdialog JPanel - JButton - JToggleButton - JCheckBox – JradioButton
JLabel , JTextField
- JTextA
-
JList
JComb
- JScro
SWING
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.
Java Swing provides platform-independent and lightweight components.
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
70
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
71
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The methods of Component class are widely used in java swing that are
given below.
JFrame
The [Link] class is a type of container which inherits the
[Link] class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
Constructors
72
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
device.
Methods
73
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
74
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
JDialog
The JDialog control represents a top level window with a border and a title
used to take some form of input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
Constructors
JPanel
The JPanel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the JComponents
class.
It doesn't have title bar.
Constructors
75
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
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.
Constructors
Methods
JToggleButton
JToggleButton is used to create toggle button, it is two-states button to
switch on or off.
76
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
77
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Constructors
Methods
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its state
from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.
Constructors
Methods
String paramString()
JRadioButton
79
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam
systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Constructors
text.
Methods
JLabel
80
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
The object of JLabel class is a component for placing text in a container. It
is used to display a single line of read only text. The text can be changed
by an application but a user cannot edit it directly. It inherits JComponent
class.
Constructors
Methods
JTextField
The object of a JTextField class is a text component that allows the
81
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
editing of a single line text. It inherits JTextComponent class.
82
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Constructors
Methods
JTextArea
The object of a JTextArea class is a multi line region that displays text. It
allows the editing of multiple line text. It inherits JTextComponent class
Constructors:
83
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Methods:
void append(String s) It is used to append the given text to the end of the
document.
JList
The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or
multiple items. It inherits JComponent class.
Constructors:
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified,
dataModel) non- null, model.
84
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
Methods:
JComboBox
The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu. It inherits JComponent
class.
Constructors:
Methods:
85
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
void removeAllItems() It is used to remove all the items from the list.
JScrollPane
A JscrollPane is used to make scrollable view of a component. When
screen size is limited, we use a scroll pane to display a large component
or a component whose size can change dynamically.
Constructors
JScrollPane(Componen
t, int, int)
Methods
86
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
SUMMARY
Use Swing to create GUI.
ACTIVITIES
o Create a JFrame that displays a simple window with a label and a
button. Clicking the button should display a message dialog.
o Create a JFrame with multiple JPanels, each using a different layout
manager (e.g., BorderLayout, FlowLayout, GridLayout). Add buttons or
other components to each panel to observe how layouts affect
component positioning.
o Construct a JFrame that mimics a simple form (e.g., login screen or
personal information form) using JLabels and JTextFields. Implement
validation by changing text colors or displaying error messages.
o Develop a settings panel within a JFrame that includes checkboxes for
enabling/disabling options and radio buttons for selecting options
exclusively (like selecting a color theme).
o Create a JFrame with both a JComboBox and a JList. Populate them with
87
Mangayarkarasi College of Arts and Science for Women
Affiliated to Madurai Kamaraj University | Accredited with ‘A’ Grade by NAAC (3rd Cycle)
Approved by UGC Under Section 2(f) Status| ISO 9001:2015 Certified Institution
Paravai, Madurai-625402
BCA – SEMESTER IV
data (e.g., items in a dropdown list or selectable items in a list).
Implement event listeners to handle selection changes.
o Customize JButton and JToggleButton components by setting icons,
tooltips, and background colors based on different states (like hover or
click). Experiment with different look and feel options to change the
appearance of components.
o Implement a JFrame with multiple buttons, each performing a different
action (e.g., changing panel content, clearing form data). Use
ActionListener to manage button clicks effectively.
SELF-ASSESSMENT QUESTIONS
1. What is Swing, and how does it differ from AWT?
2. How do you create a `JButton`? Provide an example of how to add it to a
`JFrame`.
3. What is the purpose of `JLabel`, and how can you use it to display
text and images?
4. How do you create a `JTextField`, and how can you retrieve user input from it?
5. What is the difference between `JTextArea` and `JTextField`?
6. How do you create a `JCheckBox`, and how can you determine its state?
7. Explain how to use a `JRadioButton` and group them using a `ButtonGroup`.
8. How do you create a `JComboBox` and add items to it?
9. What is the difference between `JList` and `JComboBox`?
10. W
hat is a `JPanel`, and how can it be used to organize components?
11. How
GridLayout` in Swing?
12. H
ow do you create and display a modal dialog using `JDialog`?
13. H
ow do you attach an `ActionListener` to a button?
14. H
ow can you create a custom component by extending `JComponent`?
15. E
xplain how to override the `paintComponent` method for custom drawing.
88