[Go to site: main page, start]

0% found this document useful (0 votes)
13 views185 pages

Java OOP Concepts and Benefits Explained

The document provides an overview of Object-Oriented Programming (OOP) concepts, Java programming fundamentals, and the history of Java. It covers key principles such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism, along with the benefits of using OOP compared to procedure-oriented programming. Additionally, it discusses Java's features, the Java Virtual Machine, and its buzzwords that highlight its simplicity, security, portability, and robustness.

Uploaded by

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

Java OOP Concepts and Benefits Explained

The document provides an overview of Object-Oriented Programming (OOP) concepts, Java programming fundamentals, and the history of Java. It covers key principles such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism, along with the benefits of using OOP compared to procedure-oriented programming. Additionally, it discusses Java's features, the Java Virtual Machine, and its buzzwords that highlight its simplicity, security, portability, and robustness.

Uploaded by

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

JAVA PROGRAMMING UNIT-I 2022-23

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)

THE BENEFITS OF INHERITANCE


❖ Software Reusability
When behavior is inherited from another class, the code that provides that behavior does not
have to be rewritten. With objet oriented techniques, the functions can be written once and
reused.

❖ 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.

DIFFERENCES BETWEEN OBJECT ORIENTED & PROCEDURE ORIENTED


PROGRAMMING

Object Oriented Programming:

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

6. OOP supports polymorphism, encapsulation, and inheritance concepts.


7. For solving the problems, the problem is divided into a number of modules. These modules
are a logical collection of classes and objects.
8. OOP supports data abstraction.

Procedure Oriented Programming:

1. A procedure oriented program consists of instructions in groups, known as functions. High


level language like FORTRAN, PASCAL, and C are commonly known as procedure oriented
languages.

Global Data

2. POP employs top-down 1 ramming


Functionprog 2 w here a problem
approach
Function Functionis3 vi ewed as a sequence
of tasks to be per formed.
Data Data Data
3. POP has 2 ma jor drawbacks. (1) da ta move freely around the program and are therefore
vulnerable to changes caused by any function in the program, (2) it does not model
3. Data in procedure oriented language is open and can be accessed by any function.
4. Function overloading and operator overloading are not possible.
5. Local variables can be declared only at the beginning of the block.
6. Program controls are through jumps and calls to subroutines.
[Link], encapsulation and inheritance are not possible.
For solving the problems, the problem is divided into a number of modules. Each module is a
subprogram.
8. Data abstraction property is not supported by procedure oriented language.

Difference between Procedure Oriented Programming and OOP:


JAVA PROGRAMMING UNIT-I 2022-23

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.

THE JAVA VIRTUAL MACHINE

• 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.‖

Interpreted and High Performance

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

• Comments in a program are called inline documentation


• They should be included to explain the purpose of the program and describe
processing steps
• They do not affect how a program works

Java comments can take three forms:

// this comment runs to the end of the line

/* this comment runs to the terminating symbol, even across line breaks */

/** this is a javadoc comment */

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.

Integer Data Types: These data types store integer numbers


JAVA PROGRAMMING UNIT-I 2022-23

// Compute distance light travels using long variables.


class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.

Float Data Types: These data types handle floating point numbers

// Compute the area of a circle.


class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
[Link]("Area of circle is " + a);
}
}
Character Data Type: This data type represents a single character. char data type in java
uses two bytes of memory also called Unicode system. Unicode is a specification to include
alphabets of all international languages into the character set of java.
JAVA PROGRAMMING UNIT-I 2022-23

Here is a program that demonstrates char variables:


// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y

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:

// char variables behave like integers.


class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1);
ch1++; // increment ch1
[Link]("ch1 is now " + ch1);
}
}
The output generated by this program is shown here:
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1
containing Y, the next character in the ASCII (and Unicode) sequence.

Boolean Data Type: can handle truth values either true or false
e.g.:- boolean response = true;

Here is a program that demonstrates the boolean type:

// Demonstrate boolean values.


class BoolTest {
public static void main(String args[]) {
JAVA PROGRAMMING UNIT-I 2022-23

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:

type identifier [ = value][, identifier [= value] ...] ;

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;

Eg: int n=10, m=20;

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);
}
}

THE SCOPE AND LIFETIME OF VARIABLES

✓ Java allows variables to be declared within any block.


✓ A block is begun with an opening curly brace and ended by a closing curly brace. A
block defines a scope. Thus, each time you start a new block, you are creating a new
scope.
✓ A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
✓ Most other computer languages define two general categories of scopes: global and
local.
✓ In Java, the two major scopes are those defined by a class and those defined by a
method.
✓ The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method‘s scope.
✓ As a general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is defined outside that scope. Thus, when you declare a variable within a
scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
✓ Indeed, the scope rules provide the foundation for encapsulation.
✓ Scopes can be nested. The outer scope encloses the inner scope This means that
objects declared in the outer scope will be visible to code within the inner scope.
However, the reverse is not true. Objects declared within the inner scope will not be
visible outside it.

// Demonstrate block scope.


class Scope {
public static void main(String args[]) {
int x;
x = 10;
if(x == 10) {
int y = 20;
// x and y both known here.
[Link]("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
}
}

✓ 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.

// Demonstrate lifetime of a variable.


class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
[Link]("y is: " + y); // this always prints -1
y = 100;
[Link]("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

TYPE CONVERSION AND CASTING

✓ Type casting is to assign a value of one type to a variable of another type.


✓ If the two types are compatible, then Java will perform the conversion automatically.
For example, it is always possible to assign an int value to a long variable.
✓ For instance, there is no conversion defined from double to byte. To do so, you must
use a cast, which performs an explicit conversion between incompatible types.

Java’s Automatic Conversions

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:

■ The two types are compatible.


■ The destination type is larger than the source type.

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

Casting Incompatible Types

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);
}
}

Conversion of int to byte.


i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

OPERATORS

An operator is a symbol that performs an operation. An operator acts on variables called


operands.

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.

Relational operators: These operators are used for comparison purpose.

Logical operators: Logical operators are used to construct compound conditions. A


compound condition is a combination of several simple conditions.
JAVA PROGRAMMING UNIT-I 2022-23

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.

Ternary Operator or Conditional Operator (? :):

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.

e.g.: max = (a>b) ? a: b;

Program 1: Write a program to perform arithmetic operations

//Addition of two numbers


class AddTwoNumbers
{ public static void mian(String args[])
{ int i=10, j=20;
[Link]("Addition of two numbers is : " + (i+j));
[Link]("Subtraction of two numbers is : " + (i-j));
[Link]("Multiplication of two numbers is : " + (i*j));
[Link]("Quotient after division is : " + (i/j) );
JAVA PROGRAMMING UNIT-I 2022-23

[Link]("Remainder after division is : " +(i%j) );


}
}

Program 2: Write a program to perform Bitwise operations


//Bitwise Operations
class Bits
{ public static void main(String args[])
{ byte x,y;
x=10;
y=11;
[Link] ("~x="+(~x));
[Link] ("x & y="+(x&y));
[Link] ("x | y="+(x|y));
[Link] ("x ^ y="+(x^y));
[Link] ("x<<2="+(x<<2));
[Link] ("x>>2="+(x>>2));
[Link] ("x>>>2="+(x>>>2));
}
}

OPERATOR HIERARCHY

➢ An expression is a sequence of operands and operators that reduce to a single


value.
➢ Expressions can be simple or complex.
JAVA PROGRAMMING UNIT-I 2022-23

➢ An operator is a syntactical token that requires an action be taken.


➢ An operand is an object on which an operation is performed; it receives an
operator‘s action .
➢ A simple expression contains only one operator.
Ex: 2+5
➢ A complex expression contains more than one operator.
Ex: 2+5*7
➢ An expression always reduces to a single value.
➢ We can divide simple expressions into six categories based on number of
operands, relative position of the operand and operator and the precedence of
operator.

ENUMERATED TYPES
Enumeration:
• An enumeration is created using the enum keyword. For example, here is a
simple

enumeration that lists various apple varieties:

• The identifiers Jonathan, GoldenDel, and so on, are called enumeration


constants. Each is their type is the type of the enumeration in which they are
declared, which is Apple in this case.

• Once defined an enumeration, you can create a variable of that type.


• However, even though enumerations define a class type, you do not instantiate an
enum using new.
• declare and use an enumeration variable in much the same way as you do one
of the primitive types.
• For example, this declares ap as a variable of enumeration type Apple:
Apple ap;
ap is of type Apple, the only values that it can be assigned (or can contain) are those
defined by the enumeration.
• For example, this assigns ap the value RedDel:
ap = [Link];
RedDel is preceded by Apple.
JAVA PROGRAMMING UNIT-I 2022-23

// An enumeration of apple varieties.

enum Apple
{

Jonathan, GoldenDel, RedDel, Winesap, Cortland


}

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

The output from the program is shown here:


Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow.

CONTROL STATEMENTS

Statements are divided into three groups:

STATEMENTS

SELECTION ITERATION/ JUMP


LOOP

Java’s Selection 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.

The else clause is optional.


The if works like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed. In no case will both statements be executed. For example,
consider the following:

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)

The if-else-if Ladder


A common programming construct that is based upon a sequence of nested ifs is the if-else-if
ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

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.

Here is the general form of a switch statement:

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

Java‘s iteration statements are

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.

Syntax: while (condition)


{
statements;
}
JAVA PROGRAMMING UNIT-I 2022-23

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
while (i <= 20)
{ [Link] (i + ―\t‖);
i++;
}
}
}

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);

Program: Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
do
{ [Link] (i + ―\t‖);
i++;
} while (i <= 20);
}
}

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.

Syntax: for (expression1; expression2; expression3)


{ statements;
}
Here, expression1 is used to initialize the variables, expression2 is used for condition
checking and expression3 is used for increment or decrement variable value.

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i;
for (i=1; i<=20; i++)
JAVA PROGRAMMING UNIT-I 2022-23

[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.

Program : Write a program to use break as a civilized form of goto.

//using break as a civilized form of goto


class BreakDemo
{ public static void main (String args[])
{ boolean t = true;
first:
{
second:
{
third:
{
[Link] (―Before the break‖);
if (t) break second; // break out of second block
[Link] (―This won‘t execute‖);
}
[Link] (―This won‘t execute‖);
}
[Link] (―This is after second 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;

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main (String args[])
{ int i=1;
while (true)
JAVA PROGRAMMING UNIT-I 2022-23

{ [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

Program : Write a program to demonstrate return statement.


//Demonstrate return
class ReturnDemo
{ public static void main(String args[])
{ boolean t = true;
[Link] (―Before the return‖);
if (t)
return;
[Link] (―This won‘t execute‖);
}}

SIMPLE JAVA STAND ALONE PROGRAM

• As all other programming languages, Java also has a structure.


• The first line of the C/C++ program contains include statement. For example,
<stdio.h> is the header file that contains functions, like printf (), scanf () etc. So if we
want to use any of these functions, we should include this header file in C/ C++
program.
• Similarly in Java first we need to import the required packages. By default [Link].*
is imported. Java has several such packages in its library. A package is a kind of
directory that contains a group of related classes and interfaces. A class or interface
contains methods.
• Since Java is purely an Object Oriented Programming language, we cannot write a
Java program without having at least one class or object. So, it is mandatory to write a
class in Java program. We should use class keyword for this purpose and then write
class name.
JAVA PROGRAMMING UNIT-I 2022-23

• 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

The general form of a onedimensional array declaration is

type var-name[ ];

Here, type declares the base type of the array.

eg: int month_days[];


you must allocate one using new and assign it to month_days. new is a special operator
that allocates memory.

The general form of new as it applies to one-dimensional arrays appears as follows:

array-var = new type[size];

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.");
}
}

the following code creates an initialized array of integers:


JAVA PROGRAMMING UNIT-I 2022-23

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

In Java, multidimensional arrays are actually arrays of arrays.


To declare a multidimensional array variable, specify each additional index using another set
of square brackets.

int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD.

// Demonstrate a two-dimensional array.


class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19

// Initialize a two-dimensional array.


class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
JAVA PROGRAMMING UNIT-I 2022-23

{ 0*1, 1*1, 2*1, 3*1 },


{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
[Link](m[i][j] + " ");
[Link]();
}
}
}
When you run this program, you will get the following output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

Alternative Array Declaration Syntax

There is a second form that may be used to declare an array:

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:

int al[] = new int[3];


int[] a2 = new int[3];

The following declarations are also equivalent:

char twod1[][] = new char[3][4];


char[][] twod2 = new char[3][4];

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

CONSOLE INPUT AND OUTPUT

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.

To accept data from the keyboard:


· Connect the keyboard to an input stream object. Here, we can use InputStreamReader that
can read data from the keyboard.

InputSteamReader obj = new InputStreamReader ([Link]);

· Connect InputStreamReader to BufferReader, which is another input type of stream. We are


using BufferedReader as it has got methods to read data properly, coming from the stream.

BufferedReader br = new BufferedReader (obj);

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.

Accepting a Single Character from the Keyboard:

· Create a BufferedReader class object (br).


· Then read a single character from the keyboard using read() method as:
char ch = (char) [Link]();
JAVA PROGRAMMING UNIT-I 2022-23

· 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.

Accepting a String from Keyboard:

· Create a BufferedReader class object (br).


· Then read a string from the keyboard using readLine() method as:
String str = [Link] ();

· 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.

Accepting an Integer value from Keyboard:

· 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]().

Accepting a Float value from Keyboard:

· 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.

Accepting a Double value from Keyboard:

· 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.

Accepting Other Types of Values:

· To accept a byte value: byte n = [Link] ([Link] () );


· To accept a short value: short n = [Link] ([Link] () );
· To accept a long value: long n = [Link] ([Link] () );
· To accept a boolean value: boolean x = [Link] ([Link] () );
If read () / readLine () method could not accept values due to some reason (like insufficient
memory or illegal character), then it gives rise to a runtime error which is called by the name
IOException, where IO stands for Input/Output and Exception represents runtime [Link]
we do not know how to handle this exception, in Java we can use throws command to throw
the exception without handling it by writing:

throws IOException at the side of the method where read ()/ readLine () is used.

Program 1: Write a program to accept and display student details.


// Accepting and displaying student details.
import [Link].*;
class StudentDemo
{ public static void main(String args[]) throws IOException
{ // Create BufferedReader object to accept data
BufferedReader br =new BufferedReader (new InputStreamReader ([Link]));
//Accept student details
[Link] ("Enter roll number: ");
int rno = [Link] ([Link]());
[Link] (―Enter Gender (M/F): ―);
char gender = (char)[Link]();
[Link] (2);
[Link] ("Enter Student name: ");
String name = [Link] ()
[Link] ("Roll No.: " + rno);
[Link] ("Gender: " + gender);
[Link] ("Name: " + name);
}
}

Java Scanner class

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.

There is a list of commonly used Scanner class methods:

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.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.

import [Link];

class ScannerTest{

public static void main(String args[]){

Scanner sc=new Scanner([Link]);

[Link]("Enter your rollno");

int rollno=[Link]();

[Link]("Enter your name");

String name=[Link]();

[Link]("Enter your fee");

double fee=[Link]();

[Link]("Rollno:"+rollno+" name:"+name+" fee:"+fee);

[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

The General Form of a Class

A class is declared by use of the class keyword. The general form of a class definition is
shown here:

Access specifier class classname {


type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method

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

Obtaining objects of a class is a two-step process.

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.

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object

The above two statements can be written as a single statement as

Box mybox = new Box();

Introducing Methods

This is the general form of a method:

modifier type name(parameter-list)


{
// body of method
}

More generally, method declarations have six components, in order:

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

4. The parameter list in parenthesis—a comma-delimited list of input parameters,


preceded by their data types, enclosed by parentheses, (). If there are no parameters,
you must use empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.

CONSTRUCTORS

✓ A constructor initializes an object immediately upon creation.


✓ It has the same name as the class in which it resides and is syntactically similar to a
method.
✓ Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
✓ Constructors have no return type, not even void. This is because the implicit return
type of a class‘ constructor is the class type itself.

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

The constructors that take parameters are called parameterized constructors.

class Box {
double width;
double height;
double depth;

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}

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);
}
}

The output from this program is shown here:


Volume is 3000.0
Volume is 162.0

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.

Java‘s access specifiers are:


JAVA PROGRAMMING UNIT-I 2022-23

• 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]());
}
}

The this Keyword

✓ 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.

Box(double w, double h, double d) {


[Link] = w;
[Link] = h;
[Link] = d;
}

Instance Variable Hiding:

✓ 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.

// Use this to resolve name-space collisions.


Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth; }

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.

The finalize( ) Method

✓ 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.

The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}

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.

Here is a simple example that illustrates method overloading:

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);
}
}

This program generates the following output:


No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of [Link](123.25): 15190.5625

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

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}

OUTPUT:
111 Karan 0
222 Aryan 25

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Constructor is used to initialize the state of an Method is used to expose behaviour


object. of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by compiler


constructor if you don't have any constructor. in any case.

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.

// Simple types are passed by value.


class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
[Link]("a and b before call: " +
a + " " + b);
[Link](a, b);
[Link]("a and b after call: " +
a + " " + b);
}
}

The output from this program is shown here:


a and b before call: 15 20
a and b after call: 15 20

// Objects are passed by reference.


class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
[Link]("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
[Link](ob);
JAVA PROGRAMMING UNIT-I 2022-23

[Link]("ob.a and ob.b after call: " +


ob.a + " " + ob.b);
}
}

This program generates the following output:


ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10

RECURSION

✓ Java supports recursion.


✓ Recursion is the process of defining something in terms of itself. As it relates to Java
programming, recursion is the attribute that allows a method to call itself.
✓ A method that calls itself is said to be recursive.
✓ The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. For
example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use
of a recursive method:

// A simple example of recursion.


class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}

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));
}
}

The output from this program is shown here:


Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

✓ 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.

EXPLORING STRING CLASS

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 Constructors

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:

char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
[Link]([Link]());

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

For example, the following fragment concatenates three strings:

String age = "9";


String s = "He is " + age + " years old.";
[Link](s);

This displays the string ―He is 9 years old.‖

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:

char charAt(int where)

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:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

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.

equals( ) and equalsIgnoreCase( )

To compare two strings for equality, use equals( ). It has this general form:

boolean equals(Object str)

startsWith( ) and endsWith( )

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:

boolean startsWith(String str)


boolean endsWith(String str)

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:

Hello equals Hello -> true


Hello == Hello -> false

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:

int compareTo(String str)

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( )

You can concatenate two strings using concat( ), shown here:


String concat(String str)

replace( )

The replace( ) method replaces all occurrences of one character in the invoking string
with another character. It has the following general form:

String replace(char original, char replacement)


Here, original specifies the character to be replaced by the character specified by
replacement. The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string ―Hewwo‖ into s.

trim( )

The trim( ) method returns a copy of the invoking string from which any leading and
JAVA PROGRAMMING UNIT-I 2022-23

trailing whitespace has been removed. It has this general form:


String trim( )
Here is an example:
String s = " Hello World ".trim();

Changing the Case of Characters Within a String

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)

length( ) and capacity( )

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:

void ensureCapacity(int capacity)


JAVA PROGRAMMING UNIT-I 2022-23

Here, capacity specifies the size of the buffer.

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.

charAt( ) and setCharAt( )

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:

char charAt(int where)


void setCharAt(int where, char ch)

getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has
this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

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:

StringBuffer append(String str)


StringBuffer append(int num)
StringBuffer append(Object obj)

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:

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
JAVA PROGRAMMING UNIT-I 2022-23

reverse( )

You can reverse the characters within a StringBuffer object using reverse( ), shown here:

StringBuffer reverse( )

delete( ) and deleteCharAt( )

Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and
deleteCharAt( ). These methods are shown here:

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

replace( )

Another method added to StringBuffer by Java 2 is replace( ). It replaces one set of


characters with another set inside a StringBuffer object. Its signature is shown here:

StringBuffer replace(int startIndex, int endIndex, String str)

substring( )

Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It
has the following two forms:

String substring(int startIndex)


String substring(int startIndex, int endIndex)

Java static keyword:


The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
JAVA PROGRAMMING UNIT-I 2022-23

1) Java static variable

If you declare any variable as static, it is known as a static variable.

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.

Example of static variable


//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
JAVA PROGRAMMING UNIT-I 2022-23

void display (){[Link](rollno+" "+name+" "+college);}


}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//[Link]="BBDIT";
[Link]();
[Link]();
}
}

2) Java static method

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.

Example of static method

/Java Program to demonstrate the use of a static method.


class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
JAVA PROGRAMMING UNIT-I 2022-23

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

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}

2) Java final method


class Bike{
final void run(){[Link]("running");}
}

class Honda extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
[Link]();
}
JAVA PROGRAMMING UNIT-I 2022-23

}
3) Java final class
final class Bike{}

class Honda1 extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
[Link]();
}
}
JAVA PROGRAMMING UNIT - II 2022-23

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

type final-varname2 = value;


// ...
return-type method-nameN(parameter-list);
type final-varnameN = value; }

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

access class classname [extends superclass]


[implements interface [,interface...]] {
// class-body
}

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.

class Client implements Callback {


public void callback(int p) {
[Link]("callback called with " + p);
}
}

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.

class Client implements Callback {


public void callback(int p) {
[Link]("callback called with " + p);
}

void nonIfaceMeth() {
[Link]("Classes that implement interfaces " +
"may also define other members, too.");
}
}

Accessing Implementations Through Interface References

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:

// One interface can extend another.


interface A {
void meth1();
void meth2();
}

interface B extends A {
void meth3();
}

class MyClass implements B {


public void meth1() {
[Link]("Implement meth1().");
}
public void meth2() {
[Link]("Implement meth2().");
}
public void meth3() {
[Link]("Implement 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);
}
}

MULTIPLE INHERITANCE USING INTERFACES


Java does not support multiple inheritance. But multiple inheritance can be achieved by using
interfaces.

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 MyClass implements Father, Mother


{
void show()
{
[Link]("Total property is :" +([Link]+[Link]));
[Link] ("Average height is :" + ([Link] + [Link])/2 );
}
}

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.

Uses of Inner Classes

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.

Ex: non static inner class

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

[Link] i= [Link] Inner();


[Link]();
}
}

Ex: static inner class

class Outer
{
static int x=10;
static class Inner
{
void show()
{
[Link]("Hello "+x);
}
}
}

class Demo1
{
public static void main(String args[])
{

[Link] i= new [Link]();


[Link]();
}
}

Anonymous Inner Class

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

//dog contains an object of anonymous subclass of Dog.


[Link]();
}
}

class Dog
{
public void someDog()
{
[Link]("Classic Dog");
}
}

Ex2:

public class MainClass {


public static void main(String[] args) {
Ball b = new Ball() {
public void hit() {
[Link]("You hit it!");
}
};
[Link]();
}

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.

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package.

For example, package MyPackage;

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.

The general form of a multileveled package statement is shown here:

package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system.

For example, package [Link];

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.

Setting up Java Environment:

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:

set PATH=C:\Program Files\Java\jdk1.5.0_05\bin;

Setting environment variables as system variables:

If we set the variables as system variables they will hold continuously.


o Right-click on My Computer
o Choose Properties
o Select the Advanced tab
o Click the Environment Variables button at the bottom
o In system variables tab, select path (system variable) and click on edit button
o A window with variable name path and its value will be displayed.
o Don’t disturb the default path value that is appearing and just append (add) to that path at
the end:
;C:\ProgramFiles\Java\ jdk1.5.0_05\bin;
o Finally press OK button.

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

public static void main(String args[]) {


Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}

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

Java addresses four categories of visibility for class members:


■ Subclasses in the same package
■ Non-subclasses in the same package
■ Subclasses in different packages
■ Classes that are neither in the same package nor subclasses

The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.

Anything declared public can be accessed from anywhere.


Anything declared private cannot be seen outside of its class.
When a member does not have an explicit access specification, it is visible to subclasses as
well as to other classes in the same package. This is the default access.
If you want to allow an element to be seen outside your current package, but only to classes
that subclass your class directly, then declare that element protected.

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

Private No modifier Protected Public

Same class Yes Yes Yes Yes

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.

This is the general form of the import statement:

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[]) {

Factorial f=new Factorial();


[Link]([Link](5));
}
}

Page 30
JAVA PROGRAMMING UNIT - III 2022-23

CONCEPTS OF EXCEPTION HANDLING

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.

Exception: An abnormal event in a program is called Exception.

 Exception may occur at compile time or at runtime.


 Exceptions which occur at compile time are called Checked exceptions.
e.g.: ClassNotFoundException, NoSuchMethodException, NoSuchFieldException etc.
 Exceptions which occur at run time are called Unchecked exceptions.
eg:ArrayIndexOutOfBoundsException, ArithmeticException, etc..

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."

BENEFITS OF EXCEPTION HANDLING

Exception handling provides the following advantages over ``traditional'' error Management
techniques:

Separating Error Handling Code from ``regular'' one


It separates the working/functional code from the error-handling code by way of try-catch
clauses.

Propagating Errors Up the Call Stack


It allows a clean path for error propagation. If the called method encounters a situation it can't
manage, it can throw an exception and let the calling method deal with it.

Error Types and Error Differentiation


By enlisting the compiler to ensure that "exceptional" situations are anticipated and accounted
for, it enforces powerful coding.

Page 3
JAVA PROGRAMMING UNIT - III 2022-23

EXCEPTION HIERARCHY

Runtime Exception IOException

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:

 unchecked exceptions can be thrown "at any time";


 methods don't explicitly have to declare that they can throw an unchecked
exception; 
 callers don't have to handle them explicitly.

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

catch ( ExceptionClass obj)


{ statements;
}

· 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;
}

Performing above tasks is called Exception Handling.

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
}

Using try and catch


To guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block.
Each try block, must include a matching catch clause

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

This program generates the following output:


Division by zero.

Multiple catch Clauses

 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.");
}
}

Nested try Statements

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);

try { // nested try block


if(a==1) a = a/(a-a); // division by zero

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:

type method-name(parameter-list) throws exception-list


{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.

throws clause is useful to escape from handling an exception. throws clause


is useful tothrow out any exception without handling it.
import [Link].*;
class Sample
{
void accept( )throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader([Link]));
[Link] ("enter ur name: ");
String name=[Link] ( );
[Link] ("Hai "+name);
}
}
class ExceptionNotHandle
{
public static void main (String args[])
throws IOException
{
Sample s=new Sample ( );
[Link] ( );
}
}

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");
}
}

static void procC()


{
try
{
[Link]("inside procC");
}
finally
{
[Link]("procC's finally");
}
}
public static void main(String args[])
{
try {
procA();
}
catch (Exception e) {
[Link]("Exception caught");
}
procB();
procC();
}

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

Java’s Built-in Exceptions

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.

Creating Your Own Exception Subclasses

These are the exceptions created by the programmer.

Creating user defined exceptions:

o Write user exception class extending Exception class.


e.g.: class MyException extends Exception
o Write a default constructor in the user exception class
e.g.: MyException ( ) { }
o Write a parameterized constructor with String as a parameter, from there call the
parameterized constructor of Exception class.
e.g.: MyException (String str)

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;

class MyException extends Exception


{
int accno[] = {1001,1002,1003,1004,1005};
String name[] = {"Hari","Siva","Bhanu","Rama","Chandu"};
double bal[] = {2500,3500,1500,1000,6000};
MyException()
{
}
MyException(String str)
{
super(str);
}
public static void main(String args[])
{
try
{
MyException me = new MyException("");
[Link]("AccNo \t Name \t Balance ");
for(int i=0;i<5;i++)
{
[Link]([Link][i]+ "\t" + [Link][i] + "\t" +
[Link][i] );
if( [Link][i] < 2000 )
{
MyException me1 = new MyException
("Insufficient Balance");
throw me1;
}
}
}
catch(MyException e)
{
[Link]();
}
}
}

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

1 Light weight process Heavy weight process

2 Do not require separate address space Each process requires separate address
for its execution. space for its execution.

[Link] Multithreading Multiprocessing

1 Thread is a fundamental unit of Process/Program is a fundamental unit


multithreading. of multiprocessing.

2 Multiple parts of single program gets Multiple programs get executed in


executed in multithreading multiprocessing environment.
environment.

3 During multithreading the processor During multiprocessing the processor


switches between multiple threads in switches between multiple
the program. programs/processes.

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

5 Highly efficient Less efficient.

6 Develops efficient application Develops efficient OS programs.


programs

Page 2
JAVA PROGRAMMING UNIT - III 2022-23

THREAD LIFE CYCLE:

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.

 The thread that was just created is in the born state.


 The thread remains in this state until the threads start method is called. This causes the
thread to enter the ready state.
 The highest priority ready thread enters the running state when system assigns a
processor to the thread i.e., the thread begins executing.
 When a running thread calls wait the thread enters into a waiting state for the
particular object on which wait was called. Every thread in the waiting state for a
given object becomes ready on a call to notify all by another thread associated with
that object.
 When a sleep method is called in a running thread that thread enters into the
suspended (sleep) state. A sleeping thread becomes ready after the designated sleep
time expires. A sleeping thread cannot use a processor even if one is available.
 A thread enters the dead state when its run () method completes (or) terminates for any
reason. A dead thread is eventually be disposed of by the system.
 One common way for a running thread to enter the blocked state is when the thread
issues an input or output request. In this case a blocked thread becomes ready when
the input or output waits for completes. A blocked thread can’t use a processor even if
one is available.

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:

- Scheduled it for running using start() method.


- Kill it using stop() method.
If scheduled it moves to the ready state. If we attempt to use any other method at this stage, an
exception will be thrown.

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 thread Ready threads

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()

Running Ready Suspended


thread

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.

■ You can implement the Runnable interface.


■ You can extend the Thread class, itself.

The Thread class defines several methods that help manage threads.

Method Meaning

getName Obtain a thread’s name.


getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
start Start a thread by calling its run method.
Creating a Thread:

 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.

The Main Thread

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.

The main thread is important for two reasons:


■ It is the thread from which other “child” threads will be spawned.
■ Often it must be the last thread to finish execution because it performs various shutdown
actions.

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.

Its general form is shown here:

Page 15
JAVA PROGRAMMING UNIT - III 2022-23

static Thread currentThread( )

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");
}
}
}

Current thread: Thread[main,5,main]


After name change: Thread[My Thread,5,main]
5
4
3
2
1

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:

public void run( )

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:

Thread(Runnable threadOb, String threadName)

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 NewThread implements Runnable {


Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
[Link]("Child thread: " + t);
[Link](); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link]("Child Thread: " + i);
[Link](500);
}
}
catch (InterruptedException e) {
[Link]("Child interrupted.");
}
[Link]("Exiting child thread.");
}
}

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:

Child thread: Thread[Demo Thread,5,main]


Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4

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 NewThread extends Thread


{
NewThread()
{
// Create a new, second thread
super("Demo Thread");
[Link]("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run()
{
try {
for(int i = 5; i > 0; i--) {
[Link]("Child Thread: " + i);
[Link](500);
}
}
catch (InterruptedException e) {
[Link]("Child interrupted.");
}
[Link]("Exiting child 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

[Link]("Main Thread: " + i);


[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("Main thread exiting.");
}}

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 A extends Thread


{
public void run()
{
[Link]("Thread #1");
for(int i=1;i<=5;i++)
{
[Link]("\tA:"+i);
}
[Link]("End of Thread #1");
}
}

class B extends Thread


{
public void run()
{
[Link]("Thread #2");
for(int k=1;k<=5;k++)
{
[Link]("\tB:"+k);
}
[Link]("End of Thread #2");
}
}

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 ()
{
}

Using Synchronized Methods

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.

// This program is not 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;
msg = s;
t = new Thread(this);
[Link]();
}
public void run() {
[Link](msg);
}
}
class Synch {
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");
}
}
}
Here is the output produced by this program:
Hello[Synchronized[World]
]
]

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]

The synchronized Statement

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.

This is the general form of the synchronized statement:

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.

These methods are declared within Object, as shown here:

Page 24
JAVA PROGRAMMING UNIT - III 2022-23

final void wait( ) throws InterruptedException


final void notify( )
final void notifyAll( )

// An incorrect implementation of a producer and consumer.


class Q {
int n;
synchronized int get() {
[Link]("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
[Link]("Put: " + n);
}
}
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 PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
[Link]("Press Control-C to stop.");
}

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:

// A correct implementation of a producer and consumer.


class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link]("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught");
}
this.n = n;

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.

· Creating a thread group: ThreadGroup tg = new ThreadGroup (“groupname”);

· To add a thread to this group (tg): Thread t1 = new Thread (tg, targetobj, “threadname”);

· To add another thread group to this group (tg):


ThreadGroup tg1 = new ThreadGroup (tg, “groupname”);

· To know the parent of a thread: [Link] ();

· 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] ();

· To change the maximum priority of a thread group tg: [Link] ();

 Thread and ThreadGroup are the classes present in [Link] package.


 ThreadGroup creates a group of threads.
 It is possible to suspend all threads at a time with ThreadGroup.

Two constructors in ThreadGroup are:

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

}
}

class Thread1 extends Thread


{
Thread1(ThreadGroup tg, String name)
{
super([Link]);
}
public void run()
{
try
{
for(int i=1;i<=2;i++)
{
[Link](“From child thread1”);
[Link](1000);
}
}
catch(InterruptedException e)
{
[Link](e);
}
}
}

class Thread2 extends Thread


{
Thread1(ThreadGroup tg, String name)
{
super(tg,name);
}
public void run()
{
try
{
for(int i=1;i<=2;i++)
{
[Link](“From child thread2”);
[Link](1000);
}
}
catch(InterruptedException e)
{
[Link](e);
}
}
}

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

 In Java, any thread can be a Daemon thread.


 Daemon threads are like a service providers for other threads or objects running in
the same process as the daemon thread.
 Daemon threads are used for background supporting tasks and are only needed while
normal threads are executing.
 If normal threads are not running and remaining threads are daemon threads then the
interpreter exits.

setDaemon(true/false) ? This method is used to specify that a thread is 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.

public class DaemonThread extends Thread


{
public void run()
{
[Link](“Enter run method”);
try
{
[Link](“In run method: currentThread() is” +[Link]());

while(true)
{
try
{
[Link](500);
}
catch(InterruptedException x)
{
}

[Link](“In run method: woke up again”);


}
}

Page 30
JAVA PROGRAMMING UNIT - IV 2022-23

public static void main(String args[])


{
[Link](“Entering main method”);

DaemonThread t=new DaemonThread();


[Link](true);
[Link]();

try
{
[Link](3000);
}
catch(InterruptedException x)
{
}

[Link](“Leaving main thread”);


}
}

INTRODUCTION TO COLLECTION FRAMEWORK:

• “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.

• The collection framework is comprised of collection classes and collection interfaces.

• 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.

General form of a Generic class:

Declaring a generic class

class class-name<type-param-list>
{

Declaring a reference to a generic class:

class class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-


arg-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);

Gen<String> strob=new Gen<String>(“Generics Test”);


[Link]();

String str=[Link]();
[Link](str);
}
}

Output:
[Link]
88
[Link]
Generics Test

A Generic Class with Two Type Parameters

class TwoGen<T, V>


{
T ob1;
V ob2;

TwoGen(T o1, V o2)


{
ob1=o1;
ob2=o2;
}

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

public static void main(String args[])


{
TwoGen<Integer, String> obj = new TwoGen<Integer, String> (88,
“Generics”);

[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

COMMONLY USED COLLECTION CLASSESARRAY

LIST

 The ArrayList class implements the List interface.


 Used to implement dynamic array.
 In general, an ArrayList serves the same purpose as an array, except that an ArrayList
can change length while the program is running.

ArrayList has the constructors shown here:

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

[Link]("Initial size of al: " +[Link]());

// add elements to the array list


[Link]("C");
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F");
[Link](1, "A2");
[Link]("Size of al after additions: " +[Link]());

// display the array list


[Link]("Contents of al: " + al);

// Remove elements from the array list


[Link]("F");
[Link](2);

[Link]("Size of al after deletions: " +[Link]());


[Link]("Contents of al: " + al);
}
}

/*
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

• Vector is similar to Array List, but with two differences:


• Vector is synchronized, and it contains many legacy methods that are not part of the
collections framework.

Constructors:

Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)

Page 6
JAVA PROGRAMMING UNIT - IV 2022-23

ARRAY LIST Vs VECTOR

• 1) Synchronization: ArrayList is non-synchronized which means multiple threads can


work on ArrayList at the same time. For e.g. if one thread is performing an add
operation on ArrayList, there can be an another thread performing remove operation
on ArrayList at the same time in a multithreaded environment
• while Vector is synchronized. This means if one thread is working on Vector, no other
thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation
on vector at a time.
• 2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain
the optimal use of storage, however the way they resized is different. ArrayList grow
by half of its size when resized while Vector doubles the size of itself by default when
grows.
• 3) Performance: ArrayList gives better performance as it is non-synchronized. Vector
operations gives poor performance as they are thread-safe, the thread which works on
Vector gets a lock on it which makes other thread wait till the lock is released.

• The Methods Defined by Vector:

 Object elementAt(int index)


 Void addElement(object)
 void insertElementAt(Object element,int index)
 Object lastElement( )
 Object firstElement( )
 boolean isEmpty( )
 void removeAllElements( )
 boolean removeElement(Object element)
 void removeElementAt(int index)
 void setElementAt(Object element,int index)
 void setSize(int size)
 int size( )
import [Link];

public class VectorOperations {

public static void main(String a[]){


Vector<String> vct = new Vector<String>();
//adding elements to the end
[Link]("First");
[Link]("Second");
[Link]("Third");
[Link](vct);

//getting elements by index

Page 7
JAVA PROGRAMMING UNIT - IV 2022-23

[Link]("Element at index 1 is: "+[Link](1));


//getting first element
[Link]("The first element of this vector is: "+[Link]());
//getting last element
[Link]("The last element of this vector is: "+[Link]());
//how to check vector is empty or not
[Link]("Is this vector empty? "+[Link]());
}
}

MAP
• Map is a kind of data structure which associates the key and values.
• There are 3 classes which implements map.

• Hashtable stores key/value pairs in a hash table.


• When using a Hashtable, you specify an object that is used as a key, and the value that
you want linked to that key.

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

[Link]("Todd Hall", new Double(99.22));


[Link]("Ralph Smith", new Double(-19.08));

// Show all balances in hash table.


names = [Link]();
while([Link]()) {
[Link](" "+[Link]());

}
}
}

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 to perform operations of push, pop,search an element.

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

BufferedReader br=new BufferedReader(new


InputStreamReader([Link]));
while(choice<4)
{
[Link]("Stack Operations");
[Link]("1. Push an element");
[Link]("[Link] an element");
[Link]("[Link] an element");
[Link]("Enter your choice");

// Assigning the value to perform the operation.

choice=[Link]([Link]());

// Switch case to perform the operation.

switch(choice)
{

// Operation to be performed when entering the element.

case 1:
[Link]("Enter an element");
element = [Link]([Link]());
[Link](element);
break;

// Operation to be performed when getting the element.

case 2:
[Link]("Which element ? ");
Integer obj = [Link]();
[Link]("Poped element= "+obj);
break;

// Operation to be performed to search the element.

case 3:
[Link]("Which an element ? ");
element = [Link]([Link]());
position = [Link](element);

// Loop to display the element and position.

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];

public class EnumerationTester {

public static void main(String args[]) {


Enumeration days;
Vector dayNames = new Vector();
[Link]("Sunday");
[Link]("Monday");
[Link]("Tuesday");
[Link]("Wednesday");
[Link]("Thursday");
[Link]("Friday");
[Link]("Saturday");
days = [Link]();
while ([Link]()){
[Link]([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( ).

Methods declared by Iterator


• 1. boolean hasNext( ) - Returns true if there are more elements. Otherwise, returns
false.
• 2. Object next( )-Returns the next element. Throws NoSuchElementException if
there is not a next element.
• 3. void remove( ) - Removes the current element. Throws IllegalStateException if an
attempt is made to call remove( ) that is not preceded by a call to next( ).
Methods declared by ListIterator
• 1. void add(Object obj)
• 2. boolean hasNext( )
• 3. boolean hasPrevious( )
• 4. Object next( )
• 5. int nextIndex( )
• 6. Object previous( )
• 7. int previousIndex( )

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[])
{

// Create an array list.


ArrayList<String> al = new ArrayList<String>();
// Add elements to the array list.
[Link]("C");
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F");

// Use iterator to display contents of al.


[Link]("Original contents of al: ");
Iterator<String> itr = [Link]();
while([Link]())
{
String element = [Link]();
[Link](element + " ");
}

[Link]();

// Modify objects being iterated.


ListIterator<String> litr = [Link]();
while([Link]())
{
String element = [Link]();
[Link](element + "+");
}
[Link]("Modified contents of al: ");
itr = [Link]();
while([Link]())
{
String element = [Link]();
[Link](element + " ");
}
[Link]();

// Now, display the list backwards.

Page 13
JAVA PROGRAMMING UNIT - IV 2022-23

[Link]("Modified list backwards: ");


while([Link]())
{
String element = [Link]();
[Link](element + " ");
}
[Link]();
}
}

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.

• int countTokens( ) -determines the number of tokens left to


be parsed and returns the result.
• boolean hasMoreElements( ) -Returns true if one or more tokens remain
in the string and returns false if there are none.
• boolean hasMoreTokens( ) -Returns true if one or more tokens
remain in the string and returns false if there are none.
• Object nextElement( ) -Returns the next token as an Object.
• String nextToken( ) -Returns the next token as a String.
• String nextToken(String delimiters) -Returns the next token as a String
and sets the delimiters string to that specified by delimiters.

Page 14
JAVA PROGRAMMING UNIT - IV 2022-23

import [Link];
import [Link];

// class to accept integers and find the sum using StringTokenizer class

public class StringToken


{
public static void main( String args[] )
{

// accept the values at run time

Scanner scanner = new Scanner( [Link] );


[Link]( "Enter sequence of integers (with space betwen
them) and press Enter" );

// getting the count of integers that were entered

String digit = [Link]();

// creating object of StringTokenizer class

StringTokenizer tokens = new StringTokenizer( digit);


int i=0,dig=0,sum=0,x;

// loop to determine the tokens and find the sum

while ( [Link]() )
{
String s=[Link]();
dig=[Link](s);
[Link](dig+"");
sum=sum+dig;
}

Page 15
JAVA PROGRAMMING UNIT - IV 2022-23

// display the output

[Link]();
[Link]( "sum is "+sum );
}
}

RANDOM

• The Random class is a generator of pseudorandom numbers. These are called


pseudorandom numbers because they are simply uniformly distributed sequences.
Constructors
• Random( )
• Random(long seed)
METHODS
• boolean nextBoolean( ) Returns the next boolean random number.
• void nextBytes(byte vals[ ]) Fills vals with randomly generated values.
• double nextDouble( ) Returns the next double random number.
• float nextFloat( ) Returns the next float random number.
• double nextGaussian( ) Returns the next Gaussian random number.
• int nextInt( ) Returns the next int random number.
• int nextInt(int n) Returns the next int random number within
the range zero to n. (Added by Java 2)
• long nextLong( ) Returns the next long random number.
• void setSeed(long newSeed) Sets the seed value (that is, the starting
point for the random number generator) to
that specified by newSeed.

Page 16
JAVA PROGRAMMING UNIT - IV 2022-23

// Demonstrate iterators.
import [Link].*;
class RandomDemo
{
public static void main(String args[])
{

Random t=new Random();


int x=[Link](10);
[Link]("Random="+x);
}
}

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.

• boolean hasNext( ) boolean hasNext(Pattern pattern)


• boolean hasNext(String pattern) boolean hasNextBigDecimal( )
• boolean hasNextBigInteger( ) boolean hasNextBigInteger(int radix)
• boolean hasNextBoolean( ) boolean hasNextByte( )
• boolean hasNextByte(int radix) boolean hasNextDouble( )
• boolean hasNextFloat( ) boolean hasNextInt( )
• boolean hasNextInt(int radix) boolean hasNextLine( )
• boolean hasNextLong( ) boolean hasNextLong(int radix)

Page 17
JAVA PROGRAMMING UNIT - IV 2022-23

• boolean hasNextShort( ) boolean hasNextShort(int radix)


• String next( ) String next(String pattern)
• boolean nextBoolean( ) byte nextByte( )
• double nextDouble( ) int nextInt( )
• String nextLine( ) long nextLong()
• short nextShort( )

CALENDER And PROPERTIES

• An instance of [Link] represents a specific instant in time with millisecond


precision. [Link] is an abstract base class for extracting detailed
information such as year, month, date, hour, minute and second from a Date object.
Subclasses of Calendar can implement specific calendar systems such as Gregorian
calendar, Lunar Calendar and Jewish calendar. Currently, [Link]
for the Gregorian calendar is supported in the Java API.

• Calendar provides no public constructors.

• 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

components that can be requested are [Link], [Link],


[Link], and so forth.
• static Calendar getInstance( ) - Returns a Calendar object for the default
locale and time zone.
• final Date getTime( ) - Returns a Date object equivalent to
the time of the invoking object.
• final void set(int year, int month, int dayOfMonth) -Sets various date and time
components of the invoking object.
• final void setTime(Date d) - Sets various date and time
components of the invoking object. This information is obtained from the Date object
d.
// Demonstrate Calendar
import [Link];
class CalendarDemo
{
public static void main(String args[])
{
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"
};
// Create a calendar initialized with the
// current date and time in the default
// locale and timezone.

Calendar calendar = [Link]();

// Display current time and date information.

[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]));

// Set the time and date information and display it.

[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.

 Streams are of two types:

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

Reading the Text Input from console:


To accept data from the keyboard:
· Connect the keyboard to an input stream object. Here, we can use InputStreamReader
that can read data from the keyboard.

InputSteamReader obj = new InputStreamReader ([Link]);

· Connect InputStreamReader to BufferReader, which is another input type of stream.


We are using BufferedReader as it has got methods to read data properly, coming from the
stream.

BufferedReader br = new BufferedReader (obj);

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.

Accepting a Single Character from the Keyboard:


· Create a BufferedReader class object (br).
· Then read a single character from the keyboard using read() method as:
char ch = (char) [Link]();
· 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.
Writing the Output:
The simple method used for writing the output on the console is write().
[Link](int b)
But typically print() or println() is used to write the output on the console. And these
methods belong to PrintWriter class.

// Accepting and displaying student details.


import [Link].*;
class TextInput
{ public static void main(String args[]) throws IOException
{ // Create BufferedReader object to accept data
BufferedReader br =new BufferedReader (new InputStreamReader ([Link]));

Page 25
JAVA PROGRAMMING UNIT - IV 2022-23

//Accept student details


[Link] ("Enter roll number: ");
int rno = [Link] ([Link]());
[Link] ("Enter Gender (M/F): ");
char gender = (char)[Link]();

[Link] ("Roll No.: " + rno);


[Link] ("Gender: " + gender);
}}

Binary Input/Output

The following classes are also commonly used with binary files, for both JDK 7 and
earlier versions:

When reading and writing binary files:


• it's almost always a good idea to use buffering (default buffer size is 8K)
• it's often possible to use references to abstract base classes,
• pay attention to exceptions
(in particular, IOException and FileNotFoundException)
The [Link] class is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some
[Link] that need to define a subclass of OutputStream must always provide at least
a method that writes one byte of output.
void close() - This method closes this output stream and releases any system resources
associated with this stream.

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);}
}
}

Example: FileInputStream and FileOutputStream

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

RANDOM ACCESS FILE OPERATION


• The input and streams discussed till now are sequential access streams--streams whose
contents must be read or written sequentially.
• Sequential access files are leftovers from the days of magnetic tape and other naturally
sequential medium.
• Random access files, on the other hand, permit non-sequential, or random, access to
the contents of a file.
• RandomAccessFile(String fileName, String access) throws FileNotFoundException
• Access - “r” - read but not written
• “rw” - read-write mode
• “rwd” – data to be written immediately to the device.
• The method seek() is used to set the current position of the file pointer within the file:
• void seek(long newPos) throws IOException
• newPos- specifies the new position, in bytes, of the file pointer from the beginning of
the file.
• RandomAccessFile implements read() and write() methods.
import [Link].*;
class RandomAccessDemo
{
public static void main(String args[])
{
double data[]={19.4,10.1,123.54,33.0,87.9,74.25};
double d;
try (RandomAccessFile raf=new
RandomAccessFile("[Link]","rw"))
{
for(int i=0;i<[Link];i++)
{
[Link](data[i]);
}
[Link](0);
d=[Link]();
[Link]("First Value:"+d);

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);

[Link]("Here is alternative values");


for(int i=0;i<[Link];i+=2)
{
[Link](8*i);
d=[Link]();
[Link](d+" ");
}
}
catch(IOException ex)
{
[Link]("I/O error");
}
}
}

Page 30
JAVA PROGRAMMING UNIT - IV 2022-23

FILE MANAGEMENT: USING FILE CLASS

• File deals directly with files and file system.


• The File class does not specify how information is retrieved from or stored in files; it
describes the properties of file itself.
• A File object is used to obtain or manipulate the information associated with a disk
file, such as time, date, permission, directory path etc.,
• Constructors:
• File(String path)
• File(String directoryPath, String filename)
Method Description

boolean canRead() Returns true if the file can read

boolean canWrite() Returns true if the file can be written

boolean exists() Returns true if the file exists

String getAbsolutePath() Returns absolute path to the file

String getName() Returns the file name.

String getParent() Returns name of the file’s parent directory, or null if no parent

boolean is Absolute() Returns true if the path is absolute, false if relative

boolean isDirectory() Return true if the file is directory.

boolean isFile() Returns true if the file is “normal” file.

boolean isHidden() Returns true if the invoking file is hidden.

long length() returns length of the file in bytes.

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:

// Import the package to access

File Stream class. import [Link].*;

class file1
{
public static void main(String args[]) throws Exception
{

// Creating FileInputStream and read the file [Link].

FileInputStream f1=new
FileInputStream("[Link]"); int
size=(byte)[Link]();

// Loop to check whether file is

readable or writable. if([Link]()==0)


[Link]("the
file is readable");else
[Link](" the file is writable");

// Display the size of the file.

[Link]("the size of the file in bytes"+size);


}
}

// The data in [Link].

[Link]
class abc
{
public static void main(String args[])
{
}
}

Output:

the file is writable

Page 32
JAVA PROGRAMMING UNIT - IV 2022-23
the size of the file in bytes 70

Page 33
JAVA PROGRAMMING UNIT - IV 2022-23

AWT CLASS HIERARCHY


Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-
based applications in Java.

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.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

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:

There are four types of containers in Java AWT:

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.

Useful Methods of Component Class


Method Description

public void add(Component c) Inserts a component on this component.

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.

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame in
AWT.

By extending Frame class (inheritance)

By creating the object of Frame class (association)

AWT Example by Inheritance


Page 3
JAVA PROGRAMMING UNIT - IV 2022-23

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.

[Link]

// importing Java AWT class


import [Link].*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


[Link](30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {

Page 4
JAVA PROGRAMMING UNIT - IV 2022-23

// creating instance of Frame class


AWTExample1 f = new AWTExample1();
}

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
creating a TextField, Label and Button component on the Frame.

[Link]

// importing Java AWT class

import [Link].*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// creating a Frame
Frame f = new Frame();

// creating a Label

Page 5
JAVA PROGRAMMING UNIT - IV 2022-23

Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


[Link](20, 80, 80, 30);
[Link](20, 100, 80, 30);
[Link](100, 100, 80, 30);

// adding components into frame


[Link](b);
[Link](l);
[Link](t);

// frame size 300 width and 300 height


[Link](400,300);

// setting the title of frame


[Link]("Employee info");

// no layout
[Link](null);

// setting visibility of frame


[Link](true);
}

// main method
public static void main(String args[]) {

/ // creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

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:

It works at client side so less response time.

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.

Lifecycle of Java Applet


Applet is initialized.

Applet is started.

Applet is painted.

Applet is stopped.

Applet is destroyed.

Page 8
JAVA PROGRAMMING UNIT - IV 2022-23

Lifecycle methods for Applet:


The [Link] class 4 life cycle methods and [Link] class provides 1 life cycle
methods for an applet.

[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

How to run an Applet?


There are two ways to run an applet

By html file.

By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

/[Link]
import [Link];
import [Link];
public class First extends Applet{

public void paint(Graphics g){


[Link]("welcome",150,150);
}

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

public void paint(Graphics g){


[Link]("welcome to applet",150,150);
}

}
/*
<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

The MVC model component can be tested separately.


The components of MVC can be developed simultaneously.
It reduces complexity by dividing an application into three units. Model, view, and
controller.
It supports Test Driven Development (TDD).
It works well for Web apps that are supported by large teams of web designers and
developers.
This architecture helps to test components independently as all classes and objects are
independent of each other
Search Engine Optimization (SEO) Friendly.

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

Popular MVC Frameworks:


Some of the most popular and extensively used MVC frameworks are listed below.
Ruby on Rails
Django
CherryPy
Spring MVC
Catalyst
Rails
Zend Framework
Fuel PHP
Laravel
Symphony

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.

Delegation Event model

It has Sources and Listeners.

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.

Registering the Source With Listener

Different Classes provide different registration methods.


Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a component-


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

AdjustmentEvent AdjustmentListener
The adjustment event is emitted by an

Page 16
JAVA PROGRAMMING UNIT - IV 2022-23

Event Class Listener Interface Description

Adjustable object like Scrollbar.

An event that indicates that a component


moved, the size changed or changed its
ComponentEvent ComponentListener visibility.

When a component is added to a container (or)


removed from it, then this event is generated by
ContainerEvent ContainerListener a container object.

These are focus-related events, which include


FocusEvent FocusListener focus, focusin, focusout, and blur.

An event that indicates whether an item was


ItemEvent ItemListener selected or not.

An event that occurs due to a sequence of


KeyEvent KeyListener keypresses on the keyboard.

MouseListener & The events that occur due to the user


MouseEvent MouseMotionListener interaction with the mouse (Pointing Device).

An event that specifies that the mouse wheel


MouseWheelEvent MouseWheelListener was rotated in a component.

An event that occurs when an object’s text


TextEvent TextListener changes.

An event which indicates whether a window


WindowEvent WindowListener has changed its status or not.

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

Listener Interface Methods

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

Listener Interface Methods

windowClosed()
windowClosing()
windowIconified()
windowDeiconified()

Flow of Event Handling

User Interaction with a component is required to generate an event.


The object of the respective event class is created automatically after event generation, and
it holds all information of the event source.
The newly created object is passed to the methods of the registered listener.
The method executes and returns the result.

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

Event Handling Within Class

// Java program to demonstrate the


// event handling within the class

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

class GFG extends Frame implements ActionListener {

TextField textField;

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

// setBounds method is used to provide


// position and size of the component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
Page 19
JAVA PROGRAMMING UNIT - IV 2022-23

[Link](100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
[Link](this);

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

// set visibility
setVisible(true);
}

// implementing method of actionListener


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

public static void main(String[] args)


{
new GFGTop();
}
}

Event Handling by Other Class

// Java program to demonstrate the

Page 20
JAVA PROGRAMMING UNIT - IV 2022-23

// event handling by the other class

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

class GFG1 extends Frame {

TextField textField;

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

// setBounds method is used to provide


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

Other other = new Other(this);

// Registering component with listener


// Passing other class as reference
[Link](other);

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

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG2();
}
}

/// import necessary packages


import [Link].*;

// implements the listener interface


class Other implements ActionListener {

GFG2 gfgObj;

Page 21
JAVA PROGRAMMING UNIT - IV 2022-23

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

public void actionPerformed(ActionEvent e)


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

Event Handling By Anonymous Class

// Java program to demonstrate the


// event handling by the anonymous class

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

class GFG3 extends Frame {

TextField textField;

GFG3()
{

Page 22
JAVA PROGRAMMING UNIT - IV 2022-23

// Component Creation
textField = new TextField();

// setBounds method is used to provide


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

// Registering component with listener anonymously


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

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

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}

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 was developed by JavaSoft, a subsidiary of Sun MicroSystems.

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

JDBC Type 1 to 4 Drivers

JDBC Type 1 – JDBC-ODBC Bridge

Page 27
JAVA PROGRAMMING UNIT - IV 2022-23

JDBC Type 2 – Native-API Driver (Partly Java Driver)

JDBC Type 3 – Network Protocol Driver

Page 28
JAVA PROGRAMMING UNIT - IV 2022-23

JDBC Type 4 – Thin Driver (Pure Java Driver)

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);

// Now you can extract all the records


// to see the updated records
sql = "SELECT id, first, last, age FROM

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.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is part of the
standard Java distribution. By today’s application GUI requirements, AWT is a limited implementation,
not quite capable of providing the components required for developing complex 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

The MVC Connection

 In general, a visual component is a composite of three distinct aspects:


1. The way that the component looks when rendered on the screen
2. The way such that the component reacts to the user
3. The state information associated With the component
 Over the years, one component architecture has proven itself to be exceptionally effective:- Model-
View-Controller or MVC for short.
 In MVC terminology, the model corresponds to the state information associated with the Component
 The view determines how the component is displayed on the screen, including any aspects of the view
that are affected by the current state of the model.
 The controller determines how the component reacts to the user
The simplest Swing components have capabilities far beyond AWT components as follows:
Page 2
JAVA PROGRAMMING UNIT - V 2022-23

 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 {

// Main driver method


public static void main(String[] args)
{
JFrame frame
= new JFrame(); // creating instance of JFrame

JButton button = new JButton(


" GFG WebSite Click"); // creating instance of
// JButton
[Link](
150, 200, 220,
50); // x axis, y axis, width, height

[Link](button); // adding button in JFrame

[Link](500, 600); // 400 width and 500 height


[Link](null); // using no layout managers
[Link](true); // making the frame visible
}
}

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);
}

public static void main(String a[]) {


new button();
}
}

Example 3 :

import [Link].*;
class Lan {
Lan() {
Frame f = new Frame();

Label l1 = new Label("Select known Languages");

[Link](100, 50, 120, 80);


[Link](l1);

Checkbox c2 = new Checkbox("Hindi");


[Link](100, 150, 50, 50);
[Link](c2);
Checkbox c3 = new Checkbox("English");

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);
}

public static void main(String ar[]) {


new Lan();
}
}

Components of Swing Classthe task’s percentage

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

Container A Container is a component that can container SWING Components

A JComponent is a base class for all swing UI Components In order to use a


JComponent swing component that inherits from JComponent, component must be in a

Page 6
JAVA PROGRAMMING UNIT - V 2022-23

Class Description

containment hierarchy whose root is a top-level Swing container

JLabel A JLabel is an object component for placing text in a container

JButton This class creates a labeled button

A JColorChooser provides a pane of controls designed to allow the user to


JColorChooser manipulate and select a color

A JCheckBox is a graphical(GUI) component that can be in either an on-(true) or


JCheckBox off-(false) state

The JRadioButton class is a graphical(GUI) component that can be in either an


JRadioButton on-(true) or off-(false) state. in the group

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

JPasswordField A JPasswordField object it is a text component specialized for password entry

A JTextArea object s a text component that allows for the editing of multiple
JTextArea lines of text

A ImageIcon control is an implementation of the Icon interface that paints Icons


Imagelcon from Images

A JScrollbar control represents a scroll bar component in order to enable users to


JScrollbar Select from range values

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:

Execution of Servlets basically involves six basic steps:


1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the webserver.

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.

Difference between Servlet and CGI

Servlet CGI(Common Gateway Interface)

Page 9
JAVA PROGRAMMING UNIT - V 2022-23

Servlet CGI(Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

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:

Component Type Package

Servlet Interface [Link].*

ServletRequest Interface [Link].*

ServletResponse Interface [Link].*

GenericServlet Class [Link].*

HttpServlet Class [Link].*

HttpServletRequest Interface [Link].*

HttpServletResponse Interface [Link].*

Filter Interface [Link].*

ServletConfig Interface [Link].*

Advantages of a Java Servlet


 Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request
received.

Page 10
JAVA PROGRAMMING UNIT - V 2022-23

 Servlets, as written in Java, are platform-independent.


 Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate
process. There is only a single instance that handles all requests concurrently. This also saves the
memory and allows a Servlet to easily manage the client state.
 It is a server-side component, so Servlet inherits the security provided by the Web server.
 The API designed for Java Servlet automatically acquires the advantages of the Java platforms such
as platform-independent and portability. In addition, it obviously can use the wide range of APIs
created on Java platforms such as JDBC to access the database.
 Many Web servers that are suitable for personal use or low-traffic websites are offered for free or at
extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web servers are
rather expensive, with the notable exception of Apache, which is free.

The Servlet Container:


Servlet container, also known as Servlet engine is an integrated set of objects that provide a run time
environment for Java Servlet components.
In simple words, it is a system that manages Java Servlet components on top of the Web server to handle
the Web client requests.
Services provided by the Servlet container :
 Network Services: Loads a Servlet class. The loading may be from a local file system, a remote file
system or other network services. The Servlet container provides the network services over which the
request and response are sent.
 Decode and Encode MIME-based messages: Provides the service of decoding and encoding MIME-
based messages.
 Manage Servlet container: Manages the lifecycle of a Servlet.
 Resource management Manages the static and dynamic resources, such as HTML files, Servlets, and
JSP pages.
 Security Service: Handles authorization and authentication of resource access.
 Session Management: Maintains a session by appending a session ID to the URL path.

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

Interfaces and Classes in [Link] package

Interfaces in [Link] package


1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in [Link] package

The Classes are in [Link] package are listed below:


1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

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 And Classes in [Link] package

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

Classes in [Link] package


1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

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.

HttpServletRequestWrapper and HttpServletResponseWrapper: this two wrapper classes allowing


capability of the HttpServletResponse and HttpServletRequest interfaces to the servlet by its functions

HttpSessionEvent: This class HttpSessionEvent notified as any activity or changes/editing are


encountered in the session of web applications in servlet.

HttpSessionBindingEvent: This class notified when any attribute is bounded, unbounded or replaced in
any Current session

Page 14

You might also like