Java Object-Oriented Programming Guide
Java Object-Oriented Programming Guide
IMPORTANT TOPICS
MODULE 1
MODULE 2
MODULE 3
MODULE 4
MODULE 5
MODULE 1
INTRODUCTION:
Approaches to Software Design - Functional Oriented Design, Object Oriented Design, Case
Study of Automated Fire Alarm System.
Object Modeling Using Unified Modeling Language (UML) – Basic Object Oriented concepts,
UML diagrams, Use case model, Class diagram, Interaction diagram, Activity diagram, State chart
diagram.
Example:
CST 205: MODULE 1
Example:
MULTIPLICITY
Indicates how many objects of each class taken part in relationship.
CST 205: MODULE 1
NB: (Assign type of value returned in this diagram as I described during class)
CST 205: MODULE 1
Sequence and collaboration diagrams are used to capture the dynamic nature but from a
different angle.
Following things are to be identified clearly before drawing the interaction diagram:
Object organization.
The following diagram shows the message sequence for SpecialOrder object and the same
can be used in case of NormalOrder object. It is important to understand the time sequence
of message flows. The message flow is nothing but a method call of an object.
The first call is sendOrder () which is a method of Order object. The next call is confirm
() which is a method of SpecialOrder object and the last call is Dispatch () which is a
method of SpecialOrder object. The following diagram mainly describes the method calls
from one object to another, and this is also the actual scenario when the system is running.
CST 205: MODULE 1
2) Collaboration Diagram
The second interaction diagram is the collaboration diagram. It shows the object
organization as seen in the following diagram. In the collaboration diagram, the method
call sequence is indicated by some numbering technique. The number indicates how the
methods are called one after another. We have taken the same order management system
to describe the collaboration diagram.
Method calls are similar to that of a sequence diagram. However, difference being the
sequence diagram does not describe the object organization, whereas the collaboration
diagram shows the object organization.
To choose between these two diagrams, emphasis is placed on the type of requirement. If
the time sequence is important, then the sequence diagram is used. If organization is
required, then collaboration diagram is used.
ACTIVITY DIAGRAMS
Activity diagram is another important diagram in UML to describe the dynamic aspects
of the system.
Activity diagram is basically a flowchart to represent the flow from one activity to
another activity. The activity can be described as an operation of the system.
The control flow is drawn from one operation to another. This flow can be sequential,
branched, or concurrent.
Activity is a particular operation of the system. Activity diagrams are not only used for
visualizing the dynamic nature of a system, but they are also used to construct the
executable system by using forward and reverse engineering techniques. The only missing
thing in the activity diagram is the message part.
It does not show any message flow from one activity to another. Activity diagram is
sometimes considered as the flowchart. Although the diagrams look like a flowchart, they
are not. It shows different flows such as parallel, branched, concurrent, and single.
Before drawing an activity diagram, we must have a clear understanding about the
elements used in activity diagram. The main element of an activity diagram is the activity
itself. An activity is a function performed by the system. After identifying the activities,
we need to understand how they are associated with constraints and conditions.
Activities
Association
Conditions
Constraints
Once the above-mentioned parameters are identified, we need to make a mental layout of
the entire flow. This mental layout is then transformed into an activity diagram.
After receiving the order request, condition checks are performed to check if it is normal
or special order. After the type of order is identified, dispatch activity is performed and
that is marked as the termination of the process.
Activity diagram is suitable for modeling the activity flow of the system. An application
can have multiple systems. Activity diagram also captures these systems and describes the
CST 205: MODULE 1
flow from one system to another. This specific usage is not available in other diagrams.
These systems can be database, external queues, or any other system.
We will now look into the practical applications of the activity diagram. From the above
discussion, it is clear that an activity diagram is drawn from a very high level. So it gives
high level view of a system. This high level view is mainly for business users or any other
person who is not a technical person.
This diagram is used to model the activities which are nothing but business requirements.
The diagram has more impact on business understanding rather than on implementation
details.
STATECHART DIAGRAMS
Statechart diagram define different states of an object during its lifetime and these states
are changed by events.
Statechart diagrams are useful to model the reactive systems. Reactive systems can be
defined as a system that responds to external or internal events.
Statechart diagram describes the flow of control from one state to another state. States
are defined as a condition in which an object exists and it changes when some event is
triggered. The most important purpose of Statechart diagram is to model lifetime of an
object from creation to termination.
CST 205: MODULE 1
Statechart diagrams are also used for forward and reverse engineering of a system.
However, the main purpose is to model the reactive system.
Statechart diagrams are very important for describing the states. States can be identified
as the condition of objects when a particular event occurs.
The first state is an idle state from where the process starts. The next states are arrived for
events like send request, confirm request, and dispatch order. These events are responsible
for the state changes of order object.
CST 205: MODULE 1
During the life cycle of an object (here order object) it goes through the following states
and there may be some abnormal exits. This abnormal exit may occur due to some problem
in the system. When the entire life cycle is complete, it is considered as a complete
transaction as shown in the following figure. The initial and final state of an object is also
shown in the following figure.
Statechart diagrams are used to model the states and also the events operating on the
system. When implementing a system, it is very important to clarify different states of an
object during its life time and Statechart diagrams are used for this purpose. When these
CST 205: MODULE 1
states and events are identified, they are used to model it and these models are used during
the implementation of the system.
If we look into the practical implementation of Statechart diagram, then it is mainly used
to analyze the object states influenced by events. This analysis is helpful to understand the
system behavior during its execution.
INTRODUCTION TO JAVA
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX. The language was developed by James Gosling.
(JAVA BUZZWORDS)
Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
web and interpreted by the Java Virtual Machine (JVM) on whichever platform it
is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master. Java is similar to C++, but with most of
the more complex features of C and C++ removed.
A programming language
CST 205: MODULE 1
An API specification
A virtual machine specification
Java runtime, or Java runtime environment (JRE), is a set of the minimum components
necessary to create and run a Java application and is part of a Java development kit (JDK).
It is made up of the Java virtual machine (JVM), Java class libraries, and the Java class
loader. So, while a developer would use a JDK to develop Java software, a JRE is made
up of tools used to program and run Java applications, and a JVM is a kind of computer-
within-a-computer, the purpose of which is to execute a Java program.
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
All Java platforms consist of a Java Virtual Machine (VM) and an application
programming interface (API). The Java Virtual Machine is a program, for a particular
hardware and software platform, that runs Java technology applications. An API is a
collection of software components that you can use to create other software components
or applications. Each Java platform provides a virtual machine and an API, and this
allows applications written for that platform to run on any compatible system with all
the advantages of the Java programming language: platform-independence, power,
stability, ease-of-development, and security.
Java SE
When most people think of the Java programming language, they think of the Java
SE API. Java SE's API provides the core functionality of the Java programming
language. It defines everything from the basic types and objects of the Java
CST 205: MODULE 1
programming language to high-level classes that are used for networking, security,
database access, graphical user interface (GUI) development, and XML parsing.
In addition to the core API, the Java SE platform consists of a virtual machine,
development tools, deployment technologies, and other class libraries and toolkits
commonly used in Java technology applications.
Java EE
The Java EE platform is built on top of the Java SE platform. The Java EE platform
provides an API and runtime environment for developing and running large-scale,
multi-tiered, scalable, reliable, and secure network applications.
• Bytecode is an intermediary language between Java source and the host system.
• It is the medium which compiles Java code to bytecode which gets interpreted on
a different machine and hence it makes it Platform/Operating system independent.
CST 205: MODULE 1
JVM is the main component of Java architecture and it is the part of the JRE (Java
Runtime Environment).
A program of JVM is written into “ C Programming Language” aqnd JVM is
Operating System dependent.
JVM is responsible to allocate the necessary memory needed by the Java program.
JVM is responsible to deallocate memory space.
CST 205: MODULE 1
JAVA APPLET
CST 205: MODULE 1
LEXICAL ISSUES
Java programs is a collection of White spaces , Identifiers , comments , Literals ,
Operators ,Separators and Keywords.
1. White Spaces
Java is a free form language. This means that you do not need to follow any special
indentation rules. In java, white spaces is a space , tab or new line.
CST 205: MODULE 1
2. Identifiers
Identifiers are used for class names, method names and variable names. An identifier may
be any descriptive sequence of uppercase and lowercase letters, numbers or the
underscore and dollar sign design.
3. Literals (Constants)
A constant value in java is created by using a literal representation of it. A literal can be
used anywhere a value of its type is allowed.
4. Comments
First is single line comment (//)and the second one is multi line comment. (/*….*/)
5. Separators
There are few symbols in java that are used as [Link] most commonly used
separator in java is the semicolon ' ; '. some other separators are Parentheses '( )' , Braces '
{} ' , Bracket ' [] ' , Comma ' , ' , Period ' . ' .
6. Java Keywords
There are 49 reserved keywords currently defined in java. These keywords cannot be
used as names for a variable, class or method.
The Keywords are : abstract , assert , Boolean , break , byte , case , catch , char , class ,
const , continue , default , do , double , else , extends , final , finally , float , for , goto , if ,
implements , import , instanceof , int, interface , long , native , new , package , private ,
protected , public , return , short , static , strictfp , super , switch , synchronized , this ,
throw , throws , transient , try , void , volatile, while.
CST 205: MODULE 1
GARBAGE COLLECTION
Java garbage collection is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on
the heap, which is a portion of memory dedicated to the program. Eventually, some objects
will no longer be needed. The garbage collector finds these unused objects and deletes
them to free up memory.
1. Documentation Section
2. Package Statement
3. Import Statement
4. Interface Section
5. Class Definition
6. Main Method Class
Documentation Section
It is used to improve the readability of the program. It consists of comments in Java which
include basic information such as the method’s usage or functionality to make it easier for
CST 205: MODULE 1
the programmer to understand it while reviewing or debugging the code. A Java comment
is not necessarily limited to a confined space, it can appear anywhere in the code.
There are three types of comments that Java supports
Package Statement
There is a provision in Java that allows you to declare your classes in a collection
called package. There can be only one package statement in a Java program and it has to
be at the beginning of the code before any class or interface declaration.
Import Statement
Many predefined classes are stored in packages in Java, an import statement is used to refer
to the classes stored in other packages. An import statement is always written after the
package statement but it has to be before any class declaration.
Interface Section
This section is used to specify an interface in Java. It is an optional section which is mainly
used to implement multiple inheritance in Java. An interface is a lot similar to a class in
Java but it contains only constants and method declarations.
The main method is from where the execution actually starts and follows the order
specified for the following statements. Let’s take a look at a sample program to understand
how it is structured.
CST 205: MODULE 1
Example:
public class Example //main() should be declared inside the class and use this
//class name as program name, eg: [Link]
{
public static void main (String args []) // main method declaration
{
[Link](“hello world”); //printing statement
}
}
Let’s analyze the above program line by line to understand how it works.
Comments
To improve the readability, we can use comments to define a specific note or functionality
of methods, etc for the programmer.
Braces
The curly brackets are used to group all the commands together. To make sure that the
commands belong to a class or a method.
String[] args
It is an array where each element is a string, which is named as args. If you run the Java
code through a console, you can pass the input parameter. The main() takes it as an input.
[Link]();
The statement is used to print the output on the screen where the system is a predefined
class, out is an object of the PrintWriter class. The method println prints the text on the
screen with a new line. All Java statements end with a semicolon.
JAVA COMMENTS
The Java comments are the statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about
the variable, method, class or any statement. It can also be used to hide program code.
Syntax:
Example:
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
Output:
10
Syntax:
CST 205: MODULE 1
/**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 num
bers.*/
-
public class Calculator
{
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b)
{
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b)
{
return a-b;
}
}
-
javac [Link]
javadoc [Link]
Now, there will be HTML files created for your Calculator class in the current directory.
Open the HTML files and see the explanation of Calculator class provided through
documentation comment.
CST 205 OBJECT ORIENTED PROGRAMMING IN JAVA
MODULE 1 IMPORTANT QUESTIONS AND ANSWERS
*note: Since there are many rooms, fire detectors, alarms, sprinklers, corresponding data needs
to store in array variables.
Answer
● For drawing an use case diagram first and foremost identify the actors (users)who are going
to interact with the system:
In the case of Online Music Player, following are the actors: Listeners, Admin
● Now Identify various usecases (operations) associated with each
user Listeners: Login, SearchMusic, PlayMusic, Stop,
ChangeSettings Admin: Login, ManageUser, ManageSongs
LOGIN
SEARCH
MANAGE
USER
PLAY
MANAGE
STOP SONGS
CHANGE
Member Variables
Member Functions
Student
+name : String
+rn : int
+rank : int
- fees : long
+
displayDetails(n:Stri
ng, r: int) : void
+displayRank(
ra:int): void
● JRE acts as a translator and facilitator, so that Java programs are portable from one system to
another without modifications.
● Java Class libraries contains predefined functions that can be called whenever required.
● Class Loader connects Class Libraries and JVM by loading the required libraries to JVM.
● JVM is the part that executes the code.
● Java Programming Environment consist of a programming language, API Specification and a
Virtual Machine.
10. Explain ByteCodes and JVM.
11. Why java is Platform Independent? Give reasons.
12. Why Java programs are called WORA (Write Once Run Anywhere)
Answer
● Bytecode and JVM in Java is the reason java is platform-independent.
● Bytecodes are generated in .class format when a program is successfully compiled for the first
time.
● It is the instruction set for Java Virtual Machine (JVM).
● When a Java program is executed, the compiler compiles
that piece of code and a Bytecode is generated for each
method in that program in the form of a .class file.
● We can run this bytecode on any other platform as well.
But the bytecode is a non-runnable code that requires or
relies on an interpreter. This is where JVM plays an
important part.
● The bytecode generated after the compilation is run by the
Java virtual machine. Resources required for the
execution are made available by the Java virtual machine
for smooth execution which calls the processor to allocate
the resources.
● JVM (Java Virtual Machine) acts as a run time engine to run Java based applications. It is the
part that invokes main function of a Java Program.
● Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any other
Java-enabled system without any adjustment. This is all possible because of JVM.
● When we compile a .java file, .class files (contains byte-code) with the same class
names present in .java file are generated by the Java compiler.
Answer
Java Applications
● They are normal java programs that require a main () function.
● Have full access to local storage.
● Trusted by OS.
● For execution a web browser isn’t
required Example:
class Sample
{
public static void main(String args[])
{
}
}
Java Applets
● Applets are programs that can be embedded in an HTML website.
● It runs inside a web browser and requires an extension of JDK to be installed in the browser
for execution.
● Doesn’t have full access to local storage, can’t read and write without permission.
● It doesn’t require a main() method for its execution.
● A java applet program consist of following functions: init(), start() and paint().
Example:
import
[Link];
import [Link];
// importing necessary packages
public class SampleApplet extends Applet //class must extend Applet class in java
{
public void paint(Graphics g) // paint function includes all graphics related operations
{
// printing the message using drawString() method
// other parameters are of the position
[Link]("Java Applet", 250, 250);
}
}
16. Explain Java Buzzwords. (Properties of Java Programming Language)
Answer
● Object oriented - Java provides the basic object technology of C++ with some enhancements
and some deletions.
● Architecture neutral - Java source code is compiled into architecture-independent object
code. The object code is interpreted by a Java Virtual Machine (JVM) on the target
architecture.
● Portable - Java implements additional portability standards. For example, ints are always 32-
bit, 2's-complemented integers. User interfaces are built through an abstract window system
that is readily implemented in Solaris and other operating environments.
● Distributed - Java contains extensive TCP/IP networking facilities. Library routines support
protocols such as HyperText Transfer Protocol (HTTP) and file transfer protocol (FTP).
● Robust - Both the Java compiler and the Java interpreter provide extensive error checking.
Java manages all dynamic memory, checks array bounds, and other exceptions.
● Secure - Features of C and C++ that often result in illegal memory accesses are not in the
Java language. The interpreter also applies several tests to the compiled code to check for
illegal code. After these tests, the compiled code causes no operand stack over- or underflows,
performs no illegal data conversions, performs only legal object field accesses, and all opcode
parameter types are verified as legal.
● High performance - Compilation of programs to an architecture independent machine-like
language, results in a small efficient interpreter of Java programs. The Java environment also
compiles the Java bytecode into native machine code at runtime.
● Multithreaded - Multithreading is built into the Java language. It can improve interactive
performance by allowing operations, such as loading an image, to be performed while
continuing to process user actions.
● Dynamic - Java does not link invoked modules until runtime.
● Simple - Java is similar to C++, but with most of the more complex features of C and C++
removed.
- Member variables associated with Student class are: name, rollno, marks, rank, fees…
- Methods associated with Student class are: displayDetails(), payFees() etc…
2. Objects: Instance of a class. All objects belonging to a class share common variables and
methods. However the values of variables differ across objects.
Eg: In a Student class, objects will be different students say stud1, stud2, stud3…..All these objects
have name, rollno, marks, rank and fees that may contain different values. In addition all these
objects can perform the operations displayDetails(), payFees() defined in class Student.
3. Encapsulation: Wrapping up of data and methods into a single entity. The only way to access
data is through methods.
In the above example Employee class is trying to access the Teachers data through the member
method displayDetails() of class Teachers. It is possible because the data and methods of classes are
wrapped as a single entity by means of encapsulation.
4. Inheritance: It is a process by which object of one class inherit the properties of objects of
another class. It is the capability to define a new class in terms of an existing class. The existing class
or Parent class is known as a base class or super class and the new class or child class is known as
derived class or sub class. Inheritance supports code reusability.
Example : Consider a parent class named Vehicle and its members as given in the figure.
• Vehicle is a class having member variables String reg_no, model, color, int
fuel_capacity and member functions void vehicleDetails(), void fillfuel() and void
calculateSpeed().
• wo subclasses of the class Vehicle are created Car and Bus. The subclasses will inherit
the member variables and functions of Vehicle class. Car and Bus can have their own
member variables as shown in the figure.
5. Abstraction: Abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces. Its main
goal is to handle complexity by hiding unnecessary details from the user. That enables the user to
implement more complex logic on top of the provided abstraction without understanding or even
thinking about all the hidden complexity.
● Dynamic Polymorphism
● Static Polymorphism
In Dynamic polymorphism, the object creation is done at run-time the form of method which should
be executed (the method in the object) can be only decided at run-time. Method Overriding is a type
of Dynamic polymorphism or Run Time Polymorphism. In method overriding, when functions of
same signature is used in both parent and child, the function of superclass will be overridden by the
subclass method.
In Static Polymorphism, method overloading happens. Method overloading is having more than one
method with the same method name but with different arguments (return type may or may not be
same). Here when calling the methods compiler compiler choose which method to call depending on
the parameters passed when calling. This happens at compile-time
A Single-line comment starts and ends in the same line. To write a single-line comment, we can use
the // symbol. For example,
// "Hello, World!" program example
class Main
{
public static void main(String[] args)
{
// prints "Hello, World!"
[Link]("Hello, World!");
}
}
Teachers
int tid
String name, designation
void displayDetsils()
Employee
The Java compiler ignores everything from // to the end of line. Hence, it is also known as End of
Line comment.
Multi Line Comments: When we want to write comments in multiple lines, we can use the
multi- line comment. To write multi-line comments, we can use the /*. */ symbol. For example,
*/
class HelloWorld {
[Link]("Hello, World!");
This type of comment is also known as Traditional Comment. In this type of comment, the Java
compiler ignores everything from /* to */.
Documentation Comments: This type of comment is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */ .
• Comments: Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
*/
class HelloWorld {
[Link]("Hello, World!");
• Separators: In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon.
• Keywords: There are 50 keywords currently defined in the Java language. These keywords,
combined with the syntax of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as identifiers. Thus, they cannot be used as names
for a variable, class, or method. The keywords const and goto are reserved but not used. In the
early days of Java, several other keywords were reserved for possible future use.
// program body
…………….
eg: [Link]
….
- public : It has to be public so that java runtime can execute this method. If you make any
method non-public then it’s not allowed to be executed by any program, there are some access
restrictions applied.
- static : java runtime starts, there is no object of the class present. That’s why the main method
has to be static so that JVM can load the class into memory and call the main method. If the
main method won’t be static, JVM would not be able to call it because there is no object of
the class is present.
- void : Java programming mandates that every method provide the return type. Java main
method doesn’t return anything, that’s why it’s return type is void. This has been done to keep
things simple because once the main method is finished executing, java program terminates.
So there is no point in returning anything, there is nothing that can be done for the returned
object by JVM.
- main : This is the name of java main method. It’s fixed and when we start a java program, it
looks for the main method.
- String args[] : Java main method accepts a single argument of type String array. This is also
called as java command line arguments.
Example:
CST 205 MODULE 2
CST 205 MODULE 2
Every variable in Java has a data type which tells the compiler what type of
variable it as and what type of data it is going to store.
It specifies the size and type of values.
Information is stored in a computer memory with different data types.
Whenever a variable is declared it becomes necessary to define a data type that
what will be the type of data that variable can hold.
Data Types available in Java are:
INTEGERS
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers.
CST 205 MODULE 2
long 64 bit
int 32 bit
Short 16 bit
Byte 8 bit
i) byte
The smallest integer type is byte. This is a signed 8-bit. Variables of type byte are
especially useful
ii) short
short is a signed 16-bit type. It is probably the least used Java type. Example
short s;
iii) int
The most commonly used integer type is int. In addition to other uses, variables of type
int are commonly employed to control loops and to index arrays. Example
int a;
iv) long
long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. Example
long a;
FLOATING-POINT
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. There are two kinds of floating-point types, float and
double, which represent single- and double-precision numbers, respectively.
CST 205 MODULE 2
float
The type float specifies a single-precision value that uses 32 bits of storage. Variables of
type float are useful when you need a fractional component, but don’t require a large degree of
precision.
Example: float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. When you
need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers,
double is the best choice.
Table 6: Floating Point Data Types
CHARACTERS
In Java, the data type used to store characters is char. Java uses Unicode to represent characters.
At the time of Java's creation, Unicode required 16 bits. Thus, in Java char is a 16- bit type.
Example: char letterA = 'A‘;
Table 7 : Character Data Type
BOOLEANS
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, as in the case of a
> b.
Example: boolean b;
Table 8 : boolean Data Type
JAVA OPERATORS
Java provides a rich set of operators’ environment. Java operators can be divided into following
categories:
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in
algebra.
Relation operators
The following table shows all relation operators supported by Java.
Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short,
char and byte
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value
are to be shifted. Both operands have the same precedence.
Example:
a = 0001000, b = 2
a << b = 0100000, a >> b = 0000010
Assignment Operators
Assignment operator supported by Java are as follows:
CST 205 MODULE 2
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result a+=b is same as
to left a=a+b
-= subtracts right operand from the left operand and assign a-=b is same as
the a=a-b
result to left operand
*= multiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b
%= calculate modulus using two operands and assign the result a%=b is same as
to left operand a=a%b
LITERALS IN JAVA
Literals is an identifier whose value is fixed and does not change during the execution of the program.
Types of Literals
CST 205 MODULE 2
Integer Literals
Integer Literals are numbers that has no fractional pars or exponent. It refers to the whole numbers. Integers
always begin with a digit or + or -.
We can specify integer constants in
Decimal
Octal
Hexadecimal
Decimal Integer Literals
It consists of any combination of digits taken from the set 0 to 9.
Example:
int a = 100; //Decimal Constant
int b = -145 // A negative decimal constant
int c = 065 // Leading zero specifies octal constant, not decimal
Unsigned Literals
We use either u or U suffix for Unsigned Constants and use either the l or L suffix. for Long constants
Example :
328u 0x7FFFFFL 0776745ul;
Floating-point Literals
Floating-point Literals are also called as real constants. The Floating Point contains decimal points and can
contain exponents. They are used to represent values that will have a fractional part and can be represented
in two forms – fractional form and exponent form.
In the fractional form, the fractional number contains the integer part and fractional part. A dot (.) is used to
separate the integer part and fractional part.
Example:
float x = 2.7f;
In the exponential form, the fractional number contains constants a mantissa and exponent. Mantissa contains
the value of the number and the exponent contains the magnitude of the number. The exponent, if any present,
specifies the magnitude of the number as a power of 10.
Example:
7.6: 23.46e0 // 23.46 x 100 = 23.46 x 1 = 23.46 23.46e1 // 23.46 x 101= 23.46 x10 = 234.6
Character Literals
Character Literals are specified as single character enclosed in pair of single quotation marks. Single
character constants are internally represented as ASCII codes.
char a=’c’;
String Literals
String Literals are treated as an array of char. By default, the compiler adds a special character called the
‘null character’ (‘\0’) at the end of the string to mark the end of the string.
Example:
String str = “good morning”;
Boolean literals
There are two Boolean literals
true represents a true Boolean value
false represents a false Boolean value
CST 205 MODULE 2
ARRAY
Arrays refer to a named list of final number 'n' of similar data elements. Each of the data
elements can be referenced respectively by a set of consecutive numbers, usually 0,1,2,3. ... n.
If the name of an array of 10 elements is ARY, then its elements will be referenced as shown
below:
1) one dimensional
2) two dimensional
3) multi dimensional
import [Link].*;
class OneDimensionalArray
CST 205 MODULE 2
int i=0;
int a[] = new int[10];
String n;
for(i=0;i< 5; i++)
{
n = [Link]();
a[i]=[Link](n);
}
[Link]("After the Inputting");
for(i=0; i< 5; i++)
{
[Link]("a[ "+i+"]"+"="+a[i]);
}
}
}
Two-Dimensional Arrays
The Two Dimensional array Elements are used when we Wants to Perform the Operation in Matrix Forms
the Two Dimensional arrays are used For Creating Matrix and Displaying array elements in the Form of
Rows and Columns The Total Elements of Arrays Will be Calculated by Multiplying the Elements of
Rows and Columns Like int a[3][3] i. e 9 Elements will be used by Array These are Called as Two
Dimensional Because they use two Brackets.
Eg:-
int a[][]=new int[3][3];
import [Link].*;
class TwoDimensionalArray
{
public static void main(String args[]) throws Exception
{
int a[ ][ ] = new int[2][3], sum = 0, r ,c;
String n;
[Link]("Enter the Elements");
BufferedReader obj=new BufferedReader(new InputStreamReader([Link]));
CST 205 MODULE 2
for(r=0;r< 2; r++)
{
for(c=0; c< 3; c++)
{
n = [Link]();
a[r][c]=[Link](n);
}
}
[Link]("After the Inputting");
STRINGS
Like an integer characters are also be in the Array. The Array of Characters are called as the Strings . we
Know that when Collection of Characters are called as String.
Here is the s is an array of type String Means it can accept only 10 Characters but if you will use String as
then:-
S is an object of Class String and now you can use any Method From String Class The Various String
Methods those are Reside in String Class are :-
CST 205 MODULE 2
VECTORS
The Vector class implements a growable array of objects. Like an array, it contains components that can be
accessed using an integer index. However, the size of a Vector can grow or shrink as needed to
accommodate adding and removing items after the Vector has been created.
Each vector tries to optimize storage management by maintaining a capacity and a capacity Increment.
The capacity is always at least as large as the vector size; it is usually larger because as components are
added to the vector, the vector's storage increases in chunks the size of capacity Increment. An application
can increase the capacity of a vector before inserting a large number of components; this reduces the amount
of incremental reallocation.
You can cast the primitive data types in two ways namely:
i) Widening (Implicit type casting)
CST 205 MODULE 2
Example
char ch = 'C';
int i = ch;
[Link](i);
}
Output
Integer value of the given character: 67
ii) Narrowing − Converting a higher data type to a lower data type is known as narrowing. In
this case the casting/conversion is not done automatically, you need to convert explicitly
using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this
case both datatypes need not be compatible with each other.
Example
import [Link];
CST 205 MODULE 2
int i = [Link]();
char ch = (char) i;
}
Output
Enter an integer value:
67
Character value of the given integer: C
I) SELECTION STATEMENTS
if Statement
o if statement
o if-else statement
o else-if statement
switch statement
II) LOOPING/ITERATION STATEMENTS
for
while
do while
CST 205 MODULE 2
1) Java if Statements
If statements in Java is used to control the program flow based on some
condition, it’s used to execute some statement code block if the expression is evaluated
to true, otherwise, it will get skipped. This is the simplest way to modify the control
flow of the program.
If statements in Java is used to control the program flow based on some
condition, it’s used to execute some statement code block if the expression is evaluated
to true, otherwise, it will get skipped. This is the simplest way to modify the control
flow of the program.
Syntax:
if(test_expression)
{
CST 205 MODULE 2
statement 1;
statement 2;
...
}
if(number1> number2)
[Link]("number1 is greater");
}
}
If else statements in Java is also used to control the program flow based on some
condition, only the difference is: it’s used to execute some statement code block if the
expression is evaluated to true, otherwise execute else statement code block.
Syntax:
if(test_expression)
{
//execute your code
CST 205 MODULE 2
}
else
{
//execute your code
}
Example:
public class Sample
{
public static void main(String args[])
{
int number1 = 80, number2 = 30;
if(number1> number2)
{
[Link]("number1 is greater");
}
else
{
[Link]("number2 is greater");
}
}
}
3) Java else-if Statements
else if statements in Java is like another if condition, it’s used in the program
when if statement having multiple decisions.
Syntax:
if(test_expression)
{
CST 205 MODULE 2
Example:
Syntax:
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
}
case 1:
[Link]("You chose One");
break;
case 2:
[Link]("You chose Two");
break;
case 3:
[Link]("You chose Three");
break;
case 4:
[Link]("You chose
Four"); break;
case 5:
[Link]("You chose Five");
break;
default:
[Link]("Invalid Choice. Enter a no between 1 and 5");
}
}
}
while loops
do while loops
CST 205 MODULE 2
for loops
Syntax:
while (condition)
{
statement(s);
Incrementation;
}
Example
:
Syntax:
do
{
statement(s);
}while( condition );
CST 205/281 MODULE 2
Example:
Java for loops is very similar to Java while loops in that it continues to
process a block of code until a statement becomes false, and everything is defined in
a single line.
Syntax:
break
continue
label
1) break statement
The break statement is used inside loop or switch statement. When compiler finds the
break statement inside a loop, compiler will abort the loop and continue to execute
statements followed by loop.
//[Link]
class Abc
{
public static void main(String args[])
{
int a=1;
while(a<=10)
{
if(a==5)
break;
[Link]("\n\tStatement : " + a);
a++;
}
CST 205 MODULE 2
Output :
Statement: 1.
Statement: 2.
Statement: 3.
Statement: 4.
End of Program.
The above program will abort the loop when the value of a reaches upto 5 and skip all
statements present in loop.
2) continue statement
The continue statement is also used inside loop. When compiler finds the continue
statement inside a loop, compiler will skip all the following statements in the loop and
resume the loop.
//[Link]
class xyz
{
public static void main(String args[])
{
int a=0;
CST 205 MODULE 2
while(a<10)
{
a++;
if(a==5)
continue;
[Link]("\n\tStatement " + a);
}
[Link]("\n\tEnd of Program.");
}
Output :
Statement 1.
Statement 2.
Statemnet 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.
The above program will skip all statements present in loop when the value of a reaches
upto 5 and continue the loop from 6 to 10.
3) Labelled Loop
Java does not support goto, it is reserved as a keyword just in case they wanted to add it
to a later version.
Unlike C/C++, Java does not have goto statement, but java supports label.
CST 205 MODULE 2
The only place where a label is useful in Java is right before nested loop statements.
We can specify label name with break to break out a specific outer loop.
According to nested loop, if we put break statement in inner loop, compiler will jump out
from inner loop and continue the outer loop again. What if we need to jump out from the
outer loop using break statement given inside inner loop? The answer is, we should
define lable along with colon(:) sign before loop.
In the case of nested loops to break and continue a particular loop we should go for labelled
break and continue statements. The Java labelled loops allows transferring to a particular
line or statement.
class Test
CST 205 MODULE 2
{
public static void main(String args[ ])
{
out: for(int i=1; i<=100; i++)
{
[Link]("outer");
for(int j=1; j<=100; j++)
{
[Link]("nested");
if(j==2)
{
// break; this will exit from inner for loop only
break out; // this will exit from both for loops
}
}
}
}
}
Output:-
outer
nested
nested
class Test
CST 205 MODULE 2
{
public static void main(String[] args)
{
out: for(int i=1; i<=100; i++)
{
[Link]("outer");
for(int j=1; j<=100; j++)
{
[Link]("nested");
if(j==2)
{
// continue; this will skip second(j==2) iteration
of inner for loop only
continue out; // this will skip current iteration of
both for loops
}
}
}
}
}
Output:- The outer for loop will iterate 100 times but the inner for loop will iterate twice
each time.
outer
nested
nested
outer
nested
nested
.
.
CST 205 MODULE 2
.
outer
nested
nested
INTRODUCTION TO OOP
CLASS FUNDAMENTALS
Everything in Java is defined in a class.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
class <class_name>
{
field;
method;
}
EXAMPLE:-
CST 205 MODULE 2
class Employee
String name;
String ssn;
String emailAddress;
int yearOfBirth;
If you recall, each class must be saved in a file that matches its name, for
example: [Link]
Note that in Java, Strings are also classes rather than being implemented as primitive
types.
Unlike local variables, the state variables (known as fields) of objects do not have to be
explicitly initialized. Primitive fields (such as yearOfBirth) are automatically set to
primitive defaults (0 in this case), whereas objects (name, ssn, emailAddress) are
automatically set to null — meaning that they do not point to any object.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
CST 205 MODULE 2
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
OBJECTS IN JAVA
Let us now look deep into what are objects. If we consider the real-world, we can find
many objects around us, cars, dogs, humans, etc. All these objects have a state and a
behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in
fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Consider this simple example of creating and using instances of the Employee class:
class Employee
String name;
String ssn;
String emailAddress;
int yearOfBirth;
};
[Link] = "John";
[Link] = "555-12-345";
[Link] = "john@[Link]";
CST 205 MODULE 2
[Link] = "Tom";
[Link] = "456-78-901";
[Link] = 1974;
Name: John
SSN: 555-12-345
Year Of Birth: 0
CST 205 MODULE 2
Name: Tom
SSN: 456-78-901
The following is the general form of a qualified name, which is also known as a long
name: [Link];
METHODS IN JAVA
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the [Link]() method, for example, the system
actually executes several statements in order to display a message on the console.
Creating Method
Syntax:-
modifier returnType nameOfMethod (Parameter List)
{
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
CST 205 MODULE 2
Example:-
public static int sum(int a, int b)
{
// body
}
Here,
public static − modifier
int − return type
sum − name of the method
a, b − formal parameters
int a, int b − list of parameters
Example:
public static int minimum(int a, int b)
{
int min;
if (a > b)
min = b;
else
min = a;
return min;
}
CST 205 MODULE 2
PARAMETER-LESS CONSTRUCTOR
PARAMETERIZED CONSTRUCTORS
-
.
CST 205 MODULE 2
CST 205 MODULE 2
Example
Using this with a class attribute (x):
int x;
this .x = x;
}
}
}
OUTPUT
The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). If you omit the keyword in the example above, the
output would be "0" instead of "5".
RECURSION IN JAVA
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
CST 205 MODULE 2
ACCESS CONTROL
Access control is a mechanism, an attribute of encapsulation which restricts the access of
certain members of a class to specific parts of a program. Access to members of a class can
be controlled using the access modifiers. There are four access modifiers in Java. They are:
1. public
2. protected
3. default
4. private
STATIC MEMBERS
In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
class Abc
{
static int a; // static member “a”
static String str; //static member “str”
static void disp() //This is a Static Method
{
[Link]("value of a is: "+a);
[Link]("Value of string str is: "+str);
}
}
class Xyz
{
public static void main(String args[])
{
disp();
}
}
Output:
value of a is: 0
Value of string str is: null
…………………………………………………………………………………
CST 205 MODULE 2
There is a final variable “a”, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
class xyz
{
final int a=3; //final variable
void run() Output:
{
a=10;
Compile Time Error
}
public static void main (String args[])
{
xyz obj=new xyz();
[Link]();
} }
CST 205 MODULE 2
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members
and methods.
class Outer
{
//code
class Inner
{
//code
}
}
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes
There are two types of nested classes non-static and static nested [Link] non-static
nested classes are also known as inner classes.
CST 205 MODULE 2
COMMAND-LINE ARGUMENT
A command-line argument is an information that directly follows the program's name
on the command line when it is executed. To access the command-line arguments inside
a Java program is quite easy. They are stored as strings in the String array passed to
main( ).
Example
The following program displays all of the command-line arguments that it is called with
-
public class Abc
{
public static void main(String args[ ])
{
for(int i = 0; i<[Link]; i++)
{
[Link]("args[" + i + "]: " + args[i]);
}
}
}
Try executing this program as shown here -
args[0]: I
args[1]: am
args[2]: a
args[3]: BTech
args[4]: student
args[5]: 100
CST 205 MODULE 2
args[6]: -500
--------------------------------------------------------------------------------------
VARIABLE LENGTH ARGUMENTS
In JDK 5, Java has included a feature that simplifies the creation of methods that need to
take a variable number of arguments. This feature is called varargs and it is short-form for
variable-length arguments. A method that takes a variable number of arguments is a varargs
method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using
overloaded method(one for each) and another put the arguments into an array, and then
pass this array to the method. Both of them are potentially error-prone and require more
code. The varargs feature offers a simpler, better option.
Syntax :
A variable-length argument is specified by three periods(…). For Example,
Output:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
The … syntax tells the compiler that varargs has been used and these arguments
should be stored in the array referred to by a.
The variable a is operated on as an array. In this case, we have defined the data type
of a as int. So it can take only integer values. The number of arguments can be found
out using [Link], the way we find the length of an array in Java.
INHERITANCE
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.
Single Level inheritance - A class inherits properties from a single class. For example,
Class B inherits Class A.
Multilevel inheritance - A class inherits properties from a class which again has inherits
properties
Hierarchical inheritance - Multiple classes inherits properties from a single class. For
example, Class B inherits Class A and Class C inherits Class A.
(NB: Multiple inheritance (derivation of a class from more than one parent class) is not
supported in java, instead interfaces are used in java)
CST 205 MODULE 2
CST 205 MODULE 2
CST 205 MODULE 2
OUTPUT
-
Hello
Child class
KEYWORD “SUPER”
The super keyword in java is a reference variable that is used to refer parent class objects. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:
This scenario occurs when a derived class and base class has same data members. In that case
there is a possibility of ambiguity for the JVM. We can understand it more clearly using this
code snippet:
void display()
{
/* print x of base class (A) */
[Link]("Value of x in class A: " + super.x);
}
}
class Abc
CST 205 MODULE 2
{
public static void main(String args[ ])
{
B obj = new B();
[Link]();
}
}
Output:
Value of x in class A: 10
In the above example, both base class and subclass have a member “x”. We could access “x”of base class
in subclass using super keyword.
2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we use super
keyword. This code snippet helps to understand the said usage of super keyword.
class A
{
void message()
{
[Link]("CLASS A");
}
}
class B extends A
{
void message()
{
[Link]("CLASS B");
}
{
message(); // will invoke or call current class message() method
class Abc
{
CST 205 MODULE 2
public static void main(String args[])
{
B obj = new B();
}
}
Output:
CLASS B
CLASS A
In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of super keyword, message() of superclass could also be
invoked.
super keyword can also be used to access the parent class constructor. One more important thing
is that, ‘’super’ can call both parametric as well as non parametric constructors depending upon
the situation. Following is the code snippet to explain the above concept:
class A
{
A( )
{
[Link]("class A Constructor");
}
}
[Link]("class B Constructor");
}
}
class Test
{
public static void main(String[] args)
{
CST 205 MODULE 2
B obj = new B( );
}
}
Output:
Class A Constructor
Class B Constructor
In the above example we have called the superclass constructor using keyword ‘super’ via subclass
constructor.
PROTECTED MEMBERS
Protected keyword in Java refers to one of its access modifiers. The methods or data
members declared as protected can be accessed from:
Within the same class.
Subclasses of same packages.
Different classes of same packages.
Subclasses of different packages.
needed to be applied.
CST 205 MODULE 2
2. Protecting a constructor prevents the users from creating the instance of the class,
METHOD OVERRIDING
CST 205 MODULE 2
OUTPUT
Method A
Method A in class B
Method B
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as
upcasting.
ABSTRACT CLASS
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of
the method.
EXAMPLE:-
CST 205 MODULE 2
ABSTRACT METHOD
A method which is declared as abstract and does not have implementation is known as
an abstract method.
class abc
{
public static void main (string args[])
{
C obj = new C ( );
obj.amethod1( );
}
}
CST 205 MODULE 2
class Parent
{
/* Creation of final variable pa of string type i.e
the value of this variable is fixed throughout all
the derived classes or not overidden*/
class Test
{
public static void main(String args [ ])
{
Parent p = new Parent();
// Calling a variable pa by parent object
[Link]([Link]);
CST 205 MODULE 2
Output
class Parent
{
/* Creation of final method parent of void type i.e
the implementation of this method is fixed throughout
all the derived classes or not overidden*/
final void parent( )
{
[Link]("Hello , we are in parent method");
}
}
class Child extends Parent
{
class Test
{
public static void main(String args[ ])
{
Parent p = new Parent();
// Calling a method parent() by parent object
[Link]();
Output
- - end
1
CST 205, S3, CSE MODULE 3
MODULE 3
PACKAGES AND INTERFACES
DEFINING PACKAGES
A package is a mechanism to group the similar type of classes, interfaces and sub-packages and
provide access control. It organizes classes into single unit.
In Java already many predefined packages are available, used while programming.
For example: [Link], [Link], [Link] etc.
Advantages of Packages
Packages provide code reusability, because a package has group of classes.
It helps in resolving naming collision when multiple packages have classes with the same name.
Package also provides the hiding of class facility. Thus other programs cannot use the classes
from hidden package.
Access limitation can be applied with the help of packages.
One package can be defined in another package.
Types of Packages
There are two types of packages available in Java.
1. Built-in packages
Built-in packages are already defined in java API. For example: [Link], [Link], java,lang,
[Link], [Link], [Link], etc.
2. User defined packages
The package we create according to our need is called user defined package.
Creating a Package
We can create our own package by creating our own classes and interfaces together. The package
statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}
// [Link]
package p1;
class Abc
{
public void disp()
{
[Link]("Method disp..");
}
}
It can be compiled by:
Syntax:
javac –d directoryjavaFileName
Eg:-
javac –d [Link]
It can be run by:
Java [Link]
CLASSPATH
CLASSPATH is an environment variable which is used by Application ClassLoader to locate and load
the .class files. The CLASSPATH defines the path, to find third-party and user-defined classes that
are not extensions or part of Java platform. Include all the directories which contain .class files and
JAR files when setting the CLASSPATH.
o You need to load a class that is not present in the current directory or any sub-directories.
o You need to load a class that is not in a location specified by the extensions mechanism.
The CLASSPATH depends on what you are setting the CLASSPATH. The CLASSPATH has a
directory name or file name at the end. The following points describe what should be the end of the
CLASSPATH.
o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of the zip or JAR file.
o If class files placed in an unnamed package, the CLASSPATH ends with the directory that contains the
class files.
o If class files placed in a named package, the CLASSPATH ends with the directory that contains the root
package in the full package name, that is the first package in the full package name.
The default value of CLASSPATH is a dot (.). It means the only current directory searched. The default value of
CLASSPATH overrides when you set the CLASSPATH variable or using the -classpath command (for short -cp).
Put a dot (.) in the new setting if you want to include the current directory in the search path.
If CLASSPATH finds a class file which is present in the current directory, then it will load the class and use it,
irrespective of the same name class presents in another directory which is also included in the CLASSPATH.
If you want to set multiple classpaths, then you need to separate each CLASSPATH by a semicolon (;).
The third-party applications (MySQL and Oracle) that use the JVM can modify the CLASSPATH environment
variable to include the libraries they use. The classes can be stored in directories or archives files. The classes of the
Java platform are stored in [Link].
There are two ways to ways to set CLASSPATH: through Command Prompt or by setting Environment Variable.
Step 1: Click on the Windows button and choose Control Panel. Select System.
Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a semicolon (;) at
the end. Paste the Path of MySQL-Connector [Link] file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable name as
CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector [Link];.;
The three main access modifiers private, public and protected provides a range of ways to access
required by these categories.
Simply remember, private cannot be seen outside of its class, public can be access from anywhere,
and protected can be accessible in subclass only in the hierarchy.
A class can have only two access modifier, one is default and another is public. If the class has
default access then it can only be accessed within the same package by any other code. But if the
class has public access then it can be access from any where by any other code.
INTERFACES
IMPLEMENTING INTERFACES
SAMPLE PROGRAM
The methods used for streaming output are defined in the PrintStream class. The methods used
for writing console output are print(), println() and write().
Both print() and println() methods are used to direct the output to the console. These methods are
defined in the PrintStream class and are widely used. Both these methods are used with the help
of the [Link] stream.
The basic differences between print() and println() methods are as follows:
print() method displays the string in the same line whereas println() method outputs a newline
character after its execution.
print() method is used for directing output to console only whereas println() method is used for
directing output to not only console but other sources also.
Now, let us understand it in a better way with the help of some examples.
Output:
Let us take the same example above and use println() method in place of print() method.
Output:
Both these functions work best for output of strings as well. Let us have a look at another
example.
In addition, if you want to display the value of any particular variable used in the program, then
you have to append the variable name along with the string with a plus (+) symbol.
Output:
class writeEg
{
public static void main(String args[])
{
int a, b;
a = 'Q';
b = 65;
[Link](a);
[Link]('\n');
[Link](b);
[Link]('\n');
}
}
Output:
PrintWriter class
It implements all of the print methods found in PrintStream. It does not contain methods for
writing raw bytes, for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of
the println, printf, or format methods is invoked, rather than whenever a newline character
happens to be output. These methods use the platform’s own notion of line separator rather than
the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The
client may inquire as to whether any errors have occurred by invoking checkError().
Constructor and Description
PrintWriter(File file) : Creates a new PrintWriter, without automatic line flushing, with
the specified file.
PrintWriter(File file, String csn) : Creates a new PrintWriter, without automatic line
flushing, with the specified file and charset.
Methods:
PrintWriter append(char c) : Appends the specified character to this writer
PrintWriter append(CharSequence csq, int start, int end): Appends the specified
character sequence to this writer.
PrintWriter append(CharSequence csq) : Appends a subsequence of the specified
character sequence to this writer.
boolean checkError(): Flushes the stream and checks its error state.
protected void clearError() : Clears the internal error state of this stream.
void close() : Closes the stream and releases any system resources associated with it.
PrintWriter format(Locale l, String format, Object… args): Writes a formatted string
to this writer using the specified format string and arguments.
PrintWriter format(String format, Object… args): Writes a formatted string to this
writer using the specified format string and arguments.
void print(boolean b): Prints a boolean value.
void print(char c): Prints a character.
void print(char[] s): Prints an array of characters.
void print(double d) :Prints a double-precision floating-point number.
void print(float f): Prints a floating-point number.
void print(int i): Prints an integer.
void print(long l): Prints a long integer.
void print(Object obj) :Prints an object.
void print(String s): Prints a string.
WORKING WITH FILES
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.
The File class from the [Link] package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory
name:
Example
If you don't know what a package is, read our Java Packages Tutorial.
The File class has many useful methods for creating and getting information about files.
For example:
Method Type Description
1. Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already exists.
Example:-
2. Read a File
In the following example, we use the Scanner class to read the contents of the text file
Example:-
Example:-
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception
occurs program execution gets terminated. In such cases we get a system generated error message. The
good thing about exceptions is that they can be handled in Java. By handling the exceptions we can
provide a meaningful message to the user about the issue rather than a system generated message, which
may not be understandable to a user.
Exception Handling
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the system
generated exception below:
Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For
example, if a program has bunch of statements and an exception occurs mid way after executing certain
statements then the statements after the exception will not execute and the program will terminate
abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
Exceptions are events that occurs in the code. A programmer can handle such conditions and take
necessary corrective actions. Few examples:
Keyword Description
Try The "try" keyword is used to specify a block where we should place exception code. The try block must be follo
finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use ca
followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may oc
method. It is always used with method signature.
TYPES OF EXCEPTIONS
There are two types of exceptions in Java:
1) Checked exceptions
2) Unchecked exceptions
1. CHECKED EXCEPTIONS
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not.
If these exceptions are not handled/declared in the program, you will get compilation error.
For example, SQLException, IOException, ClassNotFoundException etc.
for example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.
Example: A prg with name FilenotFound_Demo.java
import [Link];
import [Link];
If you try to compile the above program, you will get the following exceptions.
Output
Compile the prg as
javac FilenotFound_Demo.java
The error appeared as:
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or
declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you can observe
that the compiler notifies to handle IOException, along with FileNotFoundException.
2. UNCHECKED EXCEPTIONS
An unchecked exception is an exception that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Types of runtime exceptions
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size
of the string
For example, if you have declared an array of size 5 in your program, and trying to call the 6 th element of
the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Example
public class Unchecked_Demo
{
If you compile and execute the above program, you will get the following exception.
Output
Exception in thread "main" [Link]: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
1. ArithmeticException
2. NullPointerException
{
try
{
String a = null; //null value
[Link]([Link](0));
}
catch(NullPointerException e)
{
[Link]("NullPointerException..");
}
}
}
Output:
NullPointerException..
3. StringIndexOutOfBoundException
4. FileNotFoundException
5. NumberFormatException
[Link](num);
}
catch(NumberFormatException e)
{
[Link]("Number format exception");
}
}
}
Output:
Number format exception
6. ArrayIndexOutOfBounds Exception
catch(Exception e)
{
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that can handle all. This is
because in generic exception handler you can display a message but you are not sure for which type of
exception it may trigger so it will display the same message for all the exceptions and user may not be able
to understand which exception occurred. Thats the reason you should place is at the end of all the specific
exception catch blocks
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception, which is an advanced topic and I have covered it in separate
tutorials: user defined exception, throws keyword, throw vs throws.
catch(ArithmeticException e)
{
[Link]("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e)
{
[Link]("Warning: Some Other exception");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially when
an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the
first place, just after try block then in case of any exception this block will execute as it can handle
all exceptions. This catch block should be placed at the last to avoid such situations.
catch(ArithmeticException e3)
{
[Link]("Arithmetic Exception");
[Link]("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4)
{
[Link]("ArrayIndexOutOfBoundsException");
[Link]("Inside parent try catch block");
}
catch(Exception e5)
{
[Link]("Exception");
[Link]("Inside parent try catch block");
}
[Link]("Next statement..");
} // main close
} //class nest close
Output:
Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..
throw IN EXCEPTION
The throw keyword is used to create a custom error.
The throw statement is used together with an exception type. There are many exception
types available in
Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsExceptio
n, SecurityException, etc.
The exception type is often used together with a custom method, like in the example
shown below.
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
throws IN EXCEPTION
The throws keyword indicates what exception type may be thrown by a method.
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class MyClass
{
static void checkAge(int age) throws ArithmeticException
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
}
else
{
[Link]("Access granted - You are old enough!");
}
}
OUTPUT
Throw throws
Used to throw an exception for a method Used to indicate what exception type may
method
Syntax: Syntax:
throw is followed by an object (new type) throws is followed by a class
used inside the method and used with the method signatur
Here we can see that the exception occurred in try block which has been handled in catch
block, after that finally block got executed.
class Example
{
public static void main(String args[])
{
try
{
int num=121/0;
[Link](num);
}
catch(ArithmeticException e)
{
[Link]("Number should not be divided by zero");
}
finally
{
[Link]("This is finally block");
}
[Link]("Out of try-catch-finally");
}
}
Output:
Java
Module 4 - Advanced features of Java
(Part 3)
1
Java Library
❑ Collections framework
❑ Collections overview
3
Figure 1 Interfaces and Classes in the Java Collections Framework
• The Java Collections Framework standardizes the way
in which groups of objects are handled by our
programs.
classes.
• generics
• autoboxing/unboxing, and
hold.
• Collection extends the Iterable interface.
– This means that all collections can be cycled through by use of
the for-each style for loop.
Collection declares the core methods that all collections will have.
18
• Herbert Schildt, Java: The Complete Reference, 8/e,
Tata McGraw Hill, 2011.
19
CS205 Object Oriented Programming in
Java
Module 4 - Advanced features of Java
(Part 4)
1
Topics
Java Library
❑ Collections framework
List Interface
Collections Class
ArrayList Class
List Interface
List Interface(contd.)
8
ArrayList Class
class ArrayList<E>
– Here, E specifies the type of objects that the list will hold.
9
ArrayList Class(contd.)
import [Link].*;
class ArrayListDemo
{
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
[Link]("Initial size=" +[Link]());
13
void trimToSize( )
Obtaining an Array from an ArrayList
– This is needed
import [Link].*;
class ArrayListToArray {
public static void main(String args[]) {
ArrayList<Integer> al = new ArrayList<Integer>();
[Link]("Conte
[Link](1); nts of al: " + al);
[Link](2); Integer arr[] = new
[Link](3); Integer[[Link]()]; arr =
[Link](arr);
int sum = 0;
[Link](4);
6
CST205ObjectOrientedProgrammingusingJava (As
per KTU 2019 Syllabus)
Module4
MultithreadedProgramming
Definitionofthread
Athreadisasinglesequentialflowof
control within a program.
Therealexcitementsurrounding
threads is not about a single
sequential thread.
Rather,it'sabouttheuseofmultiple
threads running at the same time
and performing different tasks in a
single program
Threadsarelightweightprocesses
within a process.
Asinglethreadedprogram
begin
body
end
4
AMultithreadedProgram
start start
Threadsmayswitchorexchangedata/results
Multiple Clients Concurrently
Client1Process ServerProcess
Server
Threads
Client2Process
6
Web/InternetApplications:
ServingManyUsersSimultaneously
PC client
Internet
Server LocalAreaNetwork
PDA
7
Multithreadedprogramming
● Javaisamultithreadedprogramminglanguage
● Athreadisanindependentpathofexecutionwithinaprogram,mostofthe
programs are single threaded
● Multithreadingreferstotwoormoretasksexecutingconcurrentlywithinasingle
program.
● Manythreadscanrunconcurrentlywithina program.
● [Link] class.
● AJavaprogramcanhavemanythreads,andthesethreadscanrunconcurrently, either
asynchronously or synchronously.
AdvantagesofJavaMultithreading
■ Itdoesn'tblocktheuserbecausethreadsareindependent and
you can perform multiple operations at same time.
■ Youcanperformmanyoperationstogethersoitsaves time.
■ Threadsareindependentsoitdoesn'taffectotherthreads if
exception occur in a single thread.
■
■ Note:Atatimeonethreadisexecutedonly.
JavaThreadSupport
■ JavahasbuiltinthreadsupportforMultithreading
■ Synchronization
■ ThreadScheduling
■ Inter-ThreadCommunication:
■ currentThread start setPriority
■ yield run getPriority
■ sleep stop suspend
■ resume
■ JavaGarbageCollectorisalow-prioritythread.
10
LifeCycleofaThread
Statesofthethreadlifecycle
1. Newborn:Whenathreadiscreated(bynewstatement)butnotyettorun,itis called in
Newborn state. In this state, the local data members are allocated and
initialized.
2. Runnable : The Runnable state means that a thread is ready to run and is
awaitingforthecontroloftheprocessor,orinotherwords,threadsareinthis state in
a queue and wait their turns to be executed.
3. Running:Runningmeansthatthethreadhascontroloftheprocessor,itscode is
currently being executed and thread will continue in this state until it get
preempted by a higher priority thread, or until it relinquishes control.
4. Blocked :Athread is Blocked means that it is being prevented from the
Runnable(orRunning)stateandiswaitingforsomeeventinorderforitto reenter
the scheduling queue.
5. Terminated(Dead):AthreadisDeadwhenitfinishesitsexecutionorisstopped
(killed)byanotherthread
Transitionsfromrunningstate
ARunningThreadtransittooneofthenon-runnablestates,dependinguponthe
circumstances.
• Sleeping:TheThreadsleepsforthespecifiedamountoftime.
• BlockedforI/O:TheThreadwaitsforablockingoperationtocomplete.
• Blockedforjoincompletion:TheThreadwaitsforcompletionofanotherThread.
• Waitingfornotification:TheThreadwaitsfornotificationanotherThread.
• Blockedforlockacquisition:TheThreadwaitstoacquirethelockofanobject.
JVMexecutestheThread,basedontheirpriorityand scheduling.
ThreadPriorities
● EveryJavathreadhasaprioritythathelpstheoperatingsystemdetermine the
order in which threads are scheduled.
● JavathreadprioritiesareintherangebetweenMIN_PRIORITY(aconstantof 1)
and MAX_PRIORITY (a constant of 10).
● DefaultthreadpriorityisNORM_PRIORITY(aconstantof5).
● Threadswithhigherpriorityaremoreimportanttoaprogramandshouldbe
allocated processor time before lower-priority threads.
● Threadprioritiescannotguaranteetheorderinwhichthreadsexecuteand are
very much platform dependent.
MainThread
● WhenaJavaprogramstartsup,onethreadbeginsrunningimmediately.
● Thisisusuallycalledthemainthreadofourprogram,becauseitistheone that is
executed when our program begins.
● Itisthethreadfromwhichother“child”threadswillbe spawned.
● Often,itmustbethelastthreadtofinishexecutionbecauseitperforms
various shutdown actions
● Themainthreadiscreatedautomaticallywhenourprogramis started.
● Tocontrolitwemustobtainareferencetoitbycallingthemethod
currentThread()whichispresentinThreadclass.
● Thismethodreturnsareferencetothethreadonwhichitiscalled.
● ThedefaultpriorityofMainthreadis5andforallremaininguserthreads priority
will be inherited from parent to child.
Flowdiagramofmain thread
ThreadcreationinJava
Therearetwowaystocreateathread:
1. ByextendingThreadclass[[Link]]
2. ByimplementingRunnableinterface.[[Link]]
Whatistheneedforthisdual option?
Remember-Javadoesnotsupportmultipleinheritance
ThreadcreationinJava
[Link]
[Link]
interface
(objectsarethreads) (objectswithrun()body)
[a] [b]
18
CreateaThreadbyExtendingaThreadClass
Providesmoreflexibilityinhandlingmultiplethreadscreatedusingavailable methods in
Thread class.
CreateanewclassthatextendsThreadclassusingthefollowingsteps.
● Step1-Youwillneedtooverriderun()methodavailableinThreadclass.
● Thismethodprovidesanentrypointforthe thread
● Syntaxofrun()method−publicvoidrun()
● Step2-OnceThreadobjectiscreated,youcanstartitbycallingstart()
method,whichexecutesacalltorun() method.
● Syntaxofstart()method−voidstart();
Threadclass
Threadclassprovideconstructorsandmethodstocreateandperformoperations on a
thread.
• ThreadclassextendsObjectclassandimplementsRunnableinterface.
CommonlyusedConstructorsofThread class:
• Thread()
• Thread(Stringname)
• Thread(Runnabler)
• Thread(Runnabler,Stringname)
Note:Stringargumentistoassignathreadname.
Threadclassmethods
ThreadMethods-Followingisthelistofimportantmethodsavailableinthe Thread class.
• publicvoidrun():isusedtoperformactionfora thread.
• publicvoidstart():startstheexecutionofthethread. JVMcallstherun()method on
the thread.
• publicstaticvoidsleep(longmilliseconds) :Causesthecurrentlyexecuting
thread to sleep for the specified number of milliseconds.
• publicvoidjoin():waitsforathreadtodie.
• publicintgetPriority():returnsthepriorityofthe thread.
• publicintsetPriority(intpriority):changesthepriorityofthethread.
Threadclassmethods
• publicStringgetName():returnsthenameofthethread.
• publicThreadcurrentThread():returnsthereferenceofcurrentlyexecutingthread.
• publicint getId():returnstheidofthe thread.
• [Link]():returnsthestateofthethread.
• publicbooleanisAlive():testsifthethreadisalive.
• publicvoidsuspend():isusedtosuspendthethread(depricated).
• publicvoidresume():isusedtoresumethesuspendedthread
• publicvoidstop():isusedtostopthe thread(depricated).
• public boolean isDaemon() : tests if the thread is a daemon thread. Daemon
thread is a low priority thread (in context of JVM) that runs in background to perform
tasks suchasgarbagecollection(gc)etc.,theydonotpreventtheJVMfromexiting(evenif
the daemon thread itself is running) when all the user threads (non-daemon threads)
finish their execution
[Link]()&[Link]()
● InJava’smultithreadingconcept,start()andrun()arethetwomostimportant
methods.
● Whenaprogramcallsthestart()method,anewthreadiscreatedandthen the
run() method is executed.
● Butifwedirectlycalltherun()methodthennonewthreadwillbecreatedand run()
method will be executed as a normal method call on the current calling
thread itself and no multithreading will take place.
[Link]()&[Link]()
[Link]()&[Link]()
[Link]()&[Link]()
ByImplementingaRunnableInterface
IftheclassisintendedtobeexecutedasathreadthenimplementRunnable interface.
Step1-implementarun()[Link] provides
an entry point for the thread. [ public void run( ) ]
Step2-Asasecondstep,youwill instantiateaThreadobjectusingthefollowing
constructor−Thread(RunnablethreadObj,StringthreadName);
- threadObjisaninstanceofaclassthatimplementstheRunnableinterface.
- threadNameisthenamegiventothenewthread[optional].
class
■ CreateaclassbyextendingThreadclassandoverride
run()method:
classMyThreadextendsThread
{
publicvoidrun()
{
//threadbodyofexecution
}
}
■ Createathread:
MyThreadthr1=newMyThread();
■ StartExecutionofthreads:
[Link]();
■ CreateandExecute:
new
An example
classMyThreadextendsThread{
public void run() {
[Link]("thisthreadisrunning...");
classThreadEx1{
publicstaticvoidmain(String[]args){
MyThread t = new MyThread();
[Link]();
}
31
2nd method: Threads by
implementingRunnableinterface
■ CreateaclassthatimplementstheinterfaceRunnableand
override run() method:
classMyThreadimplementsRunnable
{
.....
publicvoidrun()
{
//threadbodyofexecution
}
}
■ CreatingObject:
MyThreadmyObject=newMyThread();
■ CreatingThreadObject:
Threadthr1=newThread(myObject);
■ StartExecution:
[Link]();
32
Anexample
classMyThreadimplementsRunnable{ public
void run() {
[Link]("thisthreadisrunning...");
classThreadEx2{
publicstaticvoidmain(String[]args){
Threadt=newThread(newMyThread());
[Link]();
}
33
CreatingMultipleThreads
● Thiscanbedonebycreatingtheinstancesoftheclasseswhichareeither
extending Thread class or implementing runnable interface.
● TODO:Runasimpleprogramwhichcreatesmultiplethreadsandidentifythe
maximum number of threads possible from your program.
● Joinmethodcanjointhenewlycreatedthreadwithmainthread
Synchronization
Whenwestarttwoormorethreadswithinaprogram,theremaybeasituation when
multiple threads try to access the same resource and finally they can produce
unforeseen result due to concurrency issues.
• For example, if multiple threads try to write within a same file then they may
corruptthedatabecauseoneofthethreadscanoverridedataorwhileonethread is
opening the same file at the same time another thread might be closing the same
file.
• Sothereisaneedtosynchronizetheactionofmultiplethreadsandmakesure that
only one thread can access the resource at a given point in time.
Followingisthegeneralformofthesynchronizedstatement:
synchronized(objectidentifier)
{
//Accesssharedvariablesandothershared resources
}
Synchronization
● Thekeywordsynchronizedisusedbywhichmethod(s)orblockof
statements can be made protected from the simultaneous access.
Synchronization
● Whentwoormorethreadswantto(W)accessasharedresource,ensureonly one
thread has access to that resource at a time to avoid raise condition
● Thekeywordsynchronizedisusedbywhichmethod(s)orblockof
statements can be made protected from the simultaneous access.
● The entire time that a thread is inside of a synchronized method, all other
threadsthattrytocallanyothersynchronizedmethodonthesameinstance have
to wait.
● InJava,synchronizedkeywordcausesaperformancecost.
● AsynchronizedmethodinJavaisveryslowandcandegradeperformance.
● So we must use synchronization keyword in java when it is necessary else,
weshoulduseJavasynchronizedblockthatisusedforsynchronizingcritical
section only.
SuspendingThread
• Thesuspend()methodofthreadclassputsthethreadfromrunningtowaitingstate.
• Thismethodisusedifyouwanttostopthethreadexecutionandstartitagainwhen a
certain event occurs.
• Thismethodallowsathreadtotemporarilycease execution.
• Thesuspendedthreadcanberesumedusingtheresume()method.
Syntax
publicfinalvoidsuspend()
SuspendingThread
ResumingThread
• Theresume()methodofthreadclassisonlyusedwithsuspend()method.
• Thismethodisusedtoresumeathreadwhichwassuspendedusingsuspend()
method.
• Thismethodallowsthesuspendedthreadtostartagain.
Syntax
publicfinalvoidresume(
ResumingThread
TerminatingaThread
• Thestop()methodofthreadclassterminatesthethreadexecution.
• Onceathreadisstopped,itcannotberestartedbystart()method.
Syntax
publicfinalvoidstop()
publicfinalvoidstop(Throwableobj)
TerminatingaThread
Inter-threadCommunication
Thefirstisthrough [Link] memory
space.
Thesecondwayforthreadstocommunicateisbyusing threadcontrolmethods.
● suspend():Athreadcansuspenditselfandwaittillanotherthreadresumeit.
● resume():Athreadcanwakeupotherwaitingthread
● join():Thismethodcanbeusedforthecallerthreadtowaitforthecompletionofcalledthread.
char[]ch={‘h','a',‘i',‘j',‘a',‘v',‘a'}; String
s=new String(ch);
issameas:
Strings= “haijava";
• JavaStringclassprovidesalotofmethodstoperformoperationsonstringssuchas compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Createastringobject
TherearetwowaystocreateStringobject:
• Bystringliteral
• Bynew keyword
1) StringLiteral
JavaStringliteraliscreatedbyusingdoublequotes.
ForExample:
Strings="welcome";
• Eachtimeyoucreateastringliteral,theJVMchecksthe"stringconstantpool"first.
• Ifthestringalreadyexistsinthepool,areferencetothepooledinstanceisreturned.
• Ifthestringdoesn'texistinthepool,anewstringinstanceiscreatedandplacedinthepool. For
example:
Strings1="Hello";
Strings2="Hello";//Itdoesn'tcreateanewinstance
Createastringobject
Strings1="Hello";
Strings2="Hello";//Itdoesn'tcreateanewinstance
• Intheaboveexample,onlyoneobjectwillbecreated.
• Firstly, JVM will not find any string object with the
value"Hello"instringconstantpool,thatiswhyitwillcreateanewO
bject.
• Afterthatitwillfindthestringwiththevalue"Hello"inthe
Strings=newString("Welcome");//createstwoobjects
andonereferencevariable
• Insuchcase,JVMwillcreateanewstringobjectinnormal
(non-pool)inheapmemory,andtheliteral"Welcome"willbeplaced in the
string constant pool.
• Thevariableswillrefertotheobjectinaheap(non-pool).
Createastringobject
2. Byusingnewkeyword
Strings=newString("Welcome");//createstwoobjects
andonereferencevariable
• Insuchcase,JVMwillcreateanewstringobjectinnormal
(non-pool)inheapmemory,andtheliteral"Welcome"willbeplaced in the
string constant pool.
• Thevariableswillrefertotheobjectinaheap(non-pool).
Stringsample
STRINGCONSTRUCTORS
• ThestringclasssupportsseveraltypesofconstructorsinJavaAPIs.
The most commonly used constructors of String class are as follows:
1. String():TocreateanemptyString,[Link]: String
s = new String();
• Itwillcreateastringobjectintheheapareawithnovalue
2. String(Stringstr):Itwillcreateastringobjectintheheapareaandstoresthegiven value
in it. For example:
Strings2=newString(“HelloJava“);
Now,theobjectcontainsHelloJava.
3. String(charchars[]):Itwillcreateastringobjectandstoresthearrayofcharactersin it. For
example:
charchars[]={‘a’,‘b’,‘c’,‘d’};
String s3 = new String(chars);
Theobjectreferencevariables3containstheaddressofthevaluestoredintheheaparea.
STRINGCONSTRUCTORS
4. String(charchars[],intstartIndex,intcount)
• Itwillcreateandinitializesastringobjectwithasubrangeofacharacterarray.
• TheargumentstartIndexspecifiestheindexatwhichthesubrangebeginsandcount
specifies the number of characters to be copied.
Forexample:
• Internalimplementat
ion public int length()
{return [Link];
}
Signature-Thesignatureofthestringlength()methodisgivenbelow
:
publicint length()
STRINGLENGTH
STRINGCOMPARISON
• Wecancomparestringinjavaonthebasisofcontentandreference
• Therearethreewaystocomparestringinjava:
Byequals()method By
= = operator
BycompareTo()method
1. Stringcomparebyequals()method
• TheStringequals()methodcomparestheoriginalcontentofthestring.
• It compares values of string for equality. String class provides two
methodspublicbooleanequals(Objectanother)comparesthisstringtothespecifiedobj
ect. public boolean equalsIgnoreCase(String another) compares this
Stringtoanotherstring,ignoringcase.
STRINGCOMPARISON
STRINGCOMPARISON
2. Stringcompareby==operator
• The==operatorcomparesreferencesnot values.
STRINGCOMPARISON
3. StringcomparebycompareTo()method
• TheStringcompareTo()methodcomparesvalueslexicographically
and returns an integer value that describes if first string is less than,
equal to or greater than second string.
[Link]: s1 ==
s2 : 0
s1 > s2 : positive value
s1<s2:negativevalue
STRINGSEARCHING
Stringcontains()
• Thejavastringcontains()methodsearchesthesequenceofcharactersinthisstring.
• Itreturnstrueifsequenceofcharvaluesarefoundinthisstringotherwisereturnsfalse.
Signature
• Thesignatureofstringcontains()methodisgivenbelow:
publicbooleancontains(CharSequencesequence)
Internalimplementation
publicbooleancontains(CharSequences)
{
returnindexOf([Link]())>-1;
}
STRINGSEARCHING
publicbooleancontains(CharSequencesequence)
STRINGSEARCHING
publicbooleancontains(CharSequencesequence)
STRINGSEARCHING
Thecontains()methodsearchescasesensitivecharsequence.
Iftheargumentisnotcasesensitive,[Link]'sseeanexamplebelow.
CHARACTEREXTRACTION
StringcharAt()
• ThejavastringcharAt()methodreturnsacharvalueatthegivenindexnumber.
• Theindexnumberstartsfrom0andgoeston-1,wherenislengthofthe string.
• ItreturnsStringIndexOutOfBoundsExceptionifgivenindexnumberisgreaterthanor
equal to this string length or a negative number.
• ThesignatureofstringcharAt()methodisgivenbelow:
publiccharcharAt(intindex)
StringIndexOutOfBoundsExceptionwithcharAt()
• Let'sseetheexampleofcharAt()methodwherewearepassinggreaterindexvalue.
• Insuchcase,itthrowsStringIndexOutOfBoundsExceptionatruntime.
charAt()example
• Thisexamplecountsthefrequencyof‘t’ingiven string
MODIFYSTRINGS
• Thejavastringreplace()methodreturnsastringreplacingalltheoldcharor
CharSequence to new char or CharSequence.
• Therearetwotypeofreplacemethodsinjavastring.
publicStringreplace(charoldChar,charnewChar)
publicStringreplace(CharSequencetarget,CharSequencereplacement)
• ThesecondreplacemethodisaddedsinceJDK1.5.
String replace(char old, char new) method
examplepublic class ReplaceExample1{
public static void main(String args[]){
Strings1="javaisaverygoodlanguage";
// replaces all occurrences of 'a' to 'e'
StringreplaceString=[Link]('a','e');
[Link](replaceString);
}}
Output:jeveisevery
MODIFYSTRINGS
• ThejavastringreplaceAll()methodreturnsastringreplacingallthesequenceof
characters matching regex and replacement string.
Internalimplementation
publicStringreplaceAll(Stringregex,Stringreplacement)
{
[Link](regex).matcher(this).replaceAll(replacement);
}
Signature
publicStringreplaceAll(Stringregex,Stringreplacement)
Regex:RegularExpression
[Link] patterns
are used by string-searching algorithms for "find" or "find and replace" operations
onstrings,orforinputvalid
StringreplaceAll()example:replacecharacter
• Let'sseeanexampletoreplacealltheoccurrencesofasinglecharacter.
publicclassReplaceAllExample1
{
public static void main(String args[]){
Strings1="javaisaverygoodlanguage";
StringreplaceString=[Link]("a","e");//replacesalloccurrences of
"a" to "e"
[Link](replaceString);
}
}
Output:jeveiseverygoodlenguege
StringreplaceAll()example:replaceword
• Let'sseeanexampletoreplacealltheoccurrencesofsinglewordorsetofwords.
StringreplaceAll()example:replacewhitespace
• Let'sseeanexampletoreplacealltheoccurrencesofwhitespaces
STRINGVALUEOFMETHOD
• ThejavastringvalueOf()methodconvertsdifferenttypesofvaluesintostring.
• BythehelpofstringvalueOf()method,wecanconvertinttostring,longtostring,boolean to
string, character to string, float to string, double to string, object to string and char array to
string.
Internalimplementation
public static String valueOf(Object obj) {
return(obj==null)?"null":[Link]();
}
STRINGVALUEOFMETHOD
• ThesignatureorsyntaxofstringvalueOf()methodisgivenbelow:
publicstaticStringvalueOf(booleanb)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
valueOf(booleanbol)MethodExample
ThisisabooleanversionofoverloadedvalueOf()[Link]
boolean value and returns a string. Let's see an example.
valueOf()MethodExample
ImmutableStringinJava
In java, string objects are immutable. Immutable simply means unmodifiable or
[Link]'tbechangedbutanew string
object is created.
ImmutableStringinJava
[Link] object is
created with sachintendulkar. That is why string is known as immutable.
ImmutableStringinJava
• Asyoucanseeinthefigurethattwoobjectsarecreatedbutsreferencevariablestill refers
to "Sachin" not to "Sachin Tendulkar".
• Butifweexplicitlyassignittothereferencevariable,itwillreferto"SachinTendulkar"
object. For example:
Whystringobjectsareimmutableinjava
• InJava,Stringisafinalandimmutableclass,whichmakesit the
most special. It cannot be inherited, and once created, we
can not alter the object.
• Becausejavausestheconceptofstringpooltosavememory.
• Supposethereare5referencevariables,allreferstooneobject
"sachin".
• Ifonereferencevariablechangesthevalueoftheobject,itwill be
affected to all the reference variables.
• Thatiswhystringobjectsareimmutableinjava.
StringandStringBuffer
JavaStringclassobjectsareimmutable.
JavaStringBufferclassisusedtocreatemutable(modifiable)string.
[Link] changed.
StringBuffer,StringBuilder
Mutablestring-Astringthatcanbemodifiedorchangedisknownasmutablestring. StringBuffer and
StringBuilder classes are used for creating mutable string.
ImportantconstructorsofStringBuffer
StringBufferappend()method
append()methodisusedtoaddcontentsattheendofthecurrent string
StringBufferinsert()method
append()methodisusedtoaddcontentsataparticular location(index)
StringBufferreplace()method
Thereplace()methodreplacesthegivenstringfromthespecifiedbeginIndexand endIndex.
StringBufferdelete()method
Thedelete()methodofStringBufferclassdeletesthestringfrom the
specified beginIndex to endIndex.
StringBufferreverse()method
Thereverse()methodofStringBufferclassreversesthecurrentstring.
COLLECTIONSINJAVA
● [Link]’smostpowerfulsubsystems:
● TheCollectionsFramework.
● TheCollectionsFrameworkisasophisticatedhierarchyofinterfacesandclassesthat
provide state-of-the-art technology(best possible technology) for managing groups of
objects.
● TheCollectioninJavaisaframeworkthatprovidesanarchitecturetostoreand
manipulate the group of objects.
● JavaCollectionscanachievealltheoperationsthatyouperformonadatasuchas
searching, sorting, insertion, manipulation, and deletion.
● JavaCollectionframeworkprovidesmanyinterfaces(Set,List,Queue,Deque)and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).
Interfaces&ClassesinCollectionFramework
CollectionsOverview
● TheJavaCollectionsFrameworkstandardizesthewayinwhichgroupsofobjectsare
handled by our programs.
● TheentireCollectionsFrameworkisbuiltuponasetofstandardinterfaces.
● Mechanismswereaddedthatallowtheintegrationofstandardarraysintothe
Collections Framework.
CollectionsOverview(contd.)
TheCollectionsFrameworkwasdesignedtomeetseveralgoals.
● – First, the framework had to be high-performance. The implementations for the
fundamentalcollections(dynamicarrays,linkedlists,trees,andhashtables)arehighly
efficient.
● –Second,theframeworkhadtoallowdifferenttypesofcollectionstoworkinasimilar manner
and with a high degree of interoperability.
● –Third,extendingand/oradaptingacollectionhadtobeeasy.
CollectionsOverview(contd.)
• Algorithmsareanimportantpartofthecollectionmechanism.
– AlgorithmsoperateoncollectionsandaredefinedasstaticmethodswithintheCollections
class.
– Thealgorithmsprovideastandardmeansofmanipulatingcollections.
• JavaCollectionsFrameworkprovidesalgorithmimplementationsthatarecommonlyused
such as sorting, searching etc.
– voidsort(Listlist)
– intbinarySearch(Listlist,Objectvalue)
CollectionsOverview(contd.)
● AnotheritemcloselyassociatedwiththeCollectionsFrameworkistheIterator
interface.
● –Aniteratoroffersageneral-purpose,standardizedwayofaccessingtheelements within
a collection, one at a time.
● –Aniteratorprovidesameansofenumeratingthecontentsofa collection.
● –BecauseeachcollectionimplementsIterator,theelementsofanycollectionclass can
be accessed through the methods defined by Iterator
CollectionsOverview(contd.)
• Theframeworkdefinesseveralmapinterfacesandclasses.
– Maps store key/value pairs.
• Amapcannotcontainduplicatekeys.
• AlthoughmapsarepartoftheCollectionsFramework,theyarenot“collections”inthe
strict use of the term
RecentChangestoCollections
CollectionsFrameworkunderwentafundamentalchangethatsignificantlyincreasedits power
and streamlined its use.
– Thechangeswerecausedbytheadditionof
• generics
• autoboxing/unboxing,and
• for-eachstyleforloop.
RecentChangestoCollections
Genericsaddtheonefeature:typesafety.
– Withgenerics,itispossibletoexplicitlystatethetypeofdatabeingstored,andrun-time type
mismatch errors can be avoided.
Autoboxing/unboxingfacilitatesthestoringofprimitivetypesincollections.
• INTHEPAST,ifwewantedtostoreaprimitivevalue,suchasanint,inacollection,we had to
manually box it into its type wrapper.
• Whenthevaluewasretrieved,itneededtobemanuallyunboxed(byusinganexplicit
cast) into its proper primitive type.
– Becauseofautoboxing/unboxing,Javacanautomaticallyperformtheproperboxingand
unboxing needed when storing or retrieving primitive types.
COLLECTIONFRAMEWORKINTERFACES
Collectioninterface
• Collectioninterfacehelpstoworkwithgroupofobjects
• TheCollectioninterfaceisatthetopofcollectionshierarchy.
• CollectioninterfaceisthefoundationuponwhichtheCollectionsFrameworkisbuilt –
because it must be implemented by any class that defines a collection.
• Collectionisagenericinterfacethathasthisdeclaration:interfaceCollection<E> –
Here, E specifies the type of objects that the collection will hold.
• CollectionextendstheIterableinterface.
– Thismeansthatallcollectionscanbecycledthroughbyuseofthefor-eachstyleforloop.
ollectioninterface
Collectioninterface
Collectioninterface(contd.)
• Wecancheckwhetheracollectioncontainsaspecificobjectbycallingcontains().
• Tocheckwhetheronecollectioncontainsallthemembersofanother,callcontainsAll().
• TodeterminewhetheracollectionisemptycallisEmpty().
• Thenumberofelementscurrentlyheldinacollectioncanbedeterminedbycallingsize().
• ThetoArray()methodsreturnanarraythatcontainstheelementsstoredintheinvoking
collection.
Object[]toArray()returnsanarrayof Object.
<T>T[]toArray(Tarray[])returnsanarrayofelementsthathavethesametypeasthe array
specified as a parameter.
Collectioninterface(contd.)
Twocollectionscanbecomparedwhethertheyareequalornotbycallingequals(). The
precise meaning of “equality” may differ from collection to collection.
– equals()canbeimplementedtocomparethevaluesofelementsstoredinthecollection.
– equals()canbeimplementedtocomparereferencestothoseelements.
The method iterator( ) returns an iterator to a collection.
– Iteratorshelptoloopthroughthecollections.
LISTINTERFACE
● TheListinterfaceextendsCollectioninterface.
● Listdeclaresthebehaviorofacollectionthatstoresasequenceofelements.
● –InJava,theListinterfaceisanorderedcollectionthatallowsustostoreandaccess elements
sequentially.
● Elementscanbeinsertedoraccessedbytheirpositioninthelist,usingzero-based index.
● Alistmaycontainduplicateelements.
● Listisagenericinterfacethathasthisdeclaration:
interface List<E>
ListInterface(contd.)
ListInterface(contd.)
• Listsupportsmethodsdefinedby Collection,
• Listdefinesitsownmethodsalso.
• Somemethodsthrowexceptions.
• ExceptionsthatarethrownbyListmethodsare:
MethodsinList Interface
MethodsinList Interface
• Listhasmanymethods:-add(int,E)andaddAll(int,Collection)
• Thesemethodsinsertelementsatthespecifiedindex.
• Themeaningofadd(E)andaddAll(Collection)definedbyCollectionarechangedbyList. In
List they add elements to the end of the list.
• Toobtaintheobjectstoredataspecificlocation,callget()withtheindexoftheobject.
• Toassignavaluetoanelementinthelist,callset(),specifyingtheindexoftheobjectto be
changed.
• Tofindtheindexofanobject,useindexOf()orlastIndexOf().
• AsublistofalistcanbeobtainedbycallingsubList(),specifyingthebeginningand ending
indexes of the sublist.
LISTINTERFACE
● ListinterfaceisthechildinterfaceofCollectioninterface.
● Itinhibitsalisttypedatastructureinwhichwecanstoretheorderedcollectionof objects.
● Itcanhaveduplicatevalues.
● ListinterfaceisimplementedbytheclassesArrayList,LinkedList,Vector,andStack.
● ToinstantiatetheListinterface,wemustuse:
● List<data-type>list1=newArrayList();
● List<data-type>list2=newLinkedList();
● List<data-type>list3=newVector();
● List<data-type>list4=newStack();
● TherearevariousmethodsinListinterfacethatcanbeusedtoinsert,delete,and access
the elements from the list.
● TheclassesthatimplementtheListinterfacearegivenbelow.
● [Link]
LISTINTERFACE
● TheArrayListclassmaintainstheinsertionorderandisnonsynchronized.
● [Link]
following example.
ArrayList
● JavaArrayListclassusesadynamicarrayforstoringthe elements.
● Itislikeanarray,[Link].
● So,[Link]
package. It is like the Vector in C++.
● [Link]
interface so we can use all the methods of List interface here.
● TheArrayListmaintainstheinsertionorderinternally.
● ItinheritstheAbstractListclassandimplementsListinterface.
ArrayList
TheimportantpointsaboutJavaArrayListclass are:
● JavaArrayListclasscancontainduplicateelements.
● JavaArrayListclassmaintainsinsertionorder.
● JavaArrayListclassisnonsynchronized.
● JavaArrayListallowsrandomaccessbecausearrayworksattheindex basis.
● InArrayList,manipulationislittlebitslowerthantheLinkedListinJavabecausealotof shifting
needs to occur if any element is removed from the array list.
ArrayListExample
IteratingArrayListusingIterator
TheCollectionClasses
• Thecollectionclassesimplementcollectio
ninterfaces.
• Someofthecollectionclassesprovidefull
implementations that can be used as-is.
• Some of the collection classes are abstract,
providing skeletal implementations that are used
asstartingpointsforcreatingconcretecollections.
• Collectionclassesarenotsynchronized.
– Twoormorethreadscanaccessthemethodsof
collection class at any time
TheCollectionClasses
ArrayListClass
• TheArrayListclassextendsAbstractListandimplementstheListinterface.
• ArrayListisagenericclassthathas declaration:
classArrayList<E>
– Here,Especifiesthetypeofobjectsthatthelistwill hold.
• ArrayListsupportsdynamicarraysthatcangrowasneeded.
– Thisisneededbecauseinsomecaseswemaynotknowhowlargeanarraywe need
precisely until run time.
• AnArrayListisavariable-lengtharrayofobjectreferences.
– SoArrayListcandynamicallyincreaseordecreaseinsize.
• Arraylistsarecreatedwithaninitialsize.
– Whenthissizeisexceeded,thecollectionisautomaticallyenlarged.
– Whenobjectsareremoved,thearraycanbeshrunk.
ArrayListClass
rrayListClass(contd.)
• ArrayListhasfollowingconstructors:
ArrayList()
Thisconstructorbuildsanemptyarraylist. ArrayList(Collection<?
extends E> c)
– Thisconstructorbuildsanarraylistthatisinitializedwiththeelementsofthecollectionc.
ArrayList(int capacity)
– Thisconstructorbuildsanarraylistthathasthespecifiedinitialcapacity.
– Thecapacityisthesizeoftheunderlyingarraythatisusedtostoretheelements.
– Thecapacitygrowsautomaticallyaselementsareaddedtoanarraylist.
ArrayListClass(contd.)
ArrayListClass(contd.)
• Thecontentsofacollectionaredisplayedusingthedefaultconversionprovidedby
toString( ), which was inherited fromAbstractCollection.
• WecanincreasethecapacityofanArrayListobjectmanuallybycallingensureCapacity().
void ensureCapacity(int cap)
• IfwewanttoreducethesizeofthearraythatofArrayListobjectsothatitispreciselyas large
as the number of items that it is currently holding, call trimToSize( ):
voidtrimToSize()
ObtaininganArrayfromanArrayList
• Toconvertacollectionintoanarray,toArray(),whichisdefinedbyCollectioncanbe
called.
– Thisisneeded
• Toobtainfasterprocessingtimesforcertainoperations
• Topassanarraytoamethodthatisnotoverloadedtoacceptacollection
• Tointegratecollection-basedcodewithlegacycodethatdoesnotunderstandcollections
• TwoversionsoftoArray()are:
Object[]toArray()
<T>T[]toArray(Tarray[])
ArrayListSample
AccessingCollectionsviaanIterator
• Tocyclethroughtheelementsinacollection([Link],sumofelements
etc.), we can use iterator, which is an object that implements either
– Iteratoror
– ListIterator
AccessingCollectionsviaanIterator
• Tocyclethroughtheelementsinacollection([Link],sumofelements
etc.), we can use iterator, which is an object that implements either
– Iteratoror
– ListIterator
• Iteratorenablesyouto
– cyclethroughacollection
– obtainingorremovingelements.
• ListIteratorextendsIteratortoallow
– bidirectionaltraversalofalist,
– themodificationofelements
IteratorandListIteratoraregenericinterfaceswhicharedeclaredas:
interface Iterator<E>
interfaceListIterator<E>
– Here,Especifiesthetype
AccessingCollectionsviaanIterator
AccessingCollectionsviaanIterator
AccessingCollectionsviaanIterator
Exceptionsinmethods
• ExceptionsintheMethodsDefinedby Iterator
– NoSuchElementException
– IllegalStateException
• ExceptionsintheMethodsDefinedby ListIterator
– NoSuchElementException
– IllegalStateException
– UnsupportedOperationException
UsinganIterator
• Eachofthecollectionclassesprovidesaniterator()methodthatreturnsaniteratortothe start
of the collection.
– Byusingthisiteratorobject,wecanaccesseachelementinthecollection,oneelement at a
time.
• Touseaniteratortocyclethroughthecontentsofacollection,
– [Link]’siterator()
method.
– [Link]().
• HavetheloopiterateaslongashasNext()returns true.
– [Link],obtaineachelementbycallingnext().
UsinganIterator
IteratorvsListiterator
TheFor-EachAlternativetoIterators
• Theforloopissubstantiallyshorterandsimplertousethantheiteratorbased approach.
• Butforloopcanonlybeusedtocyclethroughacollectionintheforwarddirection,andwe can’t
modify the contents of the collection.
• Ifwedon’twanttomodifythecontentsofacollectionorobtainingelementsinreverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
TheFor-EachAlternativetoIterators
• Theforloopissubstantiallyshorterandsimplertousethantheiteratorbased approach.
• Butforloopcanonlybeusedtocyclethroughacollectionintheforwarddirection,andwe can’t
modify the contents of the collection.
• Ifwedon’twanttomodifythecontentsofacollectionorobtainingelementsinreverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
Programtoremoveduplicates
EventHandling
FortheusertointeractwithaGUI,theunderlyingoperatingsystemmust support
event handling.
1) operatingsystemsconstantlymonitoreventssuchaskeystrokes,mouse
clicks, voice command, etc.
2) operatingsystemssortouttheseeventsandreportthemtotheappropriate
application programs
3) eachapplicationprogramthendecideswhattodoinresponsetotheseevents
• Thereareseveraltypesofevents,–Eventscanbegeneratedby
• themouse(click,move,dragmouseetc.)
• thekeyboard(type,press,releaseetc.)
• differentGUIcontrols,suchasa–pushbutton–scrollbar–checkbox
EventHandlingisthemechanismthatcontrolstheeventanddecideswhat should
happen if an event occurs.
WhatisanEvent?
● [Link] change
in state of source.
● Aneventisanobjectthatdescribesastatechangeinasource.
● Eventsaregeneratedasresultofuserinteractionwiththegraphicaluser
interface components.
● Itcanbegeneratedasaconsequenceofapersoninteractingwiththe
elements in a graphical user interface.
● Some of the activities that cause events to be generated are pressing a
button,enteringacharacterviathekeyboard,selectinganiteminalist,and clicking
the mouse.
TypesofEvent
ForegroundEvents-Thoseeventswhichrequirethedirectinteractionofuser. They are
generated as consequences of a person interacting with the GUI.
Forexample,clickingonabutton,movingthemouse,enteringacharacter through
keyboard,selecting an item from list, scrolling the page etc.
BackgroundEvents-Thoseeventsthatrequiretheinteractionofenduserare known as
background events.
Operatingsysteminterrupts,hardwareorsoftwarefailure,timerexpires,an operation
completion are the example of background events.
Eventhandling
● EventHandlingisthemechanismthatcontrolstheeventanddecideswhat
should happen if an event occurs.
● Thismechanismhavethecodewhichisknownaseventhandlerthatis
executed when an event occurs.
● Eventsaresupportedbyanumberofpackages,including
○ [Link],[Link],[Link]
● Eventhandlingisanintegralpartinthecreationofappletsandothertypes of
GUI-based programs.
● Appletsareevent-drivenprogramsthatuseaGUItointeractwiththeuser.
● Anyprogramthatusesagraphicaluserinterfaceiseventdriven.
● Thus,wecannotwritethesetypesofprogramswithoutasolidcommandof event
handling.
EventHandlingMechanisms
• Thetwowaysinwhicheventsarehandledchangedsignificantlybetweenthe
(Two event handling mechanisms)
– originalversionofJava(1.0)eventhandling and
– modernversionsofJava(beginningwithversion1.1)eventhandling
• The1.0methodofeventhandlingisstillsupported,butitisnotrecommended for
new [Link] per this Event was propagated up the containment hierarchy
until it was handled by a component.
– Manyofthemethodsthatsupporttheold1.0eventmodelhavebeen
deprecated.
• Themodernapproachisthewaythateventsshouldbehandledbyallnew
programs
TheDelegationEventModel
• The modern approach to handling
eventsisbasedonthedelegationeventmo
del
– Itdefinesstandardandconsistent
mechanisms to generate and
process events.
• Conceptofdelegationeventmodel:
– Asourcegeneratesaneventandsendsittooneormoreregisteredlisteners.
– Inthisscheme,thelistenersimplywaitsuntilitreceivesan event.
– Onceaneventisreceived,thelistenerprocessestheeventandthenreturns.
TheDelegationEventModel
TheadvantageofDelegationEventModelisthattheapplicationlogicthat processes
events is cleanly separated
fromtheuserinterfacelogicthatgeneratesthoseevents.
Auserinterfaceelementisableto“delegate”(entrust)theprocessingofanevent to a
separate piece of code.
Inthedelegationeventmodel,listenersmustregisterwithasourceinorderto receive an
event notification.
– Benefit:Notificationsaresentonlytolistenersthatwanttoreceivethem.
Inpreviousmodels,aneventwaspropagatedupthecontainmenthierarchyuntilit was
handled by a component.
– Thisrequiredcomponentstoreceiveeventsthattheydidnotprocess,andit
wasted valuable time. The delegation event model eliminates this overhead
TheDelegationEventModel
TheDelegationEventModel
TheDelegationEventModel-Event
• Inthedelegationmodel,aneventisanobjectthatdescribesastatechangeina
source.
• Eventscanbecausedwithorwithoutuserinteraction.
• Someeventsarecausedbyinteractionswithauserinterfacesuchas:
– pressingabutton,enteringacharacterviathekeyboard,
– selectinganiteminalist,clickingthemouse.
• Eventsmayalsooccurthatarenotdirectlycausedbyinteractionswithauser
interface.
– Example:aneventmaybegenerated
• whenatimerexpires,acounterexceedsa value,
• asoftwareorhardwarefailureoccurs,anoperationiscompleted
TheDelegationEventModel–EventSources
• Aeventsourceisanobjectthatgeneratesanevent.
– Eventoccurswhentheinternalstateofthatobjectchangesinsomeway.
• Sourcesmaygeneratemorethanonetypeofevent.
• Asourcemustregisterlisteners,thenonlylistenerscanreceivenotifications
about a specific type of event.
• Eachtypeofeventhasitsownregistrationmethod.
General form of listener registration is:
publicvoidaddTypeListener(TypeListenerel)
– Typeisthenameoftheevent,andelisareferencetotheeventlistener.
– Forexample,themethodthatregistersakeyboardevent
listener is called addKeyListener( ).
– Themethodthatregistersamousemotionlisteneriscalled
addMouseMotionListener().
TheDelegationEventModel–EventSources
• Aeventsourceisanobjectthatgeneratesanevent.
– Eventoccurswhentheinternalstateofthatobjectchangesinsomeway.
• Sourcesmaygeneratemorethanonetypeofevent.
• Asourcemustregisterlisteners,thenonlylistenerscanreceivenotifications
about a specific type of event.
• Eachtypeofeventhasitsownregistrationmethod.
General form of listener registration is:
publicvoidaddTypeListener(TypeListenerel)
– Typeisthenameoftheevent,andelisareferencetotheeventlistener.
– Forexample,themethodthatregistersakeyboardevent
listener is called addKeyListener( ).
– Themethodthatregistersamousemotionlisteneriscalled
addMouseMotionListener().
TheDelegationEventModel–EventSources(contd.)
• Whenaneventoccurs,allregisteredlistenersarenotifiedandreceiveacopyof the
event object. This is known as multicasting the event.
– Inallcases,notificationsaresentonlytolistenersthatregistertoreceive them.
• [Link]
method is this:
publicvoidaddTypeListener(TypeListenerel)[Link]
ption
– Whensuchaneventoccurs,[Link]
known as unicasting the event.
TheDelegationEventModel–EventSources(contd.)
Asourcemustalsoprovideamethodthatallowsalistenertounregisteraninterest in a
specific type of event. The general form of such a method is this:
publicvoidremoveTypeListener(TypeListenerel)
• Here,Typeisthenameoftheevent,andelisareferencetotheeventlistener.
– Forexample,toremoveakeyboardlistener,call
removeKeyListener( ).
• Themethodsthataddorremovelistenersareprovidedbythesourcethat
generates events.
– Forexample,theComponentclassprovidesmethodstoaddandremove
keyboard and mouse event listeners.
TheDelegationEventModel–EventListeners
● Alistenerisanobjectthatisnotifiedwhenaneventoccurs.
● Ithastwomajorrequirements.
● First,itmusthavebeenregisteredwithoneormoresourcestoreceive
notifications about specific types of events.
● Second,itmustimplementmethodstoreceiveand
● processthesenotifications
● Themethodsthatreceiveandprocesseventsaredefinedinasetofinterfaces found
in [Link].
● –Forexample,theMouseMotionListenerinterfacedefinestwomethodsto
receive notifications when the mouse is dragged or moved.
● Anyobjectmayreceiveandprocessoneorbothoftheseeventsifitprovides an
implementation of this interface.
TheDelegationEventModel
ComponentvsContainer
● InJava,acomponentisthebasicuserinterfaceobjectandisfoundinallJava
applications.
● ThemaindifferencebetweenthemisthataContainerisasubclassof
Component.
● Containercancontainothercomponentsand containers.
● Frame,PanelandAppletareexamplesofContainer
● Button,TextFieldetcareexamplesofComponent.
EventClasses
● Theclassesthatrepresentevents(Eventclasses)areatthecoreofJava’sevent
handling mechanism.
● ThemostwidelyusedeventsarethosedefinedbytheAWTandthosedefinedby
Swing.
● AttherootoftheJavaeventclasshierarchyisEventObject,whichisin [Link].
● –EventObjectisthesuperclassforallevents.
● –Itsoneconstructoris:EventObject(Objectsrc)
● –Here,srcistheobjectthatgeneratesthisevent
EventClasses(contd.)
● EventObjectcontainstwomethods:getSource(),toString().
● ThegetSource()methodreturnsthesourceofthe event.
● Itsgeneralformis:ObjectgetSource()
● -toString()returnsthestringequivalentoftheevent.
TheclassAWTEvent,[Link],isasubclassof
EventObject.
● –Itisthesuperclass(eitherdirectlyorindirectly)ofallAWT-basedeventsused by the
delegation event model.
● –ItsgetID()methodcanbeusedtodeterminethetypeoftheevent.
● –ThesignatureofgetID()methodisintgetID()
EventClasses(contd.)
EventClasses(contd.)
EventClasses(contd.)
TheActionEventClass
● AnActionEventisgeneratedwhen
● –abuttonispressed,
● –alistitemisdouble-clicked,
● –menuitemis selected.
● TheActionEventclassdefinesfourintegerconstantsthatcanbeusedto
identify any modifiers associated with an action event:
● –ALT_MASK
● –CTRL_MASK
● –META_MASK
● –SHIFT_MASK.
● IntegerconstantACTION_PERFORMED,canbeusedtoidentifyaction
events.
TheActionEventClass(contd.)
● ActionEventhasthesethreeconstructors:
● ActionEvent(Objectsrc,inttype,Stringcmd)
● ActionEvent(Objectsrc,inttype,Stringcmd,intmodifiers)
● ActionEvent(Objectsrc,inttype,Stringcmd,longwhen,intmodifiers)
● –Here,srcisareferencetotheobjectthatgeneratedthisevent.
● –Thetypeoftheeventisspecifiedbytype,anditscommandstringiscmd.
● –Theargumentmodifiersindicateswhichmodifierkeys(ALT,CTRL,META,
and/or SHIFT) were pressed when the event was generated.
● –Thewhenparameterspecifieswhentheevent occurred.
● ToobtainthecommandnamefortheinvokingActionEvent
● objectgetActionCommand()methodcanused:
● Forexample,whenabuttonispressed,anactioneventisgeneratedthathasa
command name equal to the label on that button.
TheActionEventClass(contd.)
● ThegetModifiers()method
● –returnsavaluethatindicateswhichmodifierkeys(ALT,CTRL,META,and/or
SHIFT) were pressed when the event was generated.
● Itsformis:intgetModifiers()
● ThemethodgetWhen() method
● –[Link]’s
timestamp. The getWhen( ) method is :
● longgetWhen()
TheAdjustmentEventClass
● AnAdjustmentEventisgeneratedbyascrollbar.
● Therearefivetypesofadjustmentevents.
● TheAdjustmentEventclassdefinesintegerconstantsthatcanbeusedtoidentify them.
TheAdjustmentEventClass
● ThegetAdjustable()methodreturnstheobjectthatgeneratedtheevent.
● Itsformis;AdjustablegetAdjustable()
● ThetypeoftheadjustmenteventmaybeobtainedbythegetAdjustmentType()
method.
● ItreturnsoneoftheconstantsdefinedbyAdjustmentEvent.
● Thegeneralformis:intgetAdjustmentType()
● TheamountoftheadjustmentcanbeobtainedfromthegetValue()methodis:
● intgetValue()
● –Forexample,whenascrollbarismanipulated,thismethodreturnsthevalue
represented by that change.
TheComponentEventClass
● AComponentEventisgeneratedwhenthesize,position,orvisibilityofa
component is changed.
● Therearefourtypesofcomponentevents.
● –TheComponentEventclassdefinesintegerconstantsfor this.
TheComponentEventClass(contd.)
● ComponentEventhastheconstructor:ComponentEvent(Componentsrc,inttype)
● –Here,srcisareferencetotheobjectthatgeneratedthisevent.
● Thetypeoftheeventisspecifiedbytype.
● ComponentEventisthesuperclasseitherdirectlyorindirectlyofContainerEvent,
FocusEvent, KeyEvent, MouseEvent, and WindowEvent.
● ThegetComponent()methodreturnsthecomponentthatgeneratedtheevent
● ComponentgetComponent()
TheContainerEventClass
● •AContainerEventisgeneratedwhenacomponentisaddedtoorremovedfroma
container.
● •Therearetwotypesofcontainer events.
● •TheContainerEventclassdefinesintconstantsthatcanbeusedtoidentifythem:
● –COMPONENT_ADDED
● –COMPONENT_REMOVED.
● ContainerEventisasubclassofComponentEvent.
● Constructor:ContainerEvent(Componentsrc,inttype,Componentcomp)
● –Here,srcisareferencetothecontainerthatgeneratedthisevent.
● Thetypeoftheeventisspecifiedbytype,andthecomponentthathasbeenadded to or
removed from the container is comp.
TheContainerEventClass
• AreferencetothecontainerthatgeneratedthiseventbyusingthegetContainer()
method.
ContainergetContainer()
• ThegetChild()methodreturnsareferencetothecomponentthatwasaddedtoor
removed from the container.
ComponentgetChild()
TheFocusEventClass
● •AFocusEventisgeneratedwhenacomponentgainsorlosesinputfocus.
● •Theseeventsareidentifiedbytheintegerconstants
● –FOCUS_GAINED
● –FOCUS_LOST.
● •FocusEventisasubclassofComponentEventandhastheseconstructors:
● FocusEvent(Componentsrc,inttype)
● FocusEvent(Componentsrc,inttype,booleantemporaryFlag)
● FocusEvent(Componentsrc,inttype,booleantemporaryFlag,Componentother)
● TheargumenttemporaryFlagissettotrueifthefocuseventistemporary.
● Otherwise,itissettofalse.
● Theothercomponentinvolvedinthefocuschange,calledtheoppositecomponent, is
passed in other.
TheFocusEventClass(contd.)
● Atemporaryfocuseventoccursasaresultofanotheruserinterface operation.
● –Forexample,[Link] to adjust
a scroll bar, the focus is temporarily lost.
● ifaFOCUS_GAINEDeventoccurred,otherwillrefertothecomponentthatlost focus.
● •Conversely,ifaFOCUS_LOSTeventoccurred,otherwillrefertothecomponent that
gains focus.
● •TodeterminetheothercomponentcallgetOppositeComponent():
● ComponentgetOppositeComponent()
● –Theoppositecomponentisreturned.
● •TheisTemporary()methodindicatesifthisfocuschangeistemporary.
● booleanisTemporary()
● –Themethodreturnstrueifthechangeistemporary.
● –Otherwise,it
TheInputEventClass
● TheabstractclassInputEventisasubclassofComponentEventandisthe
superclass for component input events.
● –ItssubclassesareKeyEventand MouseEvent.
● •InputEventdefinesseveralintegerconstantsthatrepresentanymodifiers,suchas the
control key being pressed.
● InputEventclassdefinedthefollowingeightvaluestorepresentthemodifiers:
● ALT_MASK
● •ALT_GRAPH_MASK
● •BUTTON1_MASK
● •BUTTON2_MASK
● •BUTTON3_MASK
● •CTRL_MASK
● •META_MASK
● •SHIFT_MASK
TheInputEventClass
● TheabstractclassInputEventisasubclassofComponentEventandisthe
superclass for component input events.
● –ItssubclassesareKeyEventand MouseEvent.
● •InputEventdefinesseveralintegerconstantsthatrepresentanymodifiers,suchas the
control key being pressed.
● InputEventclassdefinedthefollowingeightvaluestorepresentthemodifiers:
● ALT_MASK,ALT_GRAPH_MASK,BUTTON1_MASK,BUTTON2_MASK
● BUTTON3_MASK,CTRL_MASK,META_MASK,SHIFT_MASK
● Theextendedmodifiervaluestoavoidconflictbetweenkeyboardandmouseevent
modifiers are:
● •ALT_DOWN_MASK,•ALT_GRAPH_DOWN_MASK,•BUTTON1_DOWN_MASK
● •BUTTON2_DOWN_MASK,•BUTTON3_DOWN_MASK,•CTRL_MASK
● •META_DOWN_MASK,•SHIFT_DOWN_MASK
TheItemEventClass
● •AnItemEventisgenerated when
● –acheckboxoralistitemisclickedor
● –whenacheckablemenuitemisselectedordeselected.
● •Therearetwotypesofitemevents,whichareidentifiedbythefollowinginteger
constants:
● DESELECTED-Theuserdeselectedanitem.
● SELECTED-Theuserselectedanitem.
References
● HerbertSchildt,Java:TheCompleteReference,8/e,TataMcGrawHill,2011.
● [Link]
● [Link]
● [Link]
● JavaZone-[Link]
● [Link]
● [Link]
Disclaimer-Thisdocumentcontainsimages/[Link] respective
content creators. Document is compiled exclusively for study purpose and shall not be used for
.
commercialpurpose
OOPJ
JavaSwingisapartofJavaFoundationClasses(JFC)thatisusedto
createwindow-basedapplications.
ItisbuiltonthetopofAWT(AbstractWindowingToolkit)APIand entirely
written in java
JFC
• TheJavaFoundationClasses(JFC)areasetofGUIcomponentswhich
simplify the development of desktop applications.
The [Link] package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
SWINGFUNDAMENTALS
• JavaSwingisaGUIFrameworkthatcontainsasetofclassesto provide
more powerful and flexible GUI components than AWT.
• SwingprovidesthelookandfeelofmodernJavaGUI.
• SwinglibraryisanofficialJavaGUItoolkitreleasedbySun
Microsystems.
• ItisusedtocreategraphicaluserinterfacewithJava.
• [Link]- packages.
• Java Swing provides platform-independent and lightweight
components.
1
OOPJ
Plugging:
• It has a powerful component that can be extended to provide the
support for the user interface that helps in good look and feel to
the application.
• It refers to the highly modular-based architecture that allows it to
plug into other customized implementations and framework for
user interfaces.
Manageable: It is easy to manage and configure. Its mechanism and
composition pattern allows changing the settings at run time aswell.
The uniform changes can be provided to the user interface without
doing any changes to application code.
MVC:
• They mainly follows the concept of MVC that is Model View
Controller.
• With the help of this, we can do the changes in one component
without impacting or touching other components.
• Itisknownaslooselycoupledarchitectureaswell.
Customizable:
• Swing controls can be easily customized. It canbechanged andthe
visual appearance of the swing component application is
independent of its internal representation.
RichControls:
• SwingprovidesarichsetofadvancedcontrolslikeTree,
TabbedPane,slider,colorpicker,andtablecontrols.
6
2
OOPJ
DifferencebetweenAWTandSwing
HierarchyofJavaSwingclasses
3
OOPJ
TheModel-View-ControllerArchitecture
• Swing uses the model-view-controller architecture (MVC) as the
fundamental design behind each of its components
• Essentially,MVCbreaksGUI componentsintothreeelements. Each of
these elements plays a crucial role in how the component behaves.
• The Model-View-Controller is a well known software architectural
pattern ideal to implement user interfaces on computers by
dividing an application intro three interconnected parts
10
4
OOPJ
• theMVCpatterndefinestheinteractionsbetweenthesethreecompone
nts like you can see in the following figure :
11
• [Link] stores
these data and updates the View.
• TheViewletstopresentdataprovidedbytheModeltotheuser.
• TheControlleracceptsinputsfromtheuserandconvertsittocommands
for the Model or the View.
12
5
OOPJ
COMPONENTS&CONTAINERS
• A component is an independent visual control, such as a push
button or slider.
• A container holds a group of components. Thus, a container is a
special type of component that is designed to hold other
components.
• [Link],
which is the root of the Swing component hierarchy.
13
COMPONENTS
• SwingcomponentsarederivedfromtheJComponentclass.
• JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable
look and feel.
• JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT
component.
• All of Swing’s components are represented by classes defined
within the package [Link].
• ThefollowingtableshowstheclassnamesforSwingcomponents
14
6
OOPJ
• JApplet
• JColorChooser • JTogglebutton
• JDialog • JViewport
• JFrame • JButton
• JLayeredPane • JComboBox
• JMenuItem • JEditorPane
• JPopupMenu • JInternalFrame
• JRootPane • JList
• JSlider • JOptionPane
• JTable • JProgressBar
15
• NoticethatallcomponentclassesbeginwiththeletterJ.
• For example, the class for a label is JLabel; the class for a push
button is JButton; and the class for a scroll bar is JScrollBar
CONTAINERS
• Swing defines two types of containers. The first are top-level
containers: JFrame, JApplet, JWindow, and JDialog. These
containers do not inherit JComponent. They inherit the AWT
classes Component and Container.
• The second type container are lightweight and the top-level
containers are heavyweight. This makes the top-level containers a
special case in the Swing component library.
16
7
OOPJ
InJava,Containersaredividedintotwotypesasshownbelow:
17
Followingisthelistofcommonlyusedcontainerswhiledesigned
GUIusingSWING.
18
8
OOPJ
SwingExample:Awindowonthescreen.
Output
19
EVENTHANDLINGINSWINGS
• The functionality of Event Handling is what is the further step if an
action performed.
• Javafoundationintroduced“DelegationEventModel”[Link]
how to generate and control the events.
• The key elements of the Delegation Event Model are as source and
listeners.
• Thelistenershouldhaveregisteredonsourceforthepurposeof alert
notifications.
• AllGUIapplicationsareevent-driven
20
10
OOPJ
JavaSwingeventobject
• Whensomethinghappensintheapplication,aneventobjectis created.
• For example, when we click on the button or select an item from a
list.
• Thereareseveraltypesofevents,includingActionEvent,TextEvent,
FocusEvent, and ComponentEvent.
• Eachofthemiscreatedunderspecificconditions.
• An event object holds information about an event that has
occurred.
21
SWINGLAYOUTMANAGERS
• Layout refers to the arrangement of components within the
container.
• Layoutisplacingthecomponentsataparticularpositionwithinthe
container. The task of laying out the controls is done automatically
by the Layout Manager.
• The layout manager automatically positions all the components
within the container.
• Even if you do not use the layout manager, the components are
still positioned by the default layout manager. It is possible to lay
out the controls by hand, however, it becomes very difficult
22
11
OOPJ
BorderLayout GridLayout
24
12
OOPJ
FlowLayout BoxLayout
25
CardLayout GroupLayout
26
13
OOPJ
ExampleofJButton
27
ExampleofJTextField
28
14
OOPJ
ExampleofJlabel-Itisusedforplacingtextina box
29
15
OOPJ
MODULE 5
CHAPTER 2
JDBC
1
OOPJ
JDBC Architecture
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 provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to
access each data source.
2
OOPJ
3
OOPJ
4
OOPJ
5
OOPJ
6
OOPJ
Output
User #1: bill - secretpass - Bill Gates - [Link]@[Link]
14
7
OOPJ
15
16