Java OOP Concepts and Benefits Explained
Java OOP Concepts and Benefits Explained
UNIT I
Object Oriented Programming: Benefits of Object-Oriented Programming.
Introduction to Java: Java buzzwords, byte code. Java Programming Fundamentals, data types,
variables, arrays, operators,expressions, control statements, concepts of classes, objects, constructors,
methods, access control, overloading methods and constructors, introducing access control, static,
final, exploring string class.
Principles of OOPS: Data Abstraction, Data Encapsulation, Polymorphism, and Inheritance
OOP CONCEPTS
· Class: In object-oriented programming, a class is a programming language construct that is
used as a blueprint to create objects. This blueprint includes attributes and methods that the
created objects all share. Usually, a class represents a person, place, or thing - it is an
abstraction of a concept within a computer program. Fundamentally, it encapsulates the state
and behavior of that which it conceptually represents. It encapsulates state through data
placeholders called member variables; it encapsulates behavior through reusable code called
methods.
· Object: An Object is a real time entity. An object is an instance of a class. Instance means
physically happening. An object will have some properties and it can perform some actions.
Object contains variables and methods. The objects which exhibit similar properties and
actions are grouped under one class. ―To give a real world analogy, a house is constructed
according to a specification. Here, the specification is a blueprint that represents a class, and
the constructed house represents the object‖.
o To access the properties and methods of a class, we must declare a variable of that class
type. This variable does not define an object. Instead, it is simply a variable that can refer to
an object.
o We must acquire an actual, physical copy of the object and assign it to that variable. We
can do this using new operator. The new operator dynamically allocates memory for an object
and returns a reference to it. This reference is, more or less, the address in memory of the
object allocated by new. This reference is then stored in the variable. Thus, in Java, all class
objects must be dynamically allocated.
· Encapsulation: Wrapping up of data (variables) and methods into single unit is called
Encapsulation. Class is an example for encapsulation. Encapsulation can be described as a
protective barrier that prevents the code and data being randomly accessed by other code
defined outside the class. Encapsulation is the technique of making the fields in a class private
and providing access to the fields via methods. If a field is declared private, it cannot be
accessed by anyone outside the class.
· Abstraction: Providing the essential features without its inner details is called abstraction
(or) hiding internal implementation is called Abstraction. We can enhance the internal
implementation without effecting outside world. Abstraction provides security. A class
contains lot of data and the user does not need the entire data. The advantage of abstraction is
JAVA PROGRAMMING UNIT-I 2022-23
that every user will get his own view of the data according to his requirements and will not
get confused with unnecessary data. A bank clerk should see the customer details like account
number, name and balance amount in the account. He should not be entitled to see the
sensitive data like the staff salaries, profit or loss of the bank etc. So such data can be
abstracted from the clerks view.
· Inheritance: Acquiring the properties from one class to another class is called inheritance
(or) producing new class from already existing class is called inheritance. Reusability of code
is main advantage of inheritance. In Java inheritance is achieved by using extends keyword.
The properties with access specifier private cannot be inherited.
· Polymorphism: The word polymorphism came from two Greek words ‗poly‘ means ‗many‘
and ‗morphos‘ means ‗forms‘. Thus, polymorphism represents the ability to assume several
different forms. The ability to define more than one function with the same name is called
Polymorphism
e.g.: int add (int a, int b)
float add (float a, int b)
float add (int a , float b)
void add (float a)
int add (int a)
❖ Increased Reliability
Code that is executed frequently will tend to have fewer bugs then code that executed
infrequently. When same components are used in two or more applications, the code will be
exercised more than code that is developed for a single application. Thus bugs in such code
tend to be more quickly discovered and latter applications gain the benefit of using
components are more error free. Similarly the costs of maintenance of shared components can
be split among many projects.
❖ Code Sharing
Code sharing can occur on several levels with OO techniques. Two or more objects will share
the code that they inherit.
❖ Consistency of Interface
When two or more classes inherit from the same super class, the behavior inherit will be same
in all cases. Thus it easier to guarantee that interfaces to similar objects are in fact similar, the
user is not presented with a confusing collection of objects that are almost the same but
behave, and are interacted with, very differently.
JAVA PROGRAMMING UNIT-I 2022-23
❖ Software Components
Inheritance provide programmers with the ability to construct reusable software components.
The goal is to permit the development of new and novel applications that nevertheless require
little or no actual coding.
❖ Rapid Prototyping
When a s/w system is constructed largely out of reusable components, development time can
be concentrated on understanding new and unusual portion of the system. Thus, s/w systems
can be generated more quickly and easily, leading to a style of programming known as rapid
prototyping or exploratory programming.
❖ Polymorphism
Polymorphism in programming languages permits the programmer to generate high-level
reusable components that can be tailored to fit different applications by changes in their low-
level parts.
❖ Information hiding
A programmer who reuses a s/w components needs only to understand the nature of the
component and its interface. It is not necessary for the programmer to have detailed
information concerning matters such as the techniques used to implement the component.
1. OOP‘s allows to decompose a problem into a number of entities called objects and then
builds the data and functions around these objects.
Object A
Data
func
Data
funct Data
funct
Object B Object C
2. Programs are designed around the data being operated rather than the operations
themselves.
3. Data in OOP‘s is hidden, and can be accessed by member functions only.
4. In OOP‘s local variables can be declared at the points where they are actually used. This is
called dynamic declaration.
5. Data and associated operations are unified into a single entity called a class which can be
treated as if it were a normal built in data type, though, it is user defined.
JAVA PROGRAMMING UNIT-I 2022-23
Global Data
Advantages of OOPs:
1. We can eliminate redundant code and extend the use of classes with the concept of
inheritance.
2. We can build the programs from the standard working modules that communicate with
one another, rather than having to start writing the code from beginning. This leads to
saving of development time and higher productivity.
3. The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
4. It is possible to have multiple instance of an object to exist without any interference.
5. Software complexity can be managed.
6. OO systems can be easily upgraded from small to large systems.
Applications of OOPs:
1. Real time systems
2. Simulation and modeling
3. OO database
4. Hypertext, hypermedia and expert-text
5. AI and expert systems
6. Neural networks and parallel programming
7. Decision support and office automation systems
JAVA PROGRAMMING UNIT-I 2022-23
JAVA PROGRAMMING
HISTORY OF JAVA
• In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote. This project was called
Stealth Project but later its name was changed to Green Project.
• In January 1991, Project Manager James Gosling and his team members Patrick
Naughton, Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project.
• Gosling thought C and C++ would be used to develop the project. But the problem he
faced with them is that they were system dependent languages. The trouble with C and
C++ (and most other languages) is that they are designed to be compiled for a specific
target and could not be used on various processors, which the electronic devices might
use.
• James Gosling with his team started developing a new language, which was completely
system independent. This language was initially called OAK. Since this name was
registered by some other company, later it was changed to Java.
• James Gosling and his team members were consuming a lot of coffee while developing
this language. Good quality of coffee was supplied from a place called ―Java Island‘.
Hence they fixed the name of the language as Java. The symbol for Java language is cup
and saucer.
• Sun formally announced Java at Sun World conference in 1995. On January 23rd 1996,
JDK1.0 version was released.
• Java Virtual Machine (JVM) is the heart of entire Java program execution process.
First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler at the time of compilation. Remember, this java
compiler is outside the JVM. This .class file is given to the JVM. Following figure
shows the architecture of Java Virtual Machine.
JAVA PROGRAMMING UNIT-I 2022-23
• In JVM, there is a module (or program) called class loader sub system, which
performs the following instructions:
• · First of all, it loads the .class file into memory.
• · Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
•
• If the byte instructions are proper, then it allocates necessary memory to execute the
program. This memory is divided into 5 parts, called run time data areas, which
contain the data and results while running the program. These areas are as follows:
•
• o Method area: Method area is the memory block, which stores the class code, code
of the variables and code of the methods in the Java program. (Method means
functions written in a class).
•
• o Heap: This is the area where objects are created. Whenever JVM loads a class,
method and heap areas are immediately created in it.
•
• o Java Stacks: Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory is allotted on
Java Stacks. So, Java Stacks are memory area where Java methods are executed.
While executing methods, a separate frame will be created in the Java Stack, where
the method is executed. JVM uses a separate thread (or process) to execute each
method.
• o PC (Program Counter) registers: These are the registers (memory areas), which
contain memory address of the instructions of the methods. If there are 3 methods, 3
PC registers will be used to track the instruction of the methods.
•
• o Native Method Stacks: Java methods are executed on Java Stacks. Similarly, native
methods (for example C/C++ functions) are executed on Native method stacks. To
JAVA PROGRAMMING UNIT-I 2022-23
execute the native methods, generally native method libraries (for example C/C++
header files) are required. These header files are located and connected to JVM by a
program, called Native method interface.
JAVA BUZZWORDS
■ Simple
■ Secure
■ Portable
■ Object-oriented
■ Robust
■ Multithreaded
■ Architecture-neutral
■ Interpreted
■ High performance
■ Distributed
■ Dynamic
Simple
Java is a small and simple language. Java does not use pointers, pre-processor header files,
goto statement and many other. It also eliminates operator overloading and multiple
inheritance. Java inherits the C/C++ syntax and many of the object oriented features of C++.
Secure
Security becomes an important issue for a language that is used for programming on Internet.
Every time when you download a ―normal program‖, here is a risk of viral infection. When
we use a java compatible web browser, we can safely download Java applets without fear of
viral infection. Java achieves this protection by confining a Java program to the Java
execution environment and not allowing it access to other parts of the computer.
Portable
Java programs can be easily moved from one computer system to another, anywhere and
anytime. This is the reason why Java has become a popular language for programming on
Internet.
Object-Oriented
Java is a true 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 of classes,
arranged in packages, that we can use in our programs by inheritance. The object model in
java is simple and easy to extend.
JAVA PROGRAMMING UNIT-I 2022-23
Robust
Java is a robust language. It provides many safeguards to ensure reliable code. To gaon
reliability, Java restricts in few key areas
i. to force you to find mistakes early in program development.
ii. java frees you from having to worry about many of the most common causes of
programming errors.
Java is a strictly typed language. It checks your code at compile time.
Two main reasons for program failure are:
1. Memory management mistakes and
2. Mishandled exceptional conditions (i.e runtime errors)
Memory management can be a difficult, tedious task in traditional programming
environments. For example, in C/C++, the programmer must manually allocates and free all
dynamic memory. This sometime leads to problems, because programmers will either forget
to free memory that has been previously allocated or try to free some memory that another
part of there is still using. Java virtually eliminates these problems by managing allocation
and de allocation. De allocation is completely automatic, because java provides garbage
collection for unused objects.
Exceptional conditions often arise in situations such as division by zero or file not found etc..
Java helps in this area by providing object oriented exception handling.
Multithreaded
Multithreaded means handling multiple tasks simultaneously. This means that we need not
wait for the application to finish one task before beginning another. To accomplish this, java
supports multithreaded programming which allows to write programs that do many things
simultaneously.
Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the
main problems facing programmers is that no guarantee exists that if you write a program
today, it will run tomorrow—even on the same machine. Operating system upgrades,
processor upgrades, and changes in core system resources can all combine to make a program
malfunction. Java Virtual Machine solves this problem. The goal is ―write once; run
anywhere, any time, forever.‖
Java performance is impressive for an interpreted language, mainlt deu to the use of byte
code. This code can be interpreted on any system that provides a JVM. Java was designed to
perform well on very low power CPUs.
Distributed
Java is designed for the distributed environment of the Internet, because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a
file. The original version of Java (Oak) included features for intraaddress- space messaging.
This allowed objects on two different computers to execute procedures remotely. Java revived
JAVA PROGRAMMING UNIT-I 2022-23
these interfaces in a package called Remote Method Invocation (RMI). This feature brings an
unparalleled level of abstraction to client/ server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner.
COMMENTS
/* this comment runs to the terminating symbol, even across line breaks */
DATATYPES
Java defines eight simple (or elemental) types of data: byte, short, int, long, char,
float,double, and boolean. These can be put in four groups:
■ Integers This group includes byte, short, int, and long, which are for whole valued signed
numbers.
■ Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.
■ Characters This group includes char, which represents symbols in a character set, like
letters and numbers.
■ Boolean This group includes boolean, which is a special type for representing true/false
values.
Float Data Types: These data types handle floating point numbers
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127
values in the Unicode character set. For this reason, all the ―old tricks‖ that you have used
with characters in the past will work in Java, too. Even though chars are not integers, in many
cases you can operate on them as if they were integers. This allows you to add two characters
together, or to increment the value of a character variable. For example, consider the
following program:
Boolean Data Type: can handle truth values either true or false
e.g.:- boolean response = true;
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
// a boolean value can control the if statement
if(b) [Link]("This is executed.");
b = false;
if(b) [Link]("This is not executed.");
// outcome of a relational operator is a boolean value
[Link]("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
The type is one of Java‘s atomic types, or the name of a class or interface. The identifier is the
name of the variable.
Eg : int n;
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
JAVA PROGRAMMING UNIT-I 2022-23
// c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}
✓ variables are created when their scope is entered, and destroyed when their scope is
left. This means that a variable will not hold its value once it has gone out of scope.
JAVA PROGRAMMING UNIT-I 2022-23
✓ Therefore, variables declared within a method will not hold their values between calls
to that method.
✓ Also, a variable declared within a block will lose its value when the block is left. Thus,
the lifetime of a variable is confined to its scope.
✓ If a variable declaration includes an initializer, then that variable will be reinitialized
each time the block in which it is declared is entered.
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
When these two conditions are met, a widening conversion takes place.
For example, the int type is always large enough to hold all valid byte values, so no explicit
cast statement is required.
JAVA PROGRAMMING UNIT-I 2022-23
For example, what if you want to assign an int value to a byte variable? This conversion will
not be performed automatically, because a byte is smaller than an int. This kind of conversion
is sometimes called a narrowing conversion, since you are explicitly making the value
narrower so that it will fit into the target type. To create a conversion between two
incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has
this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
[Link]("\nConversion of int to byte.");
b = (byte) i;
[Link]("i and b " + i + " " + b);
[Link]("\nConversion of double to int.");
i = (int) d;
[Link]("d and i " + d + " " + i);
[Link]("\nConversion of double to byte.");
b = (byte) d;
[Link]("d and b " + d + " " + b);
}
}
OPERATORS
Arithmetic operators: These operators are used to perform fundamental operations like
addition, subtraction, multiplication etc.
JAVA PROGRAMMING UNIT-I 2022-23
Assignment operator: This operator (=) is used to store some value into a variable.
Unary operators: As the name indicates unary operator‘s act only on one operand.
Bitwise operators: These operators act on individual bits (0 and 1) of the operands. They
act only on integer data types, i.e. byte, short, long and int.
This operator is called ternary because it acts on 3 variables. The syntax for this operator is:
Variable = Expression1? Expression2: Expression3;
First Expression1 is evaluated. If it is true, then Expression2 value is stored into variable
otherwise Expression3 value is stored into the variable.
OPERATOR HIERARCHY
ENUMERATED TYPES
Enumeration:
• An enumeration is created using the enum keyword. For example, here is a
simple
enum Apple
{
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
ap = [Link];
// Output an enum value.
[Link]("Value of ap: " + ap);
[Link]();
ap = [Link];
// Compare two enum values.
if(ap == [Link])
[Link]("ap contains GoldenDel.\n");
// Use an enum to control a switch statement.
switch(ap)
{
case Jonathan:
[Link]("Jonathan is red.");
break;
case GoldenDel:
[Link]("Golden Delicious is yellow.");
break;
case RedDel:
[Link]("Red Delicious is red.");
break;
case Winesap:
[Link]("Winesap is red.");
break;
case Cortland:
[Link]("Cortland is red.");
break;
}
}
}
JAVA PROGRAMMING UNIT-I 2022-23
CONTROL STATEMENTS
STATEMENTS
Java supports two selection statements: if and switch. These statements allow you to control
the flow of your program‘s execution based upon conditions known only during run time.
if
The if statement is Java‘s conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a boolean value.
int a, b;
// ...
if(a < b) a = 0;
else b = 0;
Nested ifs
JAVA PROGRAMMING UNIT-I 2022-23
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else and
that is not already associated with an else. Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
switch
The switch statement is Java‘s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As
such, it often provides a better alternative than a large series of if-else-if statements.
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
JAVA PROGRAMMING UNIT-I 2022-23
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
case 2:
[Link]("i is two.");
break;
case 3:
[Link]("i is three.");
break;
default:
[Link]("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements
for
while
do-while
These statements are used to repeat same set of instructions specified number of times called
loops. A loop repeatedly executes the same set of instructions until a termination condition is
met.
o while Loop: while loop repeats a group of statements as long as condition is true. Once the
condition is false, the loop is terminated. In while loop, the condition is tested first; if it is
true, then only the statements are executed. while loop is called as entry control loop.
do…while Loop: do…while loop repeats a group of statements as long as condition is true.
In do...while loop, the statements are executed first and then the condition is tested. do…while
loop is also called as exit control loop.
Syntax: do
{
statements;
} while (condition);
for Loop: The for loop is also same as do…while or while loop, but it is more compact
syntactically. The for loop executes a group of statements as long as a condition is true.
[Link] (i + ―\t‖);
}
}
JUMP STATEMENTS
Java supports three jump statements: break, continue and return. These statements transfer
control to another part of the program.
o break:
• break can be used inside a loop to come out of it.
• break can be used inside the switch block to come out of the switch block.
• break can be used in nested blocks to go to the end of a block. Nested blocks represent
a block written within another block.
•
Syntax: break; (or) break label; //here label represents the name of the block.
continue: This statement is useful to continue the next repetition of a loop/ iteration. When
continue is executed, subsequent statements inside the loop are not executed.
Syntax: continue;
{ [Link] (i + ―\t‖);
i++;
if (i <= 20 )
continue;
else
break;
}
}
}
return statement:
• return statement is useful to terminate a method and come back to the calling method.
• return statement in main method terminates the application.
• return statement can be used to return some value from a method to a calling method.
•
Syntax: return;
(or)
return value; // value may be of any type
• In C/C++, program starts executing from main method similarly in Java, program
starts executing from main method. The return type of main method is void because
program starts executing from main method and it returns nothing.
• Since Java is purely an Object Oriented Programming language, without creating an
object to a class it is not possible to access methods and members of a class. But main
method is also a method inside a class, since program execution starts from main
method we need to call main method without creating an object.
• Static methods are the methods, which can be called and executed without creating
objects.
• Since we want to call main () method without using an object, we should declare main
()
Sample Program:
class Sample
{
public static void main(String args[])
{
[Link] ("Hello world");
}
}
• JVM calls main () method using its [Link] () at the time of running the
program. JVM is a program written by Java Soft people (Java development team) and
main () is the method written by us. Since, main () method should be available to the
JVM, it should be declared as public. If we don‘t declare main () method as public,
then it doesn‘t make itself available to JVM and JVM cannot execute it.
• JVM always looks for main () method with String type array as parameter otherwise
JVM cannot recognize the main () method, so we must provide String type array as
parameter to main () method.
• A class code starts with a {and ends with a}. A class or an object contains variables
and methods (functions). We can create any number of variables and methods inside
the class.
• This is our first program, so we had written only one method called main ().
• Our aim of writing this program is just to display a string ―Hello world‖.
• In Java, print () method is used to display something on the monitor. A method should
be called by using [Link] (). So, to call print () method, create an
object to PrintStream class then call [Link] () method.
• An alternative is given to create an object to PrintStream Class i.e. [Link]. Here,
System is the class name and out is a static variable in System class. out is called a
field in System class. When we call this field a PrintStream class object will be created
internally. So, we can call print() method as: [Link] (―Hello world‖); println
() is also a method belonging to PrintStream class. It throws the cursor to the next line
after displaying the result.
• In the above Sample program System and String are the classes present in [Link]
package.
JAVA PROGRAMMING UNIT-I 2022-23
ARRAYS
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array
is accessed by its index. Arrays offer a convenient means of grouping
related information.
One-Dimensional Arrays
type var-name[ ];
Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate. The elements
in the array allocated by new will automatically be initialized to zero.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + " days.");
}
}
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
[Link]("April has " + month_days[3] + " days.");
}
}
Multidimensional Arrays
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable. For
example, the following two declarations are equivalent:
This alternative declaration form is included as a convenience, and is also useful when
specifying an array as a return type for a method.
JAVA PROGRAMMING UNIT-I 2022-23
A stream represents flow of data from one place to other place. Streams are of two types in
java. Input streams which are used to accept or receive data. Output streams are used to
display or write data. Streams are represented as classes in [Link] package.
· [Link]: This represents InputStream object, which by default represents standard input
device that is keyboard.
· [Link]: This represents PrintStream object, which by default represents standard output
device that is monitor.
· [Link]: This field also represents PrintStream object, which by default represents
monitor. [Link] is used to display normal messages and results whereas [Link] is
used to display error messages.
The above two steps can be combined and rewritten in a single statement as:
BufferedReader br = new BufferedReader (new InputStreamReader ([Link]));
· Now, we can read the data coming from the keyboard using read () and readLine () methods
available in BufferedReader class.
· The read method reads a single character from the keyboard but it returns its ASCII
number,which is an integer. Since, this integer number cannot be stored into character type
variable ch, we should convert it into char type by writing (char) before the method. int data
type is converted into char data type, converting one data type into another data type is called
type casting.
· readLine () method accepts a string from keyboard and returns the string into str. In this
case, casting is not needed since readLine () is taking a string and returning the same data
type.
· First, we should accept the integer number from the keyboard as a string, using readLine ()
as: String str = [Link] ();
· Now, the number is in str, i.e. in form of a string. This should be converted into an int by
using parseInt () method, method of Integer class as:
int n = [Link] (str);
If needed, the above two statements can be combined and written as:
int n = [Link] ([Link]() );
· parseInt () is a static method in Integer class, so it can be called using class name as
[Link] ().
· We are not using casting to convert String type into int type. The reason is String is a class
and int is a fundamental data type. Converting a class type into a fundamental data type is not
possible by using casting. It is possible by using the method [Link]().
· We can accept a float value from the keyboard with the help of the following statement:
float n = [Link] ([Link]() );
· We are accepting a float value in the form of a string using [Link] () and then passing
the string to [Link] () to convert it into float. parseFloat () is a static method in Float
class.
· We can accept a double value from the keyboard with the help of the following statement:
double n = [Link] ([Link]() );
JAVA PROGRAMMING UNIT-I 2022-23
· We are accepting a double value in the form of a string using [Link] () and then passing
the string to [Link] () to convert it into double. parseDouble () is a static method
in Double class.
throws IOException at the side of the method where read ()/ readLine () is used.
There are various ways to read input from the keyboard, the [Link] class is one of
[Link] Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
JAVA PROGRAMMING UNIT-I 2022-23
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the
value as a string.
import [Link];
class ScannerTest{
int rollno=[Link]();
String name=[Link]();
double fee=[Link]();
[Link](); } }
JAVA PROGRAMMING UNIT-I 2022-23
INTRODUCING CLASSES
✓ A class is that it defines a new data type.
✓ Once defined, this new type can be used to create objects of that type.
✓ Thus, a class is a template for an object, and an object is an instance of a class
A class is declared by use of the class keyword. The general form of a class definition is
shown here:
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class.
Eg:
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
// compute volume of box
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
JAVA PROGRAMMING UNIT-I 2022-23
}
}
Declaring Objects
First, declare a variable of the class type. This variable does not define an object. Instead, it is
simply a variable that can refer to an object.
Second, acquire an actual, physical copy of the object and assign it to that variable. You can
do this using the new operator. The new operator dynamically allocates (that is, allocates at
run time) memory for an object and returns a reference to it. This reference is, more or less,
the address in memory of the object allocated by new. This reference is then stored in the
variable. Thus, in Java, all class objects must be dynamically allocated.
Introducing Methods
1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the
method does not return a value.
3. The method name—the rules for field names apply to method names as well, but the
convention is a little different.
JAVA PROGRAMMING UNIT-I 2022-23
CONSTRUCTORS
class Box {
double width;
double height;
double depth;
Box() {
[Link]("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}
JAVA PROGRAMMING UNIT-I 2022-23
Parameterized Constructors
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}
ACCESS CONTROL
Encapsulation links data with the code that manipulates it. However, encapsulation provides
another important attribute: access control.
Through encapsulation, you can control what parts of a program can access the members of a
class. By controlling access, you can prevent misuse.
• default
• public
• private
• protected
✓ When a member of a class is modified by the public specifier, then that member can
be accessed by any other code.
✓ When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
✓ When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package. In the classes
developed so far, all members of a class have used the default access mode, which is
essentially public.
Here is an example:
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
[Link](100); // OK
[Link]("a, b, and c: " + ob.a + " " +
ob.b + " " + [Link]());
}
}
✓ Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword.
✓ this can be used inside any method to refer to the current object.
✓ That is, this is always a reference to the object on which the method was invoked.
JAVA PROGRAMMING UNIT-I 2022-23
✓ You can use this anywhere a reference to an object of the current class‘ type is
permitted.
✓ As you know, it is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
✓ We can have local variables, including formal parameters to methods, which overlap
with the names of the class‘ instance variables.
✓ However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
✓ This is why width, height, and depth were not used as the names of the parameters to
the Box( ) constructor inside the Box class. If they had been, then width would have
referred to the formal parameter, hiding the instance variable width. While it is
usually easier to simply use different names, there is another way around this situation.
✓ Because this lets you refer directly to the object, you can use it to resolve any name
space collisions that might occur between instance variables and local variables.
GARBAGE COLLECTION
✓ Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
✓ In some languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
✓ Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
✓ It works like this: when no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed. There is
no explicit need to destroy objects as in C++. Garbage collection only occurs
sporadically (if at all) during the execution of your program.
✓ Sometimes an object will need to perform some action when it is destroyed. For
example, if an object is holding some non-Java resource such as a file handle or
JAVA PROGRAMMING UNIT-I 2022-23
window character font, then you might want to make sure these resources are freed
before an object is destroyed.
✓ To handle such situations, Java provides a mechanism called finalization.
✓ By using finalization, we can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
✓ To add a finalizer to a class, you simply define the finalize( ) method. The Java run
time calls that method whenever it is about to recycle an object of that class.
✓ Inside the finalize( ) method you will specify those actions that must be performed
before an object is destroyed.
✓ The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
✓ Right before an asset is freed, the Java run time calls the finalize( ) method on the
object.
METHOD OVERLOADING
✓ In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different.
✓ When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
✓ Method overloading is one of the ways that Java implements polymorphism.
✓ When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
✓ Thus, overloaded methods must differ in the type and/or number of their parameters.
While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
✓ When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.
class OverloadDemo {
void test() {
[Link]("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
[Link]("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
JAVA PROGRAMMING UNIT-I 2022-23
}
// overload test for a double parameter
double test(double a) {
[Link]("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
[Link]();
[Link](10);
[Link](10, 20);
result = [Link](123.25);
[Link]("Result of [Link](123.25): " + result);
}
}
CONSTRUCTOR OVERLOADING
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}
JAVA PROGRAMMING UNIT-I 2022-23
OUTPUT:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
Constructor must not have return type. Method must have return type.
Constructor name must be same as the class Method name may or may not be
name. same as class name.
PARAMETER PASSING
In general, there are two ways that a computer language can pass an argument to a subroutine.
1. Call-by-value
2. Call-by-reference
✓ The first way is call-by-value. This method copies the value of an argument into the
formal parameter of the subroutine. Therefore, changes made to the parameter of the
subroutine have no effect on the argument.
✓ The second way an argument can be passed is call-by-reference. In this method, a
reference to an argument (not the value of the argument) is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in
JAVA PROGRAMMING UNIT-I 2022-23
the call. This means that changes made to the parameter will affect the argument used
to call the subroutine.
As you will see, Java uses both approaches, depending upon what is passed. In Java, when
you pass a simple type to a method, it is passed by value. Thus, what occurs to the parameter
that receives the argument has no effect outside the method.
RECURSION
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}
✓ When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.
✓ A recursive call does not make a new copy of the method. Only the arguments are
new.
JAVA PROGRAMMING UNIT-I 2022-23
✓ As each recursive call returns, the old local variables and parameters are removed
from the stack, and execution resumes at the point of the call inside the method.
✓ Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional function calls.
Disadvantage:
Many recursive calls to a method could cause a stack overrun. Because storage for parameters
and local variables is on the stack and each new call creates a new copy of these variables, it
is possible that the stack could be exhausted. If this occurs, the Java run-time system will
cause an exception.
Advantage:
The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives.
In Java a string is a sequence of characters. But, unlike many other languages that implement
strings as character arrays, Java implements strings as objects of type String.
The String class supports several constructors. To create an empty String, you call the
default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the
length( ) method, shown here:
int length( )
The following fragment prints ―3‖, since there are three characters in the string s:
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception to
this rule is the + operator, which concatenates two strings, producing a String object as the
result. This allows you to chain together a series of + operations.
JAVA PROGRAMMING UNIT-I 2022-23
Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Each is examined here. Although the characters that comprise a string within a
String object cannot be indexed as if they were a character array, many of the String methods
employ an index (or offset) into the string for their operation. Like arrays, the string indexes
begin at zero.
charAt( )
To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It has this general form:
Here, where is the index of the character that you want to obtain.
getChars( )
If you need to extract more than one character at a time, you can use the getChars( )
method. It has this general form:
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This
method is called getBytes( ), and it uses the default character-to-byte conversions provided by
the platform. Here is its simplest form:
byte[ ] getBytes( )
toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest
way is to call toCharArray( ). It returns an array of characters for the entire string. It has this
general form:
char[ ] toCharArray( )
String Comparison
JAVA PROGRAMMING UNIT-I 2022-23
The String class includes several methods that compare strings or substrings within
strings. Each is examined here.
To compare two strings for equality, use equals( ). It has this general form:
String defines two routines that are, more or less, specialized forms of regionMatches( ). The
startsWith( ) method determines whether a given String begins with a specified string.
Conversely, endsWith( ) determines whether the String in question ends with a specified
string. They have the following general forms:
equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator perform two
different operations. As just explained, the equals( ) method compares the characters inside a
String object. The == operator compares two object references to see whether they refer to
the same instance. The following program shows how two different String objects can
contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
[Link](s1 + " equals " + s2 + " -> " +
[Link](s2));
[Link](s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The variable s1 refers to the String instance created by ―Hello‖. The object referred to by s2
is created with s1 as an initializer. Thus, the contents of the two String objects are identical,
but they are distinct objects. This means that s1 and s2 do not refer to the same objects and
are, therefore, not ==, as is shown here by the output of the preceding example:
compareTo( )
JAVA PROGRAMMING UNIT-I 2022-23
Often, it is not enough to simply know whether two strings are identical. For sorting
applications, you need to know which is less than, equal to, or greater than the next. A string
is less than another if it comes before the other in dictionary order. A string is greater than
another if it comes after the other in dictionary order. The String method compareTo( )
serves this purpose. It has this general form:
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted as shown here:
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
Searching Strings
The String class provides two methods that allow you to search a string for a specified
character or substring:
■ indexOf( ) Searches for the first occurrence of a character or substring.
■ lastIndexOf( ) Searches for the last occurrence of a character or substring.
substring( )
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
concat( )
replace( )
The replace( ) method replaces all occurrences of one character in the invoking string
with another character. It has the following general form:
trim( )
The trim( ) method returns a copy of the invoking string from which any leading and
JAVA PROGRAMMING UNIT-I 2022-23
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase
to uppercase. Nonalphabetical characters, such as digits, are unaffected.
Here are the general forms of these methods:
String toLowerCase( )
String toUpperCase( )
STRINGBUFFER
StringBuffer is a peer class of String that provides much of the functionality of strings. As
you know, String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer may have
characters and substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more characters
preallocated than are actually needed, to allow room for growth. Java uses both classes
heavily, but many programmers deal only with String and let Java manipulate StringBuffers
behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer defines these three constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
The current length of a StringBuffer can be found via the length( ) method, while the total
allocated capacity can be found through the capacity( ) method. They have the following
general forms:
int length( )
int capacity( )
ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer has
been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if
you know in advance that you will be appending a large number of small strings to a
StringBuffer. ensureCapacity( ) has this general form:
setLength( )
To set the length of the buffer within a StringBuffer object, use setLength( ). Its general
form is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative. When you
increase the size of the buffer, null characters are added to the end of the existing buffer. If
you call setLength( ) with a value less than the current value returned by length( ), then the
characters stored beyond the new length will be lost.
The value of a single character can be obtained from a StringBuffer via the charAt( )
method. You can set the value of a character within a StringBuffer using setCharAt( ).
Their general forms are shown here:
getChars( )
To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has
this general form:
append( )
The append( ) method concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object. It has overloaded versions for all the built-in types
and for Object. Here are a few of its forms:
insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the
simple types, plus Strings and Objects. Like append( ), it calls [Link]( ) to obtain
the string representation of the value it is called with. This string is then inserted into the
invoking StringBuffer object. These are a few of its forms:
reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and
deleteCharAt( ). These methods are shown here:
replace( )
substring( )
Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It
has the following two forms:
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.
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.
rollno = r;
name = n;
}
//method to display values
void display(){[Link](rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}
}
Final Keyword:
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
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
JAVA PROGRAMMING UNIT-I 2022-23
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}
}
3) Java final class
final class Bike{}
INTERFACES
Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
Once it is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by
the interface.
By providing the interface keyword, Java allows you to fully utilize the ―one
interface, multiple methods‖ aspect of polymorphism.
Interfaces are designed to support dynamic method resolution at run time. Normally,
in order for a method to be called from one class to another, both classes need to be
present at compile time so the Java compiler can check to ensure that the method
signatures are compatible.
Since interfaces are in a different hierarchy from classes, it is possible for classes that
are unrelated in terms of the class hierarchy to implement the same interface. This is
where the real power of interfaces is realized.
A programmer uses an abstract class when there are some common features shared by all the
objects. A programmer writes an interface when all the features have different
implementations for different objects. Interfaces are written when the programmer wants to
leave the implementation to third party vendors. An interface is a specification of method
prototypes. All the methods in an interface are abstract methods.
· An interface is a specification of method prototypes.
· An interface contains zero or more abstract methods.
· All the methods of interface are public, abstract by default.
· An interface may contain variables which are by default public static final.
· Once an interface is written any third party vendor can implement it.
· All the methods of the interface should be implemented in its implementation classes.
· If any one of the method is not implemented, then that implementation class should be
declared as abstract.
· We cannot create an object to an interface.
· We can create a reference variable to an interface.
· An interface cannot implement another interface.
· An interface can extend another interface.
· A class can implement multiple interfaces.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
JAVA PROGRAMMING UNIT - II 2022-23
Here, access is either public or not used. When no access specifier is included, then
default access results, and the interface is only available to other members of the
package in which it is declared.
When it is declared as public, the interface can be used by any other code. name is the
name of the interface, and can be any valid identifier. Notice that the methods which
are declared have no bodies. They end with a semicolon after the parameter list. They
are, essentially, abstract methods; there can be no default implementation of any
method specified within an interface.
Each class that includes an interface must implement all of the methods.
Variables can be declared inside of interface declarations. They are implicitly final
and static, meaning they cannot be changed by the implementing class. They must
also be initialized with a constant value.
All methods and variables are implicitly public if the interface, itself, is declared as
public.
interface Callback {
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
Here, access is either public or not used. If a class implements more than one interface, the
interfaces are separated with a comma. If a class implements two interfaces that declare the
same method, then the same method will be used by clients of either interface. The methods
that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface
definition.
Page 18
JAVA PROGRAMMING UNIT - II 2022-23
Notice that callback( ) is declared using the public access specifier. When you implement an
interface method, it must be declared as public. It is both permissible and common for classes
that implement interfaces to define additional members of their own.
void nonIfaceMeth() {
[Link]("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
[Link](42);
}
}
INTERFACES CAN BE EXTENDED
One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes. When a class implements an interface that inherits another interface, it
must provide implementations for all methods defined within the interface inheritance chain.
Following is an example:
interface B extends A {
void meth3();
}
Page 19
JAVA PROGRAMMING UNIT - II 2022-23
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
VARIABLES IN INTERFACE
The variables that are declared within an interface are implicitly static and final.
public interface A
{
int x=10;
}
class B implements A
{
int i;
B()
{
i=x+1;
}
void show()
{
[Link](i);
}
}
class Demo
{
public static void main(String args[])
{
B b=new B();
[Link]();
[Link](B.x);
}
}
interface Father
{ double PROPERTY = 10000;
double HEIGHT = 5.6;}
Page 20
JAVA PROGRAMMING UNIT - II 2022-23
interface Mother
{ double PROPERTY = 30000;
double HEIGHT = 5.4;}
class InterfaceDemo
{
public static void main(String args[])
{
MyClass ob1 = new MyClass();
[Link]();
}
}
Page 21
JAVA PROGRAMMING UNIT - II 2022-23
INNER CLASSES
1) Nested static class doesn't need reference of Outer class but non static nested class or Inner
class requires Outer class reference. You can not create instance of Inner class without
creating instance of Outer class. This is by far most important thing to consider while making
a nested class static or non static. A static java inner class cannot have instances. A non-static
java inner class can have instances that belong to the outer class.
2) static class is actually static member of class and can be used in static context e.g. static
method or static block of Outer class.
3) Another difference between static and non static nested class is that you can not access non
static members e.g. method and field into nested static class directly. If you do you will get
error like "non static member can not be used in static context". While Inner class can access
both static and non static member of Outer class.
It is a way of logically grouping classes that are only used in one place: If a class is useful
to only one other class, then it is logical to embed it in that class and keep the two together.
Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to
members of A that would otherwise be declared private. By hiding class B within class A, A's
members can be declared private and B can access them. In addition, B itself can be hidden
from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level
classes places the code closer to where it is used.
class Outer
{
int x=10;
class Inner
{
void show()
{
[Link]("Hello "+x);
}
}
}
class Demo
{
public static void main(String args[])
{
Outer o=new Outer();
Page 22
JAVA PROGRAMMING UNIT - II 2022-23
class Outer
{
static int x=10;
static class Inner
{
void show()
{
[Link]("Hello "+x);
}
}
}
class Demo1
{
public static void main(String args[])
{
Anonymous inner classes of Java are called anonymous because they have no name.
Anonymous inner classes are anonymous and inline. They are essentially inner classes and
defined within some other classes.
Ex1:
public class Demo
{
public static void main(String[] args)
{
Dog dog = new Dog() {
public void someDog ()
{
[Link]("Anonymous Dog");
}
}; // anonymous class body closes here
Page 23
JAVA PROGRAMMING UNIT - II 2022-23
class Dog
{
public void someDog()
{
[Link]("Classic Dog");
}
}
Ex2:
interface Ball {
void hit();
}
}
Page 24
JAVA PROGRAMMING UNIT - II 2022-23
PACKAGES
A unique name had to be used for each class to avoid name collisions. The name you
choose for a class will be reasonably unique and not collide with class names chosen
by other programmers.
Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.
The package is both a naming and a visibility control mechanism. W can define
classes inside a package that are not accessible by code outside that package. We can
also define class members that are only exposed to other members of the same
package.
A package is the set of classes and interface that provides name space management
and access protection.
Defining a Package
To create a package is quite easy: simply include a package command as the first statement in
a Java source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default package, which
has no name.
package pkg;
Java uses file system directories to store packages. More than one file can include the same
package statement. The package statement simply specifies to which package the classes
defined in a file belong. It does not exclude other classes in other files from being part of that
same package. Most real-world packages are spread across many files. You can create a
hierarchy of packages. To do so, simply separate each package name from the one above it by
use of a period.
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system.
Page 25
JAVA PROGRAMMING UNIT - II 2022-23
Understanding CLASSPATH
Packages are mirrored by directories. This raises an important question: How does the
Java run-time system know where to look for packages that you create? The answer
has two parts.
First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in the current directory, or a subdirectory of the
current directory, it will be found.
Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
After installing the JDK, we need to set at least one environment variable in order to able to
compile and run Java programs. A PATH environment variable enables the operating system
to find the JDK executables when our working directory is not the JDK's binary directory.
· Setting environment variables from a command prompt: If we set the variables from a
command prompt, they will only hold for that session. To set the PATH from a command
prompt:
Page 26
JAVA PROGRAMMING UNIT - II 2022-23
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
class AccountBalance {
Page 27
JAVA PROGRAMMING UNIT - II 2022-23
Call this file [Link], and put it in a directory called MyPack. Next, compile
the file. Make sure that the resulting .class file is also in the MyPack directory. Then try
executing the AccountBalance class, using the following command line:
java [Link]
Remember, you will need to be in the directory above MyPack when you execute this
command, or to have your CLASSPATH environmental variable set appropriately. As
explained, AccountBalance is now part of the package MyPack. This means that it cannot be
executed by itself. That is, you cannot use this command line:
java AccountBalance
Access Protection
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
A class has only two possible access levels: default and public. When a class is declared as
public, it is accessible by any other code. If a class has default access, then it can only be
accessed by other code within its same package.
Page 28
JAVA PROGRAMMING UNIT - II 2022-23
Same package
subclass No Yes Yes Yes
Same package
non-subclass No Yes Yes Yes
Different
package
subclass No No Yes Yes
Different
package
non-subclass No No No Yes
Importing Packages
Given that packages exist and are a good mechanism for compartmentalizing diverse
classes from each other, it is easy to see why all of the built-in Java classes are stored
in packages. There are no core Java classes in the unnamed default package; all of the
standard classes are stored in some named package. Since classes within packages
must be fully qualified with their package name or names, it could become tedious to
type in the long dot-separated package path name for every class you want to use. For
this reason, Java includes the import statement to bring certain classes, or entire
packages, into visibility. Once imported, a class can be referred to directly, using only
its name.
The import statement is a convenience to the programmer and is not technically
needed to write a complete Java program. If you are going to refer to a few dozen
classes in your application, however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions.
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).Finally, you specify either an explicit
classname or a star (*), which indicates that the Java compiler should import the entire
package.
The star form may increase compilation time—especially if you import several large
packages. For this reason it is a good idea to explicitly name the classes that you want to use
Page 29
JAVA PROGRAMMING UNIT - II 2022-23
rather than importing whole packages. However, the star form has absolutely no effect on the
run-time performance or size of your classes.
All of the standard Java classes included with Java are stored in a package called java. The
basic language functions are stored in a package inside of the java package called [Link].
Normally, you have to import every package or class that you want to use, but since Java is
useless without much of the functionality in [Link], it is implicitly imported by the
compiler for all programs.
import [Link].*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends [Link] {
}
Example:
package MyPack;
public class Factorial
{
public int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
}
import MyPack.*;
class Test {
public static void main(String args[]) {
Page 30
JAVA PROGRAMMING UNIT - III 2022-23
An error in a program is called bug. Removing errors from program is called debugging.
There are basically three types of errors in the Java program:
· Compile time errors: Errors which occur due to syntax or format is called compile time
errors. These errors are detected by java compiler at compilation time. Desk checking is
solution for compile-time errors.
· Runtime errors: These are the errors that represent computer inefficiency. Insufficient
memory to store data or inability of the microprocessor to execute some statement is
examples to runtime errors. Runtime errors are detected by JVM at runtime.
· Logical errors: These are the errors that occur due to bad logic in the program. These errors
are rectified by comparing the outputs of the program manually.
Error Vs Exception
Error along with RuntimeException & their subclasses are unchecked exceptions. All other
Exception classes are checked exceptions.
Checked exceptions are generally those from which a program can recover & it might be a
good idea to recover from such exceptions programmatically. Examples include
FileNotFoundException, ParseException, etc. A programmer is expected to check for these
exceptions by using the try-catch block or throw it back to the caller.
On the other hand we have unchecked exceptions. These are those exceptions that might not
happen if everything is in order, but they do occur. Examples include
ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-
Page 2
JAVA PROGRAMMING UNIT - III 2022-23
catch or throws clause for RuntimeExceptions & their subclasses but from the language
perspective it is not required to do so. Do note that recovery from a RuntimeException is
generally possible but the guys who designed the class/exception deemed it unnecessary for
the end programmer to check for such exceptions.
Errors are also unchecked exception & the programmer is not required to do anything with
these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an
Error is not possible & the program should be allowed to terminate. Examples include
OutOfMemoryError, StackOverflowError, etc.
Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them.
Errors are derived from [Link], and Exceptions are derived from [Link].
An Error "indicates serious problems that a reasonable application should not try to catch."
An Exception "indicates conditions that a reasonable application might want to catch."
Exception handling provides the following advantages over ``traditional'' error Management
techniques:
Page 3
JAVA PROGRAMMING UNIT - III 2022-23
EXCEPTION HIERARCHY
NullPointerException
NumberFormatException
IndexOutOfBoundsException
etc..
A feature built into the Java language is that Errors and RuntimeExceptions (and their
subclasses) are what are called unchecked exceptions:
An exception can be handled by the programmer where as an error cannot be handled by the
programmer. When there is an exception the programmer should do the following tasks:
· If the programmer suspects any exception in program statements, he should write them
inside try block.
try
{
statements;
}
· When there is an exception in try block JVM will not terminate the program abnormally.
JVM stores exception details in an exception stack and then JVM jumps into catch [Link]
programmer should display exception details and any message to the user in catch block.
Page 4
JAVA PROGRAMMING UNIT - III 2022-23
· Programmer should close all the files and databases by writing them inside finally block.
Finally block is executed whether there is an exception or not.
finally
{ statements;
}
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
Page 5
JAVA PROGRAMMING UNIT - III 2022-23
In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, specify two or more catch clauses, each catching a
different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed. After one catch statement
executes, the others are bypassed, and execution continues after the try/catch block.
class MultiCatch {
public static void main(String args[]) {
try {
int a = [Link];
[Link]("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index oob: " + e);
}
[Link]("After try/catch blocks.");
}
}
The try statement can be nested. That is, a try statement can be inside the block of another
try.
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 the next try statement’s catch handlers are inspected for a match. This
continues until one of the catch statements succeeds, or until all of the nested try statements
are exhausted.
If no catch statement matches, then the Java run-time system will handle the exception.
class NestTry {
public static void main(String args[]) {
try {
int a = [Link];
Page 6
JAVA PROGRAMMING UNIT - III 2022-23
int b = 42 / a;
[Link]("a = " + a);
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
}
}
}
throw
throw clause can be used to throw out user defined exceptions. It is useful to create an
exception object and throw it out of try block
class ThrowDemo
{
static void Demo( )
{
try
{
[Link] ("inside method");
throw new NullPointerException("my data");
}
catch (NullPointerException ne)
{
[Link] ("ne");
}
}
public static void main(String args[])
{
[Link] ( );
}
}
Page 7
JAVA PROGRAMMING UNIT - III 2022-23
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do
this by including a throws clause in the method’s declaration.
A throws clause lists the types of exceptions that a method might throw.
This is the general form of a method declaration that includes a throws clause:
finally
finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.
The finally clause is optional. However, each try statement requires at least one catch
or a finally clause.
Page 8
JAVA PROGRAMMING UNIT - III 2022-23
class FinallyDemo
{
static void procA()
{
try
{
[Link]("inside procA");
throw new RuntimeException("demo");
}
finally
{
[Link]("procA's finally");
}
}
.
static void procB()
{
try
{
[Link]("inside procB");
return;
}
finally
{
[Link]("procB's finally");
}
}
Page 9
JAVA PROGRAMMING UNIT - III 2022-23
}
Here is the output generated by the preceding program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Inside the standard package [Link], Java defines several exception classes. The most
general of these exceptions are subclasses of the standard type RuntimeException. Since
[Link] is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
Page 10
JAVA PROGRAMMING UNIT - III 2022-23
{
super (str);
}
o Whenever required create user exception object and throw it using throw statement.
Ex: - throw me;
Page 11
JAVA PROGRAMMING UNIT - III 2022-23
MULTITHREADING
• One of the exiting feature of OS is that – it allows user to handle multiple tasks
together, called multitasking. In Java we can perform multitasking in a single program
by means of multithreading.
• Thread: Thread is a tiny program running continuously. It is sometimes called as light-
weight process.
[Link] Thread Process
2 Do not require separate address space Each process requires separate address
for its execution. space for its execution.
4 Cost effective because CPU can be Expensive, because when a process uses
shared among multiple threads at a CPU other process has to wait.
time.
Page 1
JAVA PROGRAMMING UNIT - III 2022-23
Page 2
JAVA PROGRAMMING UNIT - III 2022-23
Thread States (Life-Cycle of a Thread): The life cycle of a thread contains several states.
At any time the thread falls into any one of the states.
Uses of Threads:
· Threads are used in designing server side programs to handle multiple clients at a time.
· Threads are used in games and animations.
Page 3
JAVA PROGRAMMING UNIT - III 2022-23
Born State
When we create a thread object, the thread is born and is said to be in new born state. The
thread is not yet scheduled for running. At this state, we can do only one of the following:
born
start() stop()
Ready
Dead
Ready State
The ready state means that the thread is ready for execution and is waiting for the availability
of the processor. i.e. the thread has joined the queue of threads that are waiting for execution.
If all threads have equal priority, then they are given time slots for executin in round robin
fashion. i.e first come first serve manner. The thread that relinquishes control joins the queue
at the end and again waits for its turn. This process of assigning time to threads is known as
time slicing. If we want a thread to relinquish control to another thread of equal priority
before its turn comes.
. . …. . .
Running State
Running means that the processor has given its time to the thread for its execution. The thread
rubs until it relinquishes control on its own or it is preempted by a higher priority thread. A
running thread may relinquish its control in one of the following situations.
1. It has been suspended using suspend() methos. A suspended thread can be revived by
using resume() method. this approach is useful when we want to suspend a thread for
some time due to certaing reasons, but do not want to kill it.
JAVA PROGRAMMING UNIT - III 2022-23
Page 13
JAVA PROGRAMMING UNIT - III 2022-23
suspend()
resume()
2. It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep(time) where time is in milliseconds. This means that the thread
is out of the queue during this time period. The thread re-enters the runnable state as
soon as this time period is elapsed.
sleep(t)
. after(t)
. .
Running Ready Sleeping
thread
3. It has been told to wait until some event occurs. This is done using the wait() method.
The thread can be scheduled to run again using the notify() method.
wait()
. . notify() .
Running Ready Sleeping
thread
Blocked State
A thread is said to be blocked when it is prevented from entering into the ready state and
subsequently the running state. This happens when the thread is suspended, sleeping, or
waiting in order to satisfy certain conditions. A blocked thread is considered “not ready” but
not dead and therefore fully qualified to run again.
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing
its run() method. It is a natural death. We can kill it by sending the stop() message to it at any
state thus causing a premature death to it. A thread can be killed as soon as it is born, or while
it is running, or when it is in blocked state.
Page 14
JAVA PROGRAMMING UNIT - III 2022-23
CREATING THREADS
Java’s multithreading system is built upon the Thread class, its methods, and its companion
interface, Runnable. To create a new thread, your program will either extend Thread or
implement the Runnable interface.
The Thread class defines several methods that help manage threads.
Method Meaning
Write a class that extends Thread class or implements Runnable interface this is
available in lang package.
Write public void run () method in that class. This is the method by default executed
by any thread.
Create an object to that class.
Create a thread and attach it to the object.
Start running the threads.
When a Java program starts up, one thread begins running immediately. This is called as main
thread, because it is the one that is executed when the program begins.
Although the main thread is created automatically when program is started, it can be
controlled through a Thread object. To do so, we must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread.
Page 15
JAVA PROGRAMMING UNIT - III 2022-23
This method returns a reference to the thread in which it is called. Once you have a reference
to the main thread, we can control it just like any other thread.
class CurrentThreadDemo {
public static void main(String args[])
{
Thread t = [Link]();
[Link]("Current thread: " + t);
// change the name of the thread
[Link]("My Thread");
[Link]("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
[Link](n);
[Link](1000);
}
}
catch (InterruptedException e) {
[Link]("Main thread interrupted");
}
}
}
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable interface.
Runnable abstracts a unit of executable code. You can construct a thread on any object that
implements Runnable. To implement Runnable, a class need only implement a single
method called run( ), which is declared like this:
After creating a class that implements Runnable, we will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown
here:
After the new thread is created, it will not start running until we call its start( ) method, which
is declared within Thread. In essence, start( ) executes a call to run( ).
Page 16
JAVA PROGRAMMING UNIT - III 2022-23
void start( )
Example:
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
[Link]("Main Thread: " + i);
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("Main thread exiting.");
}
}
Output:
Page 17
JAVA PROGRAMMING UNIT - III 2022-23
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Extending Thread
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method, which is
the entry point for the new thread. It must also call start( ) to begin execution of the new
thread.
class ExtendThread
{
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
Page 18
JAVA PROGRAMMING UNIT - III 2022-23
INTERRUPTING THREADS
Stopping a thread:
A thread can be stopped from running further by issuing the following statement.
[Link]() by this the thread enters in a dead state. From stopping state a thread can never
return to a runnable state.
Blocking a thread:
A thread can be temporarily stopped from running, this is called blocking or suspending of a
thread. Following are the ways by which thread can be blocked.
sleep() – blocked for some specific time, when the specified time gets elapsed then the thread
can return to a runnable state.
suspend()- blocked until further requests comes, whne resume() method is invoked then the
thread returns to a runnable state.
wait()- suspended for some specific conditions. When the notify() is called blocked thread
returns to the runnable state.
THREAD PRIORITY
In Java threads scheduler selects the threads using their priorities. The thread priority is a
simple integer value that can be assigned to the particular thread. These priorities can range
from 1(low priority) to 10(highest priority).
Two commonly used methods are:
set Priority()
getPriority()
The priority_val is constant value denoting the priority for the thread. It is defined as follows-
MAX_PRIORITY = 10
MIN_PRIORITY=1
NORM_PRIORITY=5
Page 19
JAVA PROGRAMMING UNIT - III 2022-23
class ThreadPriority
{
public static void main(String args[])
{
A a=new A();
B b=new B();
[Link](1);
[Link](10);
[Link]("Starting Thread #1");
[Link]();
[Link]("Starting Thread #2");
[Link]();
}
}
Page 20
JAVA PROGRAMMING UNIT - III 2022-23
OUTPUT
Thread #1
Thread #2
B: 1
B: 2
B: 3
B: 4
B: 5
End of Thread #2
A: 1
A: 2
A: 3
A: 4
A: 5
End of Thread #1
SYNCHRONIZATION
When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is
an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a
monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor. These other threads are said to be waiting for the monitor. A thread
that owns a monitor can reenter the same monitor if it so desires.
· To synchronize an entire method code we can use synchronized word before method name
e Thread synchronization is done in two ways:
· Using synchronized block we can synchronize a block of statements.
e.g.: synchronized (obj)
{
statements;
}.g.: synchronized void method ()
{
}
Synchronization is easy in Java, because all objects have their own implicit monitor
associated with them. To enter an object’s monitor, just call a method that has been modified
with the synchronized keyword. While a thread is inside a synchronized method, all other
Page 21
JAVA PROGRAMMING UNIT - III 2022-23
threads that try to call it (or any other synchronized method) on the same instance have to
wait. To exit the monitor and relinquish control of the object to the next waiting thread, the
owner of the monitor simply returns from the synchronized method.
Page 22
JAVA PROGRAMMING UNIT - III 2022-23
serialize access to call( ). i.e, restrict its access to only one thread at a time. To do this, simply
precede call( )’s definition with the keyword synchronized, as shown here:
class Callme {
synchronized void call(String msg) {
...
This prevents other threads from entering call( ) while another thread is using it.
After synchronized has been added to call( ), the output of the program is as follows:
[Hello]
[Synchronized]
[World]
While creating synchronized methods within classes that you create is an easy and effective
means of achieving synchronization, it will not work in all cases. To understand why,
consider the following. Imagine that you want to synchronize access to objects of a class that
was not designed for multithreaded access. That is, the class does not use synchronized
methods. Further, this class was not created by you, but by a third party, and you do not have
access to the source code. Thus, you can’t add synchronized to the appropriate methods
within the class. How can access to an object of this class be synchronized? Fortunately, the
solution to this problem is quite easy: You simply put calls to the methods defined by this
class inside a synchronized block.
synchronized(object) {
// statements to be synchronized
}
class Callme {
void call(String msg) {
[Link]("[" + msg);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
Page 23
JAVA PROGRAMMING UNIT - III 2022-23
msg = s;
t = new Thread(this);
[Link]();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
[Link](msg);
}
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
INTERTHREAD COMMUNICATION
Polling is usually implemented by a loop that is used to check some condition
repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU
time.
For example, consider the classic queuing problem, where one thread is producing
some data and another is consuming it. Suppose that the producer has to wait until the
consumer is finished before it generates more data.
In a polling system, the consumer would waste many CPU cycles while it waited for
the producer to produce. Once the producer was finished, it would start polling,
wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this
situation is undesirable.
To avoid polling, Java includes an elegant interprocess communication mechanism via
the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as
final methods in Object, so all classes have them. All three methods can be called
only from within a synchronized context.
■ wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
■ notify( ) wakes up the first thread that called wait( ) on the same object.
■ notifyAll( ) wakes up all the threads that called wait( ) on the same object.
Page 24
JAVA PROGRAMMING UNIT - III 2022-23
Page 25
JAVA PROGRAMMING UNIT - III 2022-23
}
Although the put( ) and get( ) methods on Q are synchronized, nothing stops the producer
from overrunning the consumer, nor will anything stop the consumer from consuming the
same queue value twice. Thus, you get the erroneous output shown here (the exact output will
vary with processor speed and task load):
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
As you can see, after the producer put 1, the consumer started and got the same 1 five times in
a row. Then, the producer resumed and produced 2 through 7 without letting the consumer
have a chance to consume them.
The proper way to write this program in Java is to use wait( ) and notify( ) to signal
in both directions, as shown here:
Page 26
JAVA PROGRAMMING UNIT - III 2022-23
valueSet = true;
[Link]("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
[Link]();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
[Link]("Press Control-C to stop.");
}
}
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies
you that some data is ready. When this happens, execution inside get( ) resumes. After the
data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more
data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed
the item from the queue. When execution resumes, the next item of data is put in the queue,
and notify( ) is called. This tells the Consumer that it should now remove it.
Here is some output from this program, which shows the clean synchronous behavior:
Put: 1
Got: 1
Put: 2
Got: 2
Page 27
JAVA PROGRAMMING UNIT - III 2022-23
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
THREAD GROUP
A ThreadGroup represents a group of threads. The main advantage of taking several threads as a
group is that by using a single method, we will be able to control all the threads in the group.
· To add a thread to this group (tg): Thread t1 = new Thread (tg, targetobj, “threadname”);
· To know the parent thread group: [Link] (); This returns a ThreadGroup object to
which the thread t belongs.
· To know the number of threads actively running in a thread group: [Link] ();
ThreadGroup(String groupName)
ThreadGroup(ThreadGroup ob, String groupName)
class ThreadGroupDemo
{
public static void main(String args[])
{
Thread t=new Thread();
ThreadGroup tg=new ThreadGroup(“Group1”);
Thread1 t1=new Thread1(tg, “ChildThread1”);
Thread2 t2=new Thread1(tg, “ChildThread2”);
[Link]();
[Link]();
[Link](“No of threads in group are..”+[Link]());
Page 28
JAVA PROGRAMMING UNIT - III 2022-23
}
}
No of threads in Group1: 2
Page 29
JAVA PROGRAMMING UNIT - III 2022-23
From childthread 1
From childthread 2
From childthread 1
From childthread 2
DAEMON THREAD
public boolean isDaemon() ? This method is used to determine the thread is daemon thread
or not.
The core difference between user threads and daemon threads is that the JVM will only shut
down a program when all user threads have terminated. Daemon threads are terminated by the
JVM when there are no longer any user threads running, including the main thread of
execution. Use daemons as the minions they are.
while(true)
{
try
{
[Link](500);
}
catch(InterruptedException x)
{
}
Page 30
JAVA PROGRAMMING UNIT - IV 2022-23
try
{
[Link](3000);
}
catch(InterruptedException x)
{
}
• “The Collections Framework provides a well-designed set of interfaces and classes for
storing and manipulating groups of data as a single unit, a collection.” -[Link]
• The standard data structure in Java can be implemented in Java using some library
classes and methods. These classes are present in [Link] package.
• Collection is a group of objects which are designed to perform certain task. These
tasks are associated with data structures.
• The collection classes are the group of classes used to implement the collection
interfaces. Various collection classes are…
• AbstractCollection AbstractList
• AbstractQueue AbstractSequentialList
Page 1
JAVA PROGRAMMING UNIT - IV 2022-23
• LinkedList ArrayList
• AbstractSet EnumSet
• HashSet PriorityQueue
• TreeSet Vector
• HashTable
Page 2
JAVA PROGRAMMING UNIT - IV 2022-23
• GENERICS
JDK 1.5 introduces several extensions to the Java programming language. One of these
is the introduction of generics.
Using generics it is possible to create a single class that automatically works with different
types of data.
class class-name<type-param-list>
{
class Gen<T>
{
T ob;
Gen(T o)
{
ob=o;
}
T getob()
{
return ob;
}
void showType()
{
[Link]([Link]().getName());
}
}
class GenDemo
{
public static void main(String args[])
{
Gen<Integer> ib = new Gen<Integer>(88);
Page 3
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]();
int v=[Link]();
[Link](v);
String str=[Link]();
[Link](str);
}
}
Output:
[Link]
88
[Link]
Generics Test
void showTypes()
{
[Link](“Type of T is” +[Link]().getName());
[Link](“Type of V is” +[Link]().getName());
}
T getob1()
return ob1;
}
V getob2()
{
return ob2;
}
}
class SimpGen
{
Page 4
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]();
int v=obj.getob1();
[Link](v);
String str=obj.getob2();
[Link](str);
}
}
Type of T is [Link]
Type of V is [Link]
88
Generics
LIST
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list
that is initialized with the elements of the collection c. The third constructor builds an array
list that has the specified initial capacity.
// Demonstrate ArrayList.
import [Link].*;
class ArrayListDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();
Page 5
JAVA PROGRAMMING UNIT - IV 2022-23
/*
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
450 J a v a ™ 2 : T h e C o m p l e t e R e f e r e n c e
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
*/
VECTOR
Constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
Page 6
JAVA PROGRAMMING UNIT - IV 2022-23
Page 7
JAVA PROGRAMMING UNIT - IV 2022-23
MAP
• Map is a kind of data structure which associates the key and values.
• There are 3 classes which implements map.
// Demonstrate a Hashtable
import [Link].*;
class HTDemo
{
public static void main(String args[])
{
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
[Link]("John Doe", new Double(3434.34));
[Link]("Tom Smith", new Double(123.22));
[Link]("Jane Baker", new Double(1378.00));
Page 8
JAVA PROGRAMMING UNIT - IV 2022-23
}
}
}
STACK
• Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack
only defines the default constructor, which creates an empty stack. Stack includes all
the methods defined by Vector, and adds several of its own.
• boolean empty( ) -Returns true if the stack is empty, and returns false if the stack
contains elements.
• Object peek( ) - Returns the element on the top of the stack, but does not remove it.
• Object pop( ) -Returns the element on the top of the stack, removing it in the process.
• Object push(Object element) - Pushes element onto the stack. element is also
• returned.
• int search(Object element) - Searches for element in the stack. If found, its offset
from the top of the stack is returned. Otherwise, –1 is returned.
import [Link].*;
import [Link].*;
import [Link].*;
class StackDemo
{
public static void main(String args[]) throws Exception
{
Stack<Integer> st=new Stack<Integer>();
int choice=0;
int position,element;
Page 9
JAVA PROGRAMMING UNIT - IV 2022-23
choice=[Link]([Link]());
switch(choice)
{
case 1:
[Link]("Enter an element");
element = [Link]([Link]());
[Link](element);
break;
case 2:
[Link]("Which element ? ");
Integer obj = [Link]();
[Link]("Poped element= "+obj);
break;
case 3:
[Link]("Which an element ? ");
element = [Link]([Link]());
position = [Link](element);
if(position==-1)
[Link]("Element not found");
else
[Link]("postion of the element is:= "+position);
break;
default:
Page 10
JAVA PROGRAMMING UNIT - IV 2022-23
return;
}
}
}
}
ENUMERATION
• The Enumeration interface defines the methods by which you can enumerate (obtain
one at a time) the elements in a collection of objects.
• The methods declared by Enumeration are summarized in the following table:
1. boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and false
when all the elements have been enumerated.
2. Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
import [Link];
import [Link];
Page 11
JAVA PROGRAMMING UNIT - IV 2022-23
}
}
}
ITERAOR
• In general, to use an iterator to cycle through the contents of a collection, follow these
steps:
• Obtain an iterator to the start of the collection by calling the collection's iterator( )
method.
• Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext(
) returns true.
• Within the loop, obtain each element by calling next( ).
Page 12
JAVA PROGRAMMING UNIT - IV 2022-23
• 8. void remove( )
9. void set(Object obj)
// Demonstrate iterators.
import [Link].*;
class IteratorDemo
{
public static void main(String args[])
{
[Link]();
Page 13
JAVA PROGRAMMING UNIT - IV 2022-23
STRING TOKENIZER
• Parsing is the division of text into a set of discrete parts, or tokens, which in a certain
sequence can convey a semantic meaning.
• The StringTokenizer class provides the first step in this parsing process, often called
the lexer (lexical analyzer) or scanner.
The StringTokenizer constructors are shown here:
• StringTokenizer(String str)
• StringTokenizer(String str, String delimiters)
• StringTokenizer(String str, String delimiters, boolean delimAsToken)
Note: if delimAsToken is true, then the delimiters are also returned as tokens when the string
is parsed. Otherwise, the delimiters are not returned. Delimiters are not returned as tokens by
the first two forms.
Page 14
JAVA PROGRAMMING UNIT - IV 2022-23
import [Link];
import [Link];
// class to accept integers and find the sum using StringTokenizer class
while ( [Link]() )
{
String s=[Link]();
dig=[Link](s);
[Link](dig+"");
sum=sum+dig;
}
Page 15
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]();
[Link]( "sum is "+sum );
}
}
RANDOM
Page 16
JAVA PROGRAMMING UNIT - IV 2022-23
// Demonstrate iterators.
import [Link].*;
class RandomDemo
{
public static void main(String args[])
{
SCANNER
• Scanner can be used to read input from the console, a file, a string, or any source that
implements the Readable interface or ReadableByteChannel. For example, you can
use Scanner to read a number from the keyboard and assign its value to a variable.
Page 17
JAVA PROGRAMMING UNIT - IV 2022-23
• abstract void add(int which, int val) - Adds val to the time or date
component specified by which. To subtract, add a negative value. Which must be one
of the fields defined by Calendar, such as [Link].
• final void clear( ) - Zeros all time components in the invoking
object.
• final void clear(int which) - Zeros the time component specified by
which in the invoking object.
• Object clone( ) - Returns a duplicate of the invoking
object.
• boolean equals(Object calendarObj) - Returns true if the invoking Calendar
object contains a date that is equal to the one specified by calendarObj. Otherwise, it
returns false.
• int get(int calendarField) - Returns the value of one component of the
invoking object. The component is indicated by calendarField. Examples of the
Page 18
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]("Date: ");
[Link](months[[Link]([Link])]);
[Link](" " + [Link]([Link]) + " ");
Page 19
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]([Link]([Link]));
[Link]("Time: ");
[Link]([Link]([Link]) + ":");
[Link]([Link]([Link]) + ":");
[Link]([Link]([Link]));
[Link]([Link], 10);
[Link]([Link], 29);
[Link]([Link], 22);
[Link]("Updated time: ");
[Link]([Link]([Link]) + ":");
[Link]([Link]([Link]) + ":");
[Link]([Link]([Link]));
}
}
Page 20
JAVA PROGRAMMING UNIT - IV 2022-23
FILES
Java programs perform I/O through streams.
A stream is an abstraction that either produces or consumes information.
A stream is linked to a physical device by the Java I/O system.
A stream can be defined as a sequence of data. The InputStream is used to read data
from a source and the OutputStream is used for writing data to a destination.
BYTE STREAM
The byte stream is used for inputting or outputting the bytes. There are two
super classes in byte stream and those are InputStream and OutputStream from
which most of the other classes are derived.
InputStream
Page 21
JAVA PROGRAMMING UNIT - IV 2022-23
OutputStream
CHARACTER STREAM
The character stream is used for inputting or outputting the characters. There are two
super classes in character stream and those are Reader and Writer from which most of
the other classes are derived.
FileReader FileWriter
PipeReader PipeWriter
FilterReader FilterWriter
BufferedReader BufferedWriter
DataReader DataWriter
LineNumberReader LineNumberWriter
PushbackReader PushbackWriter
ByteArrayReader ByteArrayWriter
SequenceReader SequenceWriter
StringBufferReader StringBufferWriter
Page 22
JAVA PROGRAMMING UNIT - IV 2022-23
import [Link].*;
public class TextFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
ByteStream Vs CharacterStream
Page 23
JAVA PROGRAMMING UNIT - IV 2022-23
Standard Streams
All the programming languages provide support for standard I/O where user's program
can take input from a keyboard and then produce output on the computer screen. If you are
aware if C or C++ programming languages, then you must be aware of three standard devices
STDIN, STDOUT and STDERR. Similar way Java provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as [Link].
Standard Output: This is used to output the data produced by the user's program
and usually a computer screen is used to standard output stream and represented as
[Link].
Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error stream and represented as
[Link].
Text Input/Output
The above two steps can be combined and rewritten in a single statement as:
BufferedReader br = new BufferedReader (new InputStreamReader ([Link]));
Page 24
JAVA PROGRAMMING UNIT - IV 2022-23
· Now, we can read the data coming from the keyboard using read () and readLine ()
methods available in BufferedReader class.
Page 25
JAVA PROGRAMMING UNIT - IV 2022-23
Binary Input/Output
The following classes are also commonly used with binary files, for both JDK 7 and
earlier versions:
Page 26
JAVA PROGRAMMING UNIT - IV 2022-23
void flush() -This method flushes this output stream and forces any buffered output
bytes to be written out.
void write(byte[] b) - This method writes [Link] bytes from the specified byte array
to this output stream.
void write(byte[] b, int off, int len) - This method writes len bytes from the specified
byte array starting at offset off to this output stream.
abstract void write(int b) -This method writes the specified byte to this output stream.
In Java, FileInputStream and FileOutputStream classes are used to read and write data
in file. In another words, they are used for file handling in java.
FileOutputStream
FileInputStream
Example: FileInputStream
import [Link].*;
class FileInput{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("[Link]");
int i=0;
while((i=[Link]())!=-1){
Page 27
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]((char)i);
}
[Link]();
}catch(Exception e){[Link](e);}
}
}
Example: FileOutputStream
import [Link].*;
class FileOutput{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("[Link]");
String s="Sachin Tendulkar is my favourite player";
byte b[]=[Link]();//converting string into byte array
[Link](b);
[Link]();
[Link]("success...");
}catch(Exception e){[Link](e);}
}
}
import [Link].*;
class FileInOut{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("[Link]");
FileOutputStream fout=new FileOutputStream("[Link]");
int i=0;
while((i=[Link]())!=-1){
[Link]((byte)i);
}
[Link]();
}
}
Page 28
JAVA PROGRAMMING UNIT - IV 2022-23
Page 29
JAVA PROGRAMMING UNIT - IV 2022-23
[Link](8);
d=[Link]();
[Link]("Second Value:"+d);
[Link](3*8);
d=[Link]();
[Link]("Fourth Value:"+d);
Page 30
JAVA PROGRAMMING UNIT - IV 2022-23
String getParent() Returns name of the file’s parent directory, or null if no parent
Page 31
JAVA PROGRAMMING UNIT - IV 2022-23
Write a java program that reads on file name from the user then displays
information about whether the file exists ,whether the file is readable,
whether the file is writable the type of file and the length of the file in
bytes.
Program:
class file1
{
public static void main(String args[]) throws Exception
{
FileInputStream f1=new
FileInputStream("[Link]"); int
size=(byte)[Link]();
[Link]
class abc
{
public static void main(String args[])
{
}
}
Output:
Page 32
JAVA PROGRAMMING UNIT - IV 2022-23
the size of the file in bytes 70
Page 33
JAVA PROGRAMMING UNIT - IV 2022-23
Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system. AWT is heavy weight i.e. its components are using the resources of underlying
operating system (OS).
The [Link] package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.
Java AWT calls the native platform calls the native platform (operating systems) subroutine for creating
API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different look and
feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the platforms
have different view for their native components and AWT directly calls the native subroutine that
creates those components.
In simple words, an AWT application will look like a windows application in Windows OS whereas it will
look like a Mac application in the MAC OS.
Page 1
JAVA PROGRAMMING UNIT - IV 2022-23
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components 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:
Window
Page 2
JAVA PROGRAMMING UNIT - IV 2022-23
Panel
Frame
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.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by default false.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.
[Link]
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
Page 4
JAVA PROGRAMMING UNIT - IV 2022-23
[Link]
import [Link].*;
// creating a Frame
Frame f = new Frame();
// creating a Label
Page 5
JAVA PROGRAMMING UNIT - IV 2022-23
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// no layout
[Link](null);
// main method
public static void main(String args[]) {
Page 6
JAVA PROGRAMMING UNIT - IV 2022-23
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
Page 7
JAVA PROGRAMMING UNIT - IV 2022-23
As displayed in the above diagram, Applet class extends Panel. Panel class
extends Container which is the subclass of Component.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
Page 8
JAVA PROGRAMMING UNIT - IV 2022-23
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life cycle methods of
applet
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
[Link] class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used
for drawing oval, rectangle, arc etc.
Page 9
JAVA PROGRAMMING UNIT - IV 2022-23
By html file.
/[Link]
import [Link];
import [Link];
public class First extends Applet{
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer [Link]. Now Html file is not required but it is for testing
purpose only.
/[Link]
import [Link];
import [Link];
public class First extends Applet{
Page 10
JAVA PROGRAMMING UNIT - IV 2022-23
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
MVC Architecture
Over the last few years, websites have shifted from simple HTML pages with a bit of CSS to
incredibly complex applications with thousands of developers working on them at the same
time. To work with these complex web applications developers use different design patterns
to lay out their projects, to make the code less complex and easier to work with. The most
popular of these patterns is MVC also known as Model View Controller.
The Model-View-Controller (MVC) framework is an architectural/design pattern that
separates an application into three main logical components Model, View, and Controller.
Each architectural component is built to handle specific development aspects of an
application. It isolates the business logic and presentation layer from each other. It was
traditionally used for desktop graphical user interfaces (GUIs). Nowadays, MVC is one of
the most frequently used industry-standard web development frameworks to create scalable
and extensible projects. It is also used for designing mobile apps.
MVC was created by Trygve Reenskaug. The main goal of this design pattern was to solve
the problem of users controlling a large and complex data set by splitting a large application
into specific sections that all have their own purpose.
Features of MVC :
It provides a clear separation of business logic, Ul logic, and input logic.
It offers full control over your HTML and URLs which makes it easy to design web application
architecture.
It is a powerful URL-mapping component using which we can build applications that have
comprehensible and searchable URLs.
It supports Test Driven Development (TDD).
Components of MVC :
The MVC framework includes the following 3 components:
Controller
Model
View
Page 11
JAVA PROGRAMMING UNIT - IV 2022-23
Controller:
The controller is the component that enables the interconnection between the views and the
model so it acts as an intermediary. The controller doesn’t have to worry about handling data
logic, it just tells the model what to do. It process all the business logic and incoming
requests, manipulate data using the Model component and interact with the View to render
the final output.
View:
The View component is used for all the UI logic of the application. It generates a user
interface for the user. Views are created by the data which is collected by the model
component but these data aren’t taken directly but through the controller. It only interacts
with the controller.
Model:
The Model component corresponds to all the data-related logic that the user works with. This
can represent either the data that is being transferred between the View and Controller
components or any other business logic-related data. It can add or retrieve data from the
database. It responds to the controller’s request because the controller can’t interact with the
database by itself. The model interacts with the database and gives the required data back to
the controller.
Let’s imagine an end-user sends a request to a server to get a list of students studying in a
class. The server would then send that request to that particular controller that handles
students. That controller would then request the model that handles students to return a list
of all students studying in a class.
Page 12
JAVA PROGRAMMING UNIT - IV 2022-23
The model would query the database for the list of all students and then return that list back
to the controller. If the response back from the model was successful, then the controller
would ask the view associated with students to return a presentation of the list of students.
This view would take the list of students from the controller and render the list into HTML that
can be used by the browser.
The controller would then take that presentation and returns it back to the user. Thus ending
the request. If earlier the model returned an error, the controller would handle that error by
asking the view that handles errors to render a presentation for that particular error. That
error presentation would then be returned to the user instead of the student list presentation.
As we can see from the above example, the model handles all of the data. The view handles
all of the presentations and the controller just tells the model and view of what to do. This is
the basic architecture and working of the MVC framework.
The MVC architectural pattern allows us to adhere to the following design principles:
1. Divide and conquer. The three components can be somewhat independently designed.
2. Increase cohesion. The components have stronger layer cohesion than if the view and
controller were together in a single UI layer.
3. Reduce coupling. The communication channels between the three components are
minimal and easy to find.
4. Increase reuse. The view and controller normally make extensive use of reusable
components for various kinds of UI controls. The UI, however will become application
specific, therefore it will not be easily reusable.
5. Design for flexibility. It is usually quite easy to change the UI by changing the view, the
controller, or both.
Advantages of MVC:
Codes are easy to maintain and they can be extended easily.
Page 13
JAVA PROGRAMMING UNIT - IV 2022-23
Disadvantages of MVC:
It is difficult to read, change, test, and reuse this model
It is not suitable for building small applications.
The inefficiency of data access in view.
The framework navigation can be complex as it introduces new layers of abstraction which
requires users to adapt to the decomposition criteria of MVC.
Increased complexity and Inefficiency of data
MVC is generally used on applications that run on a single graphical workstation. The
division of logical components enables readability and modularity as well it makes more
comfortable for the testing part.
Event Handling
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
Page 14
JAVA PROGRAMMING UNIT - IV 2022-23
Background Events
Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User Interface
(GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.
Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion, etc.
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.
Page 15
JAVA PROGRAMMING UNIT - IV 2022-23
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
Listeners: Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
AdjustmentEvent AdjustmentListener
The adjustment event is emitted by an
Page 16
JAVA PROGRAMMING UNIT - IV 2022-23
Note: As Interfaces contains abstract methods which need to implemented by the registered
class to handle events.
Different interfaces consists of different methods which are specified below.
Page 17
JAVA PROGRAMMING UNIT - IV 2022-23
ActionListener
actionPerformed()
AdjustmentListener
adjustmentValueChanged()
componentResized()
componentShown()
componentMoved()
ComponentListener
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener
itemStateChanged()
keyTyped()
keyPressed()
KeyListener
keyReleased()
mousePressed()
mouseClicked()
mouseEntered()
mouseExited()
MouseListener
mouseReleased()
mouseMoved()
MouseMotionListener
mouseDragged()
MouseWheelListener
mouseWheelMoved()
TextListener
textChanged()
windowActivated()
windowDeactivated()
WindowListener
windowOpened()
Page 18
JAVA PROGRAMMING UNIT - IV 2022-23
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
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
import [Link].*;
import [Link].*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Page 20
JAVA PROGRAMMING UNIT - IV 2022-23
import [Link].*;
import [Link].*;
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
GFG2 gfgObj;
Page 21
JAVA PROGRAMMING UNIT - IV 2022-23
Other(GFG1 gfgObj)
{
[Link] = gfgObj;
}
import [Link].*;
import [Link].*;
TextField textField;
GFG3()
{
Page 22
JAVA PROGRAMMING UNIT - IV 2022-23
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Page 23
JAVA PROGRAMMING UNIT - IV 2022-23
CONNECTING TO DATABASE
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect
Java application with Database. JDBC is used to interact with various types of Databses such as
Oracle, MS Access, My SQL and SQL Server.
JDBC can also be defined as the platform-independent interface between a relational database and
Java Programming. It allows java program to execute SQL statement and retrieve result from
database.
JDBC is similar to Open Databse Connectivity (ODBC) which is used for accessing and managing
database, but the difference is that JDBC is designed used for accessing and managing database, but
the difference is that JDBC is designed specifically for Java programs, where as ODBC is not
dependent upon any language.
In short JDBC helps the programmers to write java applications that manage
these threeprogramming activities:
1. Connect to a a data source, like a database.
2. Send queries and update statements to the data base.
3. Retrieve and process the results received from the database in answer to the query.
JDBC ARCHITECTURE
The JDBC API supports both two-tier and three-tier processing models for databaseaccess but in
general JDBC Architecture consists of two layers:
JDBC API: This provides the application-to-JDBC Manager Connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to providetransparent
connectivity to heterogeneous databases.
Page 24
JAVA PROGRAMMING UNIT - IV 2022-23
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Page 25
JAVA PROGRAMMING UNIT - IV 2022-23
JDBC API
The JDBC API is mainly divided into two package:
1. [Link] 2. [Link]
Page 26
JAVA PROGRAMMING UNIT - IV 2022-23
Page 27
JAVA PROGRAMMING UNIT - IV 2022-23
Page 28
JAVA PROGRAMMING UNIT - IV 2022-23
Page 29
JAVA PROGRAMMING UNIT - IV 2022-23
Connecting to the
Database
Page 30
JAVA PROGRAMMING UNIT - IV 2022-23
Page 31
JAVA PROGRAMMING UNIT - IV 2022-23
//Write a Java program that connects to the database using JDBC type 1 and
creates aRegistration table.
import
[Link].
*;class
Create
{
public static void main(String args[])
{
try
{
[Link]("[Link]");
Connection con;
con=[Link]("jdbc:odbc:csec”,”system”,”mlrit”)
Statement stmt=[Link]();
String sql = "CREATE TABLE REGISTRATION "
+"(id INTEGER not NULL, " +
" first VARCHAR(255), "
+" last VARCHAR(255),
" + " age INTEGER, " +
" PRIMARY KEY ( id ))";
[Link](sql);
[Link]("Created table in given
database...");[Link]();
}//tr
y
catch(Exception e)
{
[Link]();
}
}
}
Page 32
JAVA PROGRAMMING UNIT - IV 2022-23
//Write a Java program that connects to the database using JDBC type 1 and
insert rowsinto a Registration table.
import
[Link].
*;class
Insert
{
public static void main(String args[])
{
try
{
[Link]("[Link]");
Connection con;
con=[Link]("jdbc:odbc:csec”,”system”,”mlri
t”); Statement stmt=[Link]();
String sql = "INSERT INTO Registration "
+"VALUES (100, 'Hari', 'Prasad', 18)";
[Link](sql);
sql = "INSERT INTO
Registration " +
"VALUES (101, 'Vishnu', 'Sai', 25)";
[Link](sql);
sql = "INSERT INTO Registration "
+"VALUES (102, 'Sai', 'Ram', 30)";
[Link](sql);
sql = "INSERT INTO Registration "
+"VALUES(103, 'Sumit', 'Mittal',
28)";
[Link](sql);
[Link]("Inserted records into the
table...");
[Link]();
}//try
catch(Exception e)
{
[Link]();
}
}
}
//Write a Java program that connects to the database using JDBC type 1
and updateRegistration table.
import
[Link].
*;class
Update public static void main(String args[])
{ {
Page 33
JAVA PROGRAMMING UNIT - IV 2022-23
try
{
[Link]("[Link]");
Connection con;
con=[Link]("jdbc:odbc:csec”,”system”,”mlrit”
[Link]("Creating statement...");
stmt = [Link]();
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
[Link](sql);
Registration";
ResultSet rs = [Link](sql);
while([Link]()){
//Retrieve by column
name int id =
[Link]("id");
int age = [Link]("age");
String first =
[Link]("first");String
last = [Link]("last");
//Display values
[Link]("ID: " + id);
[Link](", Age: " + age);
[Link](", First: " +
first); [Link](", Last:
" + last);
}
[Link]
ose( [Link]();
); }//try
catch(Exception e)
{
[Link]();
}
}
}
Page 34
JAVA PROGRAMMING UNIT - V 2022-23
Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Swing offers much-improved functionality over AWT, new components, expanded components
features, and excellent event handling with drag-and-drop support.
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 GUI’s required in
modern commercial applications. The AWT component set has quite a few bugs and really 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- 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 looks and Functionality of
GUIs’
Swing can be used to build(Develop) The Standalone swing GUI Apps Also as Servlets And Applets
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 feels And Swing provides more powerful components
such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc
Further Swing Follows MVC.
Many programmers think that JFC and Swing are one and the same thing, but that is not so.
JFC contains Swing [A UI component package] and quite a number of other items:
Cut and paste: Clipboard support
Accessibility features: Aimed at developing GUI’s for users with disabilities
The Desktop Colors Features Has been Firstly introduced in Java 1.1
Java 2D: it has Improved colors, images, and also texts support
Features Of Swing Class
Pluggable look and feel
Uses MVC architecture
Page 1
JAVA PROGRAMMING UNIT - V 2022-23
Lightweight Components
Platform Independent
Advanced features such as JTable, JTabbedPane, JScollPane, etc.
Java is a platform-independent language and runs on any client machine, the GUI look and feel,
owned and delivered by a platform-specific O/S, simply does not affect an application’s GUI
constructed using Swing components
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component
development. For a component to qualify as lightweight, it must not depend on any non-Java [O/s
based) system classes. Swing components have their own view supported by Java’s look and feel
classes.
Pluggable Look and Feel: This feature enables the user to switch the look and feel of Swing
components without restarting an application. The Swing library supports components’ look and feels
that remain the same across all platforms wherever the program runs. The Swing library provides an
API that gives real flexibility in determining the look and feel of the GUI of an application
Highly customizable – Swing controls can be customized in a very easy way as visual appearance is
independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider,
colorpicker, and table controls.
Swing Classes Hierarchy
Swing buttons and labels can be displaying images instead of or in addition to text
The borders around most Swing components can be changed easily. For example, it is easy to put a 1
pixel border around the outside of a Swing label
Swing components do not have to be rectangular. Buttons, for example, can be round
Now The Latest Assertive technologies such as screen readers can easily get information from Swing
components. For example: A screen reader tool can easily capture the text that is displayed on a Swing
button or label
Example 1: Develop a program using label (swing) to display message “GFG WEB Site Click”;
import [Link].*;
import [Link].*;
// Main class
class GFG {
Page 3
JAVA PROGRAMMING UNIT - V 2022-23
Example 2: Write a program to create three buttons with caption OK , SUBMIT, CANCLE.
import [Link].*;
class button {
button() {
Frame f = new Frame();
Button b1 = new Button("OK");
[Link](100, 50, 50, 50);
[Link](b1);
Button b2 = new Button("SUBMIT");
Page 4
JAVA PROGRAMMING UNIT - V 2022-23
[Link](100, 101, 50, 50);
[Link](b2);
Button b3 = new Button("CANCLE");
[Link](100, 150, 80, 50);
[Link](b3);
[Link](500, 500);
[Link](null);
[Link](true);
}
Example 3 :
import [Link].*;
class Lan {
Lan() {
Frame f = new Frame();
Page 5
JAVA PROGRAMMING UNIT - V 2022-23
[Link](100, 200, 80, 50);
[Link](c3);
Checkbox c4 = new Checkbox("marathi");
[Link](100, 250, 80, 50);
[Link](c4);
[Link](500, 500);
[Link](null);
[Link](true);
}
Class Description
A Component is the Abstract base class for about the non menu user-interface
controls of SWING. Components are represents an object with a graphical
Component representation
Page 6
JAVA PROGRAMMING UNIT - V 2022-23
Class Description
JList A JList component represents the user with the scrolling list of text items
JComboBox A JComboBox component is Presents the User with a show up Menu of choices
A JTextField object is a text component that will allow for the editing of a single
JTextField line of text
A JTextArea object s a text component that allows for the editing of multiple
JTextArea lines of text
JOptionPane provides set of standard dialog boxes that prompt users for a value
JOptionPane or Something
A JFileChooser it Controls represents a dialog window from which the user can
JFileChooser select a file.
Page 7
JAVA PROGRAMMING UNIT - V 2022-23
Class Description
As the task progresses towards completion, the progress bar displays the tasks
JProgressBar percentage on its completion
A JSlider this class is lets the user graphically(GUI) select by using a value by
JSlider sliding a knob within a bounded interval.
A JSpinner this class is a single line input where the field that lets the user select
JSpinner by using a number or an object value from an ordered sequence
Servlets
Today we all are aware of the need of creating dynamic web pages i.e the ones which have the capability
to change the site contents according to the time or are able to generate the contents according to the
request received by the client. If you like coding in Java, then you will be happy to know that using Java
there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move
forward with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that run on the Java-enabled web server or application server. They are
used to handle the request obtained from the webserver, process the request, produce the response, then
send a response back to the webserver.
Properties of Servlets are as follows:
Servlets work on the server-side.
Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture is can be depicted from the image itself as provided below as follows:
Page 8
JAVA PROGRAMMING UNIT - V 2022-23
6. The web server sends the response back to the client and the client browser displays it on the screen.
Now let us do discuss eccentric point that why do we need For Server-Side extensions?
The server-side extensions are nothing but the technologies that are used to create dynamic Web pages.
Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web server. To
meet this requirement, independent Web server providers offer some proprietary solutions in the form
of APIs(Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also
one of the component APIs of Java Platform Enterprise Edition which sets standards for creating
dynamic Web applications in Java.
Before learning about something, it’s important to know the need for that something, it’s not like that this
is the only technology available for creating dynamic Web pages. The Servlet technology is similar to
other Web server extensions such as Common Gateway Interface(CGI) scripts and Hypertext
Preprocessor (PHP). However, Java Servlets are more acceptable since they solve the limitations
of CGI such as low performance and low degree scalability.
CGI:
CGI is actually an external application that is written by using any of the programming languages
like C or C++ and this is responsible for processing client requests and generating dynamic content.
In CGI application, when a client makes a request to access dynamic Web pages, the Web server
performs the following operations :
It first locates the requested web page i.e the required CGI application using URL.
It then creates a new process to service the client’s request.
Invokes the CGI application within the process and passes the request information to the application.
Collects the response from the CGI application.
Destroys the process, prepares the HTTP response, and sends it to the client.
So, in CGI server has to create and destroy the process for every request. It’s easy to understand that this
approach is applicable for handling few clients but as the number of clients increases, the workload on the
server increases and so the time is taken to process requests increases.
Page 9
JAVA PROGRAMMING UNIT - V 2022-23
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlets API’s:
Servlets are build from two packages:
[Link](Basic)
[Link](Advance)
Various classes and interfaces present in these packages are:
Page 10
JAVA PROGRAMMING UNIT - V 2022-23
Servlet – Packages
Servlets are the Java programs that run on the Java-enabled web server or application server. They are
used to handle the request obtained from the webserver, process the request, produce the response, then
send a response back to the webserver.
A package in servlets contains numerous classes and interfaces
Types of Packages
There are two types of packages in Java Servlet that are providing various functioning features to servlet
Applications. The two packages are as follows:
1. [Link] package
2. [Link] package
Type 1: [Link] package: This package of Servlet contains many servlet interfaces and classes
which are capacity of handling any types of protocol sAnd This [Link] package containing large
Page 11
JAVA PROGRAMMING UNIT - V 2022-23
interfaces and classes that are invoked by the servlet or web server container as they are not specified
with any protocol.
Type 2: [Link] package: This package of servlet contains more interfaces and classes which
are capable of handling any specified http types of protocols on the servlet. This [Link]
package containing many interfaces and classes that are used for http requests only for servlet
Servlet: This interface describes and connects all the methods that a Servlet must implement. It includes
many methods to initialize the destroy of the Servlet, and a general (service()) method which is handling
all the requests are made to it. This Servlet interface is used to creating this servlet class as this class
Page 12
JAVA PROGRAMMING UNIT - V 2022-23
having featuring to implementing these interfaces either directly or indirectly to within it on to fetching
servlets.
ServletRequest: This ServletRequest interface in which examining the methods for all objects as
encapsulating data information about its all requests i.e. made to the servers, this object of the
ServletRequest interface is used to retrieve the information data from the user.
ServletResponse: An interface examining the methods for all objects which are returning their allowed
responses from the servers and object of this current interfacing objects is used to estimate the response to
the end-user on the system.
ServletConfig: declaring this interface ServletConfig useful to gaining accessing the configuration of its
main parameters which are passing through the Servlets during the phase time of initialization and this
ServletConfig object is used for providing the information data to the servlet classes external to
explicitly.
ServletContext: The object of the ServletContext interface is very helpful to featuring the info. data to
the web applications are explaining to it for servlets
GenericServlet: This is a generic classes examination to implement the Servlet. if you want to write the
Servlet’s protocols other than the HTTP, then the easy way of doing this is to extend GenericServlet
rather than by directly implementing the Servlet interfaces
ServletException: it is an exception that can be thrown when the Servlet invoking a problem of some
examples
ServletInputStream: This class ServletInputStream is used to reading the binary data from end user
request
ServletContextEvent: in this any changes are made in the servlet context of its web application, this
class notifies it to the end-user.
ServletOutputStream: This class ServletOutputStream is useful to send the transferring binary data to
the end-user side of the system.
Interfaces: The [Link] packages have provides these feature classes that are unique to
handling these HTTP requests allowing from it. It provides the HttpServlet classes that is usable as it
accesses the selectively interfaces from [Link] class.
Interfaces in [Link]
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
Page 13
JAVA PROGRAMMING UNIT - V 2022-23
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
9. HttpServletRequest – as the extension to ServletRequest interface is using for features specified to
HTTP
10. HttpServletResponse – as this extension to ServletResponse interface is using for functions are similar
to HTTP
11. HttpSession – this interface featuring the accessing to the sessions of tracking for API
12. HttpSessionAttributeListener – This interface notifies if any changes/edits are prefetched in this
HttpSession attribute
13. HttpSessionListener – This HttpSessionListener interface notified any changes/edits are prefetched in
this interface HttpSession lifecycle span process
HttpServlet: in this HttpServlet purely abstracted class having features as functionality to extending and
applying on the HTTP requests. They have like Service() method that is declared in the Servlet interfaces
will now call its methods similar to doGet() and the doPost(), which are enabled to providing behavior to
the Calling Servlet
Cookie: This Class provides the feature Servlet an interface for the storage of small portions of data
information on the end-user computer or system.
HttpSessionBindingEvent: This class notified when any attribute is bounded, unbounded or replaced in
any Current session
Page 14