OOPJ PPTs
OOPJ PPTs
K.Anusha/Dr.N.Kavitha/P.Revathy/Gopal
CSE/NRCM
UNIT-1
OBJECT-ORIENTED
THINKING,JAVA BASICS
CSE/NRCM
History of Java
Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-
top boxes, televisions etc. It was best suited for internet programming.
Later, Java technology as incorporated by Netscape.James Gosling,
Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
Let us consider a situation, I am at my office and I wish to get food to my family members
who are at my home from a hotel. Because of the distance from my office to home, there
is no possibility of getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell
them the variety and quantity of food and the hotel name from which I wish to delever
the food to my family members. Look at the following image.
CSE/NRCM
JAVA BUZZWORDS OR FEATURES OF
JAVA
• Simple
• Secured
• Platform
independent
• Robust
• Portable
• Architecture neutral
• Dynamic
• Interpreted
• High Performance
• Multithreaded
• Distributed
CSE/NRCM
APPLICATIONS OF OBJECT ORIENTED
PROGRAMMING
CSE/NRCM
JDK, JRE and
JVMKit (JDK):
Java Development
JDK is an acronym for Java Development Kit. It physically
exists. It
contains JRE + development tools.
CSE/NRCM
JDK, JRE and
JVM (JVM):
Java Virtual Machine
JVM (Java Virtual Machine) acts as a run-time engine to run Java
applications. JVM is the one that actually calls the main method
present in a java code. JVM is a part of JRE (Java Runtime
Environment).
CSE/NRCM
Execution Process of Java
Program
The following three steps are used to
create and execute a java program.
• Create a source code (.java file).
• Compile the source code using javac
command.
• Run or execute .class file uisng java
command.
CSE/NRCM
JAVA DATA TYPES
CSE/NRCM
JAVA
A variable is VARIABLES
a named memory location used to
store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create
variables.
Syntax
data_type
variable_name; (or)
data_type variable_name_1,
variable_name_2,...; (or)
data_type variable_name =
value; (or)
data_type variable_name_1 = value,
variable_name_2 = value,...;
CSE/NRCM
JAVA ARRAYS
Creating an array
In the java programming language, an array must be created using
new operator and with a specific size. The size must be an integer
value but not a byte, short, or long. We use the following syntax to
create an array.
Syntax
data_type array_name[ ] = new
data_type[size]; (or)
data_type[ ] array_name = new data_type[size];
CSE/NRCM
Arithmetic Operators
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Modulus - Remainder of the Division 5%2=1
++ Increment a++
-- Decrement a--
CSE/NRCM
Relational Operators (<, >, <=, >=, ==,
!=)
Operator Meaning Example
< Returns TRUE if the first value is smaller than second value 10 < 5 is FALSE
otherwise returns FALSE
> Returns TRUE if the first value is larger than second value 10 > 5 is TRUE
otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or equal to second 10 <= 5 is FALSE
value otherwise returns FALSE
>= Returns TRUE if the first value is larger than or equal to second 10 >= 5 is TRUE
value otherwise returns FALSE
== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is FALSE
!= Returns TRUE if both values are not equal otherwise returns 10 != 5 is TRUE
FALSE
CSE/NRCM
Logical Operators
Operator Meaning Example
& Logical AND - Returns TRUE if all conditions are TRUE false & true => false
otherwise returns FALSE
| Logical OR - Returns FALSE if all conditions are FALSE false | true => true
otherwise returns TRUE
^ Logical XOR - Returns FALSE if all conditions are same true ^ true => false
otherwise returns TRUE
! Logical NOT - Returns TRUE if condition is FLASE and returns !false => true
FALSE if it is TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a false & true => false
decision is finalized it does not evaluate remianing.
|| short-circuit OR - Similar to Logical OR (|), but once a decision false | true => true
is finalized it does not evaluate remianing.
CSE/NRCM
Assignment Operators
Operator Meaning Example
CSE/NRCM
Bitwise Operators
Operator Meaning Example
& the result of Bitwise AND is 1 if all the bits are A&B
1 otherwise it is 0 ⇒ 16 (10000)
| the result of Bitwise OR is 0 if all the bits are 0 A|B
otherwise it is 1 ⇒ 29 (11101)
^ the result of Bitwise XOR is 0 if all the bits are A^B
same otherwise it is 1 ⇒ 13 (01101)
~ the result of Bitwise once complement is ~A
negation of the bit (Flipping) ⇒ 6 (00110)
<< the Bitwise left shift operator shifts all the bits to A << 2
the left by the specified number of positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits A >> 2
to the right by the specified number of positions ⇒ 6 (00110)
CSE/NRCM
Conditional Operators
The conditional operator is also called a
ternary operator because it requires three operands.
This operator is used for decision making. In this operator,
first, we verify a condition, then we perform one operation
out of the two operations based on the condition result.
If the condition is TRUE the first option is performed, if
the condition is FALSE the second option is performed.
Syntax
Condition ? TRUE Part : FALSE Part;
CSE/NRCM
JAVA EXPRESSIONS
Expression Types
In the java programming language,
expressions are divided into THREE types.
They are as follows.
• Infix Expression
• Postfix Expression
• Prefix ExpressionCSE/NRCM
JAVA CONTROL
STATEMENTS
CSE/NRCM
JAVA CONTROL
STATEMENTS
if statement if-else
statement
JAVA CONTROL
STATEMENTS
Switch
statement
JAVA CONTROL
STATEMENTS do-while
while
statement statement
CSE/NRCM
JAVA CONTROL
STATEMENTS for-each
for
statement statement
CSE/NRCM
JAVA CONTROL
STATEMENTS
break continue
statement statement
JAVA CLASSES
• Java is an object-oriented programming language, so everything in
java
program must be based on the object concept.
• In a java programming language, the class concept defines the
skeleton
of an object.
• The java class is a template of an object. The class defines the
blueprint
of an object. Every class in java forms a new data type.
• Once a class got created, we can generate as many objects as we
want.
Every class defines the properties and behaviors of an object.
• All the objects of a class have the same properties and behaviors
that
were defined in the class.
CSE/NRCM
Every class of java programming language has the following
JAVA CLASSES
Creating a Class
In java, we use the keyword class to create a class. A class in java
contains properties as variables and behaviors as methods. Following is
the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
The ClassName must begin with an alphabet, and the Upper-case letter
is
preferred.
The ClassName must follow all naming rules.
CSE/NRCM
JAVA CLASSES
Creating an Object
In java, an object is an instance of a class. When an object of a class
is created, the class is said to be instantiated. All the objects that are
created using a single class have the same properties and methods.
But the value of properties is different for every object. Following is
the syntax of class in the java.
Syntax
<ClassName> <objectName> = new <ClassName>( );
CSE/NRCM
JAVA METHODS
A method is a block of statements under a name that gets executes
only when it is called. Every method is used to perform a specific
task. The major advantage of methods is code re-usability (define
the code once, and use it many times).
In a java programming language, a method defined as a behavior of
an
object. That means, every method in java must belong to a
class. Every method in java must be declared inside a
class.
Every method declaration has the following
characteristics. returnType - Specifies the data type
of a return value. name - Specifies a unique name to
identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method.
CSE/NRCM
JAVA METHODS
Creating a method
A method is created inside the class and it may be created with any access
specifier.
However, specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
🔔 The methodName must begin with an alphabet, and the Lower-case letter is
preferred.
🔔 The methodName must follow all naming rules.
🔔 If you don't want to pass parameters, we ignore it.
🔔 If a method defined with return type other than void, it must contain the
return statement, otherwise, it may beCSE/NRCM
ignored.
JAVA METHODS
Calling a method
In java, a method call precedes with the object name of the class to which it
belongs and a dot operator. It may call directly if the method defined with the static
modifier. Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.
Syntax
<objectName>.<methodName>( actualArguments );
🔔 The method call must pass the values to parameters if it has.
🔔 If the method has a return type, we must provide the receiver.
🔔 The objectName must begin with an alphabet, and a Lower-case letter is
preferred.
🔔 The objectName must follow all naming rules.
When a method has both the normal parameter and variable-argument, then the
variable
Constructor
A constructor is a special method of a class that has the same name as the class
name. The constructor gets executes automatically on object creation. It does not
require the explicit method call. A constructor may have parameters and access
specifiers too. In java, if you do not provide any constructor the compiler
automatically creates a default constructor. A constructor cannot have return
value.
Let's look at the following example java code.
Example
public class ConstructorExample {
ConstructorExample() {
System.out.println("Object created!");
}
public static void main(String[] args) {
CSE/NRCM
Creating String object in java
Creating String object in java
In java, we can use the following two ways to create a string object.
Using string literal
Using String constructor
Let's look at the following example java code.
Example
String title = "Java Tutorials"; // Using literals
CSE/NRCM
String handling methods
Method Description Return Value
charAt(int) Finds the character at given index char
length() Finds the length of given string int
compareTo(String) Compares two strings int
compareToIgnoreCase(String) Compares two strings, ignoring case int
concat(String) Concatenates the object string with argument string. String
contains(String) Checks whether a string contains sub-string boolean
contentEquals(String) Checks whether two strings are same boolean
equals(String) Checks whether two strings are same boolean
equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
startsWith(String) Checks whether a string starts with the specified boolean
string
endsWith(String) Checks whether a string ends with the specified boolean
string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
indexOf(String) Finds the first index of argument string in object int
string
lastIndexOf(String) Finds the last index of argument string in object int
string
CSE/NRCM
String handling methods
Method Description Return Value
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
replaceAll(String, String) Replaces the first string with second string at all String
occurrences.
substring(int, int) Extracts a sub-string from specified start and end String
index values
toLowerCase() Converts a string to lower case letters String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends String
toString(int) Converts the value to a String object String
split(String) splits the string matching argument string String[]
intern() returns string from the pool String
join(String, String, ...) Joins all strings, first string as delimiter. String
CSE/NRCM
UNIT – II
INHERITANCE,
PACKAGES,
INTERFACES
CSE/NRCM
JAVA INHERITANCE
The inheritance can be defined as
follows. inheritance
The is the acquiring
process of properties of one th
class to another class. Inheritance e
Basics
In inheritance, we use the terms like parent class,
child class, base class, derived class, superclass,
and subclass. The Parent class is the class which
provides features to another class. The parent
class is also known as Base class or
Superclass.
CSE/NRCM
Creating Child Class in java
In java, we use the keyword extends to create a child class. The following syntax used
to
create a child class in java.
Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}
CSE/NRCM
JAVA ACCESS MODIFIERS
In Java, the access specifiers (also known as access modifiers) used to restrict
the scope or accessibility of a class, constructor, variable, method or data
member of class and interface. There are four access specifiers, and their list is
below.
default (or) no modifier
public
protecte
d
Private
CSE/NRCM
JAVA CONSTRUCTORS IN
INHERITANCE
However, if the parent class contains default and parameterized constructor, then only
the default constructor called automatically by the child class constructor.
Let's look at the following example java code.
The parameterized constructor of parent class must be called explicitly using
the super keyword.
CSE/NRCM
JAVA SUPER KEYWORD
In java, super is a keyword used to refers to the parent class object. The super
keyword came into existence to solve the naming conflicts in the inheritance.
When both parent class and child class have members with the same name, then
the super keyword is used to refer to the parent class version.
In java, the super keyword is used for the following purposes.
• To refer parent class data members
• To refer parent class methods
• To call parent class constructor
🔔 The super keyword is used inside the child class only.
CSE/NRCM
JAVA PYLYMORPHISM
The polymorphism is the process of defining same method with different
implementation. That
means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.
Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with
different implementations and different arguments. In a java programming
language, ad hoc polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad
hoc polymorphism is also known as compile-time polymorphism. Every function call
binded with the respective overloaded method based on the arguments. The ad hoc
polymorphism implemented within the class only.
Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure
polymorphism carried out with a method overriding concept. In pure polymorphism, the
method binding happens at run time. Pure polymorphism is also known as run-time
polymorphism. Every function call binding with the respective overridden method based
on the object reference.
concept CSE/NRCM
When a child class has a definition for a member function of the parent class, the parent
JAVA METHOD OVERRIDING
The method overriding is the process of re-defining a method in a child class that is
already defined in the parent class. When both parent and child classes have the
same method, then that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the
method
which aquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The
method binding which happens at run time is known as late binding. So, the method
overriding follows late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
CSE/NRCM
JAVA METHOD OVERRIDING
Rules for method overriding
• While overriding a method, we must follow the below list of rules.
• Static methods can not be overridden.
• Final methods can not be overridden.
• Private methods can not be overridden.
• Constructor can not be overridden.
• An abstract method must be overridden.
• Use super keyword to invoke overridden method from child class.
• The return type of the overriding method must be same as the parent has it.
• The access specifier of the overriding method can be changed, but the visibility must
increase but not decrease. For example, a protected method in the parent class can
be made public, but not private, in the child class.
• If the overridden method does not throw an exception in the parent class, then the
child class overriding method can only throw the unchecked exception, throwing a
checked exception is not allowed.
• If the parent class overridden method does throw an exception, then the child class
overriding method can only throw the same, or subclass exception, or it may not
throw any exception.
CSE/NRCM
JAVA ABSTRACT
AnCLASS
abstract class is a class that created using abstract keyword. In other words, a class
prefixed
with abstract keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without
implementation) and
also non-abstract methods (methods with implementation).
We use the following syntax to create an abstract class.
Syntax
abstract class <ClassName>{
...
}
CSE/NRCM
Java Object Class
In java, the Object class is the super most class of any class hierarchy. The Object
class in the
java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by
default.
The Object class is useful when you want to refer to any object whose type you don't
know.
Because
Method it isDescription
the superclass of all other classes in java, it can referReturn
to any type of
Value
object.
getClass() Returns Class class object object
Methods
equals(Objectofcompares
Object the class
argument object to calling object. boolean
obj)
The following table depicts all built-in methods of Object class in java.
concat(String) Creates copy of invoking object object
toString() eturns the string representation of invoking object. String
notify() wakes up a thread, waiting on invoking object's monitor. void
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds and nanoseconds, void
until another thread notifies.
finalize() It is invoked by the garbage collector before an object is being garbage collected. void
CSE/NRCM
JAVA FORMS OF INHERITANCE
The inheritance concept used for the number of purposes in the java programming
language. One of the main purposes is substitutability. The substitutability means that
when a child class acquires properties from its parent class, the object of the parent
class may be substituted with the child class object. For example, if B is a child class of
A, anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the different forms of inheritance in java.
Specialization
Specification
Construction
Extension
Limitation
Combination
CSE/NRCM
JAVA FORMS OF INHERITANCE
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent
class. It
holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the
parent class just specifies which methods should be available to the child class but
doesn't implement them. The java provides concepts like abstract and interfaces to
support this form of inheritance. It holds the principle of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior
defined by the parent class (overriding). It does not hold the principle of
substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It
holds
the principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does
JAVA FORMS OF INHERITANCE
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent
class. It
holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the
parent class just specifies which methods should be available to the child class but
doesn't implement them. The java provides concepts like abstract and interfaces to
support this form of inheritance. It holds the principle of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior
defined by the parent class (overriding). It does not hold the principle of
substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It
holds
the principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does
Benefits and Costs of Inheritance in
java
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the
parent
class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that
the meaningful implementation of the base class method can be designed in the
derived class. An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it
takes,
the program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled.
This
means one cannot be used independently of each other.
The changes made in the parent classCSE/NRCM
will affect the behavior of child class too.
DEFINING PACKAGES
In java, a package is a container of classes, interfaces, and sub-packages. We may
think of it as a
folder in a file directory.
We use the packages to avoid naming conflicts and to organize project-related classes,
interfaces, and sub-packages into a bundle.
In java, the packages have divided into two
types. Built-in Packages
User-defined Packages
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-
defined classes, interfaces, and sub-packages. The built-in packages were included in
the JDK. There are many built-in packages in java, few of them are as java, lang, io, util,
awt, javax, swing, net, sql, etc. We need to import the built-in packages to use them in
our program. To import a package, we use the import statement.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to
create their own packages.
CSE/NRCM
Definig/Creating a Package in java
We use the package keyword to create or define a package in java programming language.
Syntax
package packageName;
CSE/NRCM
IMPORTING PACKAGES IN JAVA
In java, the import keyword used to import built-in and user-defined packages. When a package
has
imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other
statement. Using an import statement, we may import a specific class or all the
classes from a package.
Using one import statement, we may import only one package or a class.
Using an import statement, we cannot import a class directly, but it must be a part of a
package. A program may contain any number of import statements.
CSE/NRCM
IMPLEMENTING AN INTERFACE IN
In java, an interface is implemented by a class. The class that implements an
JAVA
interface must provide code for all the methods defined in the interface; otherwise, it
must be defined as an abstract class.
The class uses a keyword implements to implement an interface. A class can
implement any
number of interfaces. When a class wants to implement more than one interface, we
use
the implements keyword is followed by a comma-separated list of the interfaces
implemented
by the class.
The following is the syntax for defineing a class that implements an interface.
Syntax
class className implements InterfaceName{
...
boby-of-the-class
...
}
CSE/NRCM
Implementing multiple Interfaces
Implementing multiple Interfaces
When a class wants to implement more than one interface, we use the implements
keyword is followed by a comma-separated list of the interfaces implemented by the
class.
The following is the syntax for defineing a class that implements multiple interfaces.
Syntax
class className implements InterfaceName1, InterfaceName2, ...{
...
boby-of-the-class
...
}
CSE/NRCM
NESTED INTERFACES IN JAVA
In java, an interface may be defined inside another interface, and also inside a
class. The interface that defined inside another interface or a class is konwn as
nested interface. The nested interface is also refered as inner interface.
The nested interface declared within an interface is public by default.
The nested interface declared within a class can be with any access modifier.
Every nested interface is static by default.
The nested interface cannot be accessed directly. We can only access the nested
interface by using outer interface or outer class name followed by dot( . ), followed by
the nested interface name.
Nested interface inside another interface
The nested interface that defined inside another interface must be accessed
as OuterInterface.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside another interface.
Example
interface OuterInterface{
void outerMethod();
interface InnerInterface{
void
innerMethod(); CSE/NRCM
} }
VARIABLES IN JAVA INTERFACES
In java, an interface is a completely abstract class. An interface is a container of abstract
methods and static final variables. The interface contains the static final variables. The variables
defined in an interface cannot be modified by the class that implements the interface, but it may
use as it defined in the interface.
The variable in an interface is public, static, and final by default.
If any variable in an interface is defined without public, static, and final keywords then, the
compiler automatically adds the same.
No access modifier is allowed except the public for interface variables.
Every variable of an interface must be initialized in the interface itself.
The class that implements an interface can not modify the interface variable, but it may use as it
defined
in the interface.
Example
interface SampleInterface{
int UPPER_LIMIT = 100;
//int LOWER_LIMIT; // Error - must be initialised
}
CSE/NRCM
STREAM IN JAVA
In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows us
to read from and write to it. A stream can be linked to a data source, or data destination, like a
console, file or network connection by java IO system. The stream-based IO operations are
faster than normal IO operations.
The Stream is defined in the java.io package.
To understand the functionality of java streams, look at the following picture.
CSE/NRCM
BYTE STREAM IN JAVA
In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of
data.
In Java 1.0 version all IO operations were byte oriented, there was no other stream (character
stream). The java byte stream is defined by two abstract classes, InputStream and
OutputStream. The InputStream class used for byte stream based input operations, and the
OutputStream class used for byte stream based output operations.
The InputStream and OutputStream classes have several concreate classes to perform various IO
operations based on the byte stream.
The following picture shows the classes used for byte stream operations
CSE/NRCM
BYTE STREAM IN JAVA
InputStream class
The InputStream class has defined as an abstract class, and it has the following methods
which have
implemented
S.No. by its
Method concrete
with classes.
Description
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.
S.No. Method with Description
1 void write(int n)
It writes byte(contained in an int) to the output stream.
2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any reCsoS
urE
ce/sN
coR
nnC
ecM
ted with this output stream.
CHARACTER STREAM IN JAVA
In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream. The unicode set is basically a type of character set where each character corresponds
to a specific numeric value within the given character set, and every programming language
has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
The character stream was introduced in Java 1.1 version. The charater stream
The java character stream is defined by two abstract classes, Reader and Writer. The Reader
class used for character stream based input operations, and the Writer class used for charater
stream based output operations.
The Reader and Writer classes have several concreate classes to perform various IO operations
based on
the character stream.
CSE/NRCM
CHARACTER STREAM IN JAVA
Reader class
The Reader class has defined as an abstract class, and it has the following methods
which have
implemented by its concrete classes.
S.No. Method with Description
1 int read()
It reads the next character from the input stream.
2 int read(char[] cbuffer)
It reads a chunk of charaters from the input stream and store them in its byte array, cbuffer.
3 int read(char[] cbuf, int off, int len)
It reads charaters into a portion of an array.
4 int read(CharBuffer target)
It reads charaters into into the specified character buffer.
5 String readLine()
It reads a line of text. A line is considered to be terminated by any oneof a line feed ('\n'), a
carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.
6 boolean ready()
It tells whether the stream is ready to be read.
7 void close()
It closes the input stream and also frees any resources connected with this input stream.
CSE/NRCM
CHARACTER STREAM IN JAVA
Writer class
The Writer class has defined as an abstract class, and it has the following methods
which have
implemented by its concrete classes.
S.No. Method with Description
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
2 void write(char[] cbuf)
It writes a whole array(cbuf) to the output stream.
3 void write(char[] cbuf, int off, int len)
It writes a portion of an array of characters.
4 void write(int c)
It writes single character.
5 void write(String str)
It writes a string.
6 void write(String str, int off, int len)
It writes a portion of a string.
7 Writer append(char c)
It appends the specified character to the writer.
8 Writer append(CharSequence csq)
It appends the specified character sequence to the writer
9 Writer append(CharSequencecsq, int start, int end)
It appends a subsequence of the specified character sequence to the writer.
10 void close() CSE/NRCM
It closes the output stream and also frees any resources connected with this output stream.
CONSOLE I/O OPERATIONS IN
JAVA
Reading console input in java
In java, there are three ways to read console input. Using the 3 following ways, we can read
input data
from the console.
• Using BufferedReader class
• Using Scanner class
• Using Console class
Let's explore the each method to read data with example.
CSE/NRCM
CONSOLE I/O OPERATIONS IN
JAVA
2. Reading console input using Scanner class in java
Reading input data using the Scanner class is the most commonly used method. This way of the
reading method is used by wrapping the System.in (standard input stream) which is wrapped in a
Scanner, we can read input from the console.
The Scanner class has defined in the java.util package.
Consider the following example code to understand how to read console input using Scanner
class.
CSE/NRCM
CONSOLE I/O OPERATIONS IN
JAVA
3. Reading console input using Console class in java
Reading input data using the Console class is the most commonly used method. This class was
introduced
in Java 1.6 version.
The Console class has defined in the java.io package.
Consider the following example code to understand how to read console input using Console
class.
Example
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
} CSE/NRCM
}
CONSOLE I/O OPERATIONS IN
JAVA
3. Reading console input using Console class in java
Reading input data using the Console class is the most commonly used method. This class was
introduced
in Java 1.6 version.
The Console class has defined in the java.io package.
Consider the following example code to understand how to read console input using Console
class.
Example
import java.io.*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
} CSE/NRCM
}
CONSOLE I/O OPERATIONS IN
JAVA
Writing console output in java
In java, there are two methods to write console output. Using the 2 following methods, we can
write
output data to the console.
• Using print() and println() methods
• Using write() method
1. Writing console output using print() and println() methods
The PrintStream is a bult-in class that provides two methods print() and println() to write console
output.
The print() and println() methods are the most widely used methods for console
output. Both print() and println() methods are used with System.out stream.
The print() method writes console output in the same line. This method can be used with console
output
only.
The println() method writes console output in a separete line (new line). This method can be
used with
console ans also with other output sources.
Let's look at the following code to illustrate print() and println() methods.
Example
CSE/NRCM
CONSOLE I/O OPERATIONS IN
JAVA
Writing console output using write() method
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also acept escape sequences.
Let's look at the following code to illustrate write() method.
Example
CSE/NRCM
FILE CLASS IN JAVA
The File is a built-in class in Java. In java, the File class has been defined in the java.io package.
The File class represents a reference to a file or directory. The File class has various methods to
perform operations like creating a file or directory, reading from a file, updating file content, and
deleting a file or directory.
The File class in java has the following constructors.
S.No. Constructor with Description
1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract pathname. If the
given string isthe empty string, then the result is the empty abstract pathname.
2 File(String parent, String child)
It Creates a new File instance from a parent abstractpathname and a child pathname string. If parent is
null then the new File instance is created as if by invoking thesingle-argument File constructor on the
given child pathnamestring.
3 File(File parent, String child)
It creates a new File instance from a parent abstractpathname and a child pathname string. If parent is
null then the new File instance is created as if by invoking thesingle-argument File constructor on the
given child pathname string.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.
CSE/NRCM
FILE CLASS IN JAVA
The File class in java has the following
methods.
S.No. Methods with Description
1 String getName()
It returns the name of the file or directory that referenced by the current File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name a parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application; false otherwise.
11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to write to the file; false otherwise.
12 long length()
It returns the length of the current file.
13 long lastModified()
It returns the time that specifies the file was last modified.
14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if the named file already exists.
15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is successfully deleted; false otherwise.
CSE/NRCM
FILE READING & WRITING IN JAVA
In java, there multiple ways to read data from a file and to write data to a file. The most commonly
used
ways are as follows.
Using Byte Stream (FileInputStream and
FileOutputStream) Using Character Stream
(FileReader and FileWriter)
Let's look each of these ways.
CSE/NRCM
FILE READING & WRITING IN JAVA
File Handling using Character Stream
In java, we can use a character stream to handle files. The character stream has the following
built-in
classes to perform various operations on a file.
FileReader - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the character stream. The FileReader class provides a method read()
to read data from a file character by character.
FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a method write() to
write data to a file character by character.
Let's look at the following example program that reads data from a file and writes the same to
another file
using FIleReader and FileWriter classes.
CSE/NRCM
RANDOMACCESSFILE IN JAVA
In java, the java.io package has a built-in class RandomAccessFile that enables a file to be
accessed randomly. The RandomAccessFile class has several methods used to move the
cursor position in a file. A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
S.No. Constructor with Description
CSE/NRCM
SERIALIZATION AND DESERIALIZATION
IN JAVA
Deserialization in Java
In a java programming language, the Deserialization is achieved with the help of class
ObjectInputStream.
This class provides a method readObject() to deserializing an
object. We use the following steps to serialize an object.
Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
Step 2 - Create reference to ObjectInputStream object with file reference.
Step 3 - Use readObject() method to access serialized object, and typecaste it to destination type.
Step 4 - Close the FileInputStream and ObjectInputStream.
CSE/NRCM
ENUM IN JAVA
In java, an Enumeration is a list of named constants. The enum concept was introduced in
Java SE 5 version. The enum in Java programming the concept of enumeration is greatly
expanded with lot more new features compared to the other languages like C, and C++.
In java, the enumeration concept was defined based on the class concept. When we create an
enum in java, it converts into a class type. This concept enables the java enum to have
constructors, methods, and instance variables.
All the constants of an enum are public, static, and final. As they are static, we can access
directly using
enum name.
The main objective of enum is to define our own data types in Java, and they are said to be
enumeration
data types.
The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper
type and
reverses of it.
CSE/NRCM
AUTOBOXING AND UNBOXING IN
JAVA
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper class
object is
called autoboxing or simply boxing. For example, converting an int value to an Integer class
object. The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of the corresponding wrapper class.
🔔 We can also perform autoboxing manually using the method valueOf( ), which is provided by
every
wrapper class.
CSE/NRCM
GENERICS IN JAVA
The java generics is a language feature that allows creating methods and class which can
handle any type of data values. The generic programming is a way to write generalized
programs, java supports it by java generics.
The java generics is similar to the templates in the C++ programming
language. Most of the collection framework classes are generic classes.
The java generics allows only non-primitive type, it does not support primitive types like int, float,
char,
etc.
The java generics feature was introduced in Java 1.5 version. In java, generics used angular
brackets “< >”. In java, the generics feature implemented using the following.
Generic Method
Generic Classe
Generic methods in Java
The java generics allows creating generic methods which can work with a different type of data
values. Using a generic method, we can create a single method that can be called with
arguments of different types. Based on the types of the arguments passed to the generic
method, the compiler handles each method call appropriately.
Generic Class in Java
In java, a class can be defined as a generic class that allows creating a class that can work with
different
types.
CSE/NRCM
A generic class declaration looks like a non-generic class declaration, except that the class name
is
UNIT – III
EXCEPTION
HANDLING &
MULTITHREADIN
G
CSE/NRCM
EXCEPTION HANDLING IN JAVA
An exception in java programming is an abnormal situation that is araised during the program
execution.
In simple words, an exception is a problem that arises at the time of program execution.
When an exception occurs, it disrupts the program execution flow. When an exception occurs,
the program execution gets terminated, and the system generates an error. We use the
exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling mechanism with
a large
number of built-in classes to handle most of the exceptions automatically.
Java programming language has the following class hierarchy to support the exception
handling mechanism.
CSE/NRCM
EXCEPTION HANDLING IN JAVA
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as follows.
When we try to open a file that does not exist may lead to an
exception. When the user enters invalid input data, it may lead to an
exception.
When a network connection has lost during the program execution may lead to an
exception. When we try to access the memory beyond the allocated range may lead to an
exception.
The physical device problems may also lead to an exception.
Types of Exception
In java, exceptions have categorized into two types, and they are as follows.
Checked Exception - An exception that is checked by the compiler at the time of compilation is
called a
checked exception.
Unchecked Exception - An exception that can not be caught by the compiler but occurrs at the
time of
program execution is called an unchecked exception.
How exceptions handled in Java?
In java, the exception handling mechanism uses five keywords namely try, catch, finally, throw,
and throws.
We will learn all these concepts in this series of tutorials.
CSE/NRCM
EXCEPTION TYPES IN JAVA
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources,
networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
In the exception class hierarchy, the checked exception classes are the direct children of the
Exception
class. CSE/NRCM
The checked exception is also known as a compile-time exception
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked
exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors,
improper use of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException
class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
CSE/NRCM
Exception class
hierarchy
In java, the built-in classes used to handle exceptions have the following class
hierarchy.
EXCEPTION MODELS IN JAVA
In java, there are two exception models. Java programming language has two models of exception
handling. The exception models that java suports are as follows.
Termination
Model
Resumptive
Model
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may also
place the CSE/NRCM
try block in a while loop that keeps re-entering the try block util the result is satisfactory.
UNCAUGHT EXCEPTIONS IN JAVA
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but automatically
caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the
exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates
the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at the
following code.
CSE/NRCM
try AND catch IN JAVA
In java, the try and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but automatically
caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
can not use
try without atleast one catch, and catch alone can be used (catch without try is not
allowed). The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
CSE/NRCM
try AND catch IN JAVA
Multiple catch clauses
In java programming language, a try block may has one or more number of catch blocks. That
means a
single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
The multiple catch clauses are defined when the try block contains the code that may lead to
different
type of exceptions.
The try block generates only one exception at a time, and at a time only one catch block is
executed. When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.
The catch block with Exception class handler must be defined at the last.
CSE/NRCM
try AND catch IN JAVA
Nested try statements
The java allows to write a try statement inside another try statement. A try block within another try
block
is known as nested try block.
When there are nested try blocks, each try block must have one or more seperate catch blocks.
In case of nested try blocks, if an exception occured in the inner try block and it's catch blocks
are unable
to handle it then it transfers the control to the outer try's catch block to handle it.
CSE/NRCM
throw, throws, AND finally KEYWORDS
In IN JAVA
java, the keywords throw, throws, and finally are used in the exception handling concept. Let's
look at
each of these keywords.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instace must be throwable instance and it can be created dynamically using new
operator.
CSE/NRCM
throw, throws, AND finally KEYWORDS
IN keyword
throws JAVA in Java
The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically,
we use throws keyword followed by method declaration
When a method throws an exception, we must put the calling statement of method in try-catch
block.
CSE/NRCM
BUILT-IN EXCEPTIONS IN JAVA
The Java programming language has several built-in exception class that support exception
handling. Every
exception class is suitable to explain certain error situations at run
time. All the built-in exception classes in Java were defined a
package java.lang. Few built-in exceptions in Java are shown in the
following image.
CSE/NRCM
List of checked exceptions in Java
S. No. Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class
cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but that the
object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance method in
class Class , but the specified class object cannot be instantiated because it is an interface or is an
abstract class.
5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile time, a
NoSuchMethodException occurs during reflection when we try to access a method that does not exist.
CSE/NRCM
List of unchecked exceptions in Java
S. No. Exception Class with Description
1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
2 ArrayIndexOutOfBoundsException
It handles the situations like 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 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of object into an arrayof objects
4 AssertionError
It is used to indicate that an assertion has failed
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or inappropriateargument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has attempted to notify other threads that wait on an object's
monitor, without owning the specified monitor.
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriatetime.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the stateof the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array, vector , string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an arraywith negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is not appropriateor illegal.
14 SecurityException
It is thrown by the Java Card VirtualMachine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either negative, or greater than the size of the string itself.
UnsupportedOperationException
16 CSE/NRCM
sted operation is not supported.
It is thrown to indicate that the reque
CREATING OWN EXCEPTIONS IN
JAVA
The Java programming language allows us to create our own exception classes which are
basically
subclasses built-in class Exception.
To create our own exception class simply creates a class as a subclass of built-in
Exception class. We may create constructor in the user-defined exception class and pass
a string to Exception class constructor using super(). We can use getMessage() method
to access the string.
CSE/NRCM
MULTITHREADING IN JAVA
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a multithreading
program. Each part of this program is called a thread. Every thread defines a separate path of
execution in java. A thread is explained in different ways, and a few of them are as specified
below.
A thread is a light wieght process.
A thread may also be defined as follows.
A thread is a subpart of a process that can run individually.
In java, multiple threads can run at a time, which enables the java to write multitasking
programs. The multithreading is a specialized form of multitasking. All modern operating
systems support multitasking. There are two types of multitasking, and they are as follows.
Process-based multitasking
Thread-based multitasking
CSE/NRCM
Process-based multitasking Vs Thread-based
multitasking
Process-based multitasking Thread-based multitasking
It allows the computer to run two or more It allows the computer to run two or
programs concurrently more threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process is a larger unit. Thread is a part of process.
Process is heavy weight. Thread is light weight.
Process requires seperate address space for Threads share same address space.
each.
Process never gain access over idle time of Thread gain access over idle time of
CPU. CPU.
Inter process communication is expensive. Inter thread communication is not
expensive.
CSE/NRCM
JAVA THREAD MODEL
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases. A thread may in any of the states like new, ready or runnable,
running, blocked or wait, and dead or terminated state. The life cycle of a thread in java is shown
in the following figure.
CREATING THREADS IN JAVA
In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.
Using Thread class (by extending Thread class)
Uisng Runnable interface (by implementing Runnable interface)
CSE/NRCM
CREATING THREADS IN JAVA
Implementing Runnable interface
The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface
implemented by the Thread class that contains all the methods that are related to the
threads. To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Step-2: Override the run( ) method with the code that is to be executed by the thread. The run( )
method
must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class
constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.
CSE/NRCM
More about Thread class
The Thread class in java is a subclass of Object class and it implements Runnable interface.
The Thread
class is available inside the java.lang package. The Thread class has the following syntax.
class Thread extends Object implements Runnable{
...
}
CSE/NRCM
Thread class methods.
Method Description Return
Value
run( ) Defines actual task of the thread. void
start( ) It moves thre thread from Ready state to Running state by calling void
run( ) method.
setName(String) Assigns a name to the thread. void
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
CSE/NRCM
JAVA THREAD
SYNCHRONISATION
The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time, and
this is performed by using the concept called synchronization.
🔔 The synchronization is the process of allowing only one thread to access a shared resource at
a time.
Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at a
time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource. CSE/NRCM
Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines in
a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
The folllowing syntax is used to define a synchronized block.
Syntax
synchronized(object){
...
block code
...
}
CSE/NRCM
JAVA INTER THREAD
COMMUNICATION
Inter thread communication is the concept where two or more threads communicate to solve the
problem of polling. In java, polling is the situation to check some condition repeatedly, to take
appropriate action, once the condition is true. That means, in inter-thread communication, a thread
waits until a condition becomes true such that other threads can execute its task. The inter-thread
communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.
wait( )
notify( )
notifyAll( )
The following table gives detailed description about the above methods.
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the same
monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
CSE/NRCM
EVENT HANDLING
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The
java.awt.event package provides many event classes and Listener interfaces for event handling.
Java
EventEvent
ClassesclassesListener
and Listener interfaces
Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEven MouseWheelListener
t
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
CSE/NRCM
EVENT HANDLING
To perform Event Handling, we need to register the source with the listener. For registering the
component
with the Listener, many classes provide the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener
a){} public void addTextListener(TextListener
a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
CSE/NRCM
Delegation Event Model in Java
The Delegation Event model is defined to handle events in GUI programming languages. The GUI
stands for
Graphical User Interface, where a user graphically/visually interacts with the system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such as a
mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to
respond to functionality to the user. This is known as event handling.
CSE/NRCM
Delegation Event Model in Java
The key advantage of the Delegation Event Model is that the application logic is completely
separated from
the interface logic.
In this model, the listener must be connected with a source to receive the event notifications. Thus,
the events will only be received by the listeners who wish to receive them. So, this approach is more
convenient than the inheritance-based event model (in Java 1.0).
In the older model, an event was propagated up the containment until a component was
handled. This needed components to receive events that were not processed, and it took lots of
time. The Delegation Event model overcame this issue.
Events
Events Sources
Events Listeners
CSE/NRCM
Delegation Event Model in Java
Events
The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements. Some of the event generation activities are
moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item from
the list, and so on. We can also consider many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a timer expires,
counter
exceeded, system failures, or a task is completed, etc. We can define events for any of the applied
actions.
Event Sources
A source is an object that causes and generates an event. It generates an event when the internal
state of
the object is changed. The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each event contains its
registration method. Below is an example:
public void addTypeListener (TypeListener e1)
CSE/NRCM
Delegation Event Model in Java
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two
things; first, it must be registered with a source; however, it can be registered with several resources
to receive notification about the events. Second, it must implement the methods to receive and
process the received notifications. The methods that deal with the events are defined in a set of
interfaces. These interfaces can be found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the mouse is
dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.
Types of Events
The events are categories into the following two categories:
The Foreground Events:
The foreground events are those events that require direct interaction of the user. These types of
events are generated as a result of user interaction with the GUI component. For example, clicking
on a button, mouse movement, pressing a keyboard key, selecting an option from the list, etc.
The Background Events :
The Background events are those events that result from the interaction of the end-user. For
example, an
Operating system interrupts system failure (Hardware or Software).
To handle these events, we need an event handling mechanism that provides control over the
events and CSE/NRCM
responses.
HANDLING MOUSE EVENTS
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
CSE/NRCM
HANDLING OF KEYBOARD EVENTS
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The
KeyListener interface is found in java.awt.event package, and it has three methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
2. public abstract void keyReleased (KeyEvent It is invoked when a key has been
e); released.
3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.
Methods inherited
This interface inherits methods from the following
interface:
java.awt.EventListener
CSE/NRCM
Jbutton
Jbutton
The JButton class is used to create a labeled button that has platform independent
implementation. The
application result in some action when the button is pushed. It inherits AbstractButton class.
CSE/NRCM
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking
on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton
class.
Commonly used
Methods:
Methods Description
AccessibleContext It is used to get the AccessibleContext associated with
getAccessibleContext() this JCheckBox.
protectedString paramString() It returns a string representation of this JCheckBox.
CSE/NRCM
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple
options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Commonly used
Methods:
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.
CSE/NRCM
JOptionPane (Dialogs)
The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information or get
input from the user. The JOptionPane class inherits JComponent class.
CSE/NRCM
JAVA QUEUE INTERFACE
The Queue interface is a child interface of
the Collection interface. The Queue
interface is available inside the java.util
package. It defines the methods that are
commonly used by classes like
PriorityQueue and ArrayDeque.
CSE/NRCM
JAVA DEQUE INTERFACE
The Deque interface is a child interface of
the Queue interface. The Deque interface is
available inside the java.util package. It
defines the methods that are used by class
ArrayDeque.
CSE/NRCM
JAVA SORTEDSET INTERFACE
Set Interface
The Set interface is a child interface of
Collection interface. It does not defines any
additional methods of it, it has all the
methods that are inherited from Collection
interface. The Set interface does not allow
duplicates. Set is a generic interface.
SortedSet Interface
The SortedSet interface is a child interface
of the Set interface. The SortedSet interface
is available inside the java.util package. It
defines the methods that are used by
classes HashSet, LinkedHashSet, and
TreeSet.
🔔 The SortedSet interface extends Set
interface.
🔔 The SortedSet interface does not
allow duplicate elements.
🔔 The SortedSet interface organise the
elements based on the ascending order.
The SortedSet interface defines the following CSE/NRCM
methods.
JAVA NAVIGABLESET INTERFACE
The NavigableSet interface is a child
interface of the SortedSet interface. The
NavigableSet interface is available inside the
java.util package. It defines the methods
that are used by class TreeSet.
CSE/NRCM
JAVA ARRAYLIST CLASS
The ArrayList class is a part of java collection framework. It is available inside the java.util
package. The
ArrayList class extends AbstractList class and implements List interface.
The elements of ArrayList are organized as an array internally. The default size of an ArrayList
is 10.
The ArrayList class is used to create a dynamic array that can grow or shrunk as needed.
🔔 The ArrayList is a child class of AbstractList
🔔 The ArrayList implements interfaces like List, Serializable, Cloneable, and
RandomAccess.
🔔 The ArrayList allows to store duplicate data values.
🔔 The ArrayList allows to access elements randomly using index-based accessing.
🔔 The ArrayList maintains the order of insertion.
Accessing Items
The ArrayList class has the following methods to access items.
E get(int index) - Returns element at specified index from the ArrayList.
ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList that contails elements
from
specified startIndex to lastIndex-1 from the invoking ArrayList.
int indexOf(E element) - Returns the index value of given element first occurence in the
ArrayList.
int lastIndexOf(E element) - Returns the index value of given element last occurence in the
ArrayList. CSE/NRCM
JAVA ARRAYLIST CLASS
Updating Items
The ArrayList class has the following methods to update or change items.
E set(int index, E newElement) - Replace the element at specified index with
newElement in the invoking ArrayList.
ArrayList replaceAll(UnaryOperator e) - Replaces each element of invoking ArrayList with
the result of applying the operator to that element.
Removing Items
The ArrayList class has the following methods to remove items.
E remove(int index) - Removes the element at specified index in the invoking ArrayList.
boolean remove(Object element) - Removes the first occurence of the given element from the
invoking
ArrayList.
boolean removeAll(Collection c) - Removes the given collection of elements from the
invoking ArrayList.
void retainAll(Collection c) - Removes all the elements except the given collection of elements
from the
invoking ArrayList.
boolean removeIf(Predicate filter) - Removes all the elements from the ArrayList that satisfies
the given
predicate.
CSE/NRCM
void clear( ) - Removes all the elements from the ArrayList.
JAVA LINKEDLIST CLASS
The LinkedList class is a part of java collection framework. It is available inside the
java.util package. The LinkedList class extends AbstractSequentialList class and
implements List and Deque interface. The elements of LinkedList are organized as the
elements of linked list data structure.
The LinkedList class is used to create a dynamic list of elements that can grow or shrunk as
needed.
🔔 The LinkedList is a child class of AbstractSequentialList
🔔 The LinkedList implements interfaces like List, Deque, Cloneable, and Serializable.
🔔 The LinkedList allows to store duplicate data values.
🔔 The LinkedList maintains the order of insertion.
Adding Items
The LinkedList class has the following methods to add items.
boolean add(E element) - Appends given element to the List.
boolean addAll(Collection c) - Appends given collection of elements to the List.
void add(int position, E element) - Inserts the given element at specified position.
boolean addAll(int position, Collection c) - Inserts the given collection of elements at
specified
position.
void addFirst(E element) - Inserts the given element at beggining of
the list. void addLast(E element) - Inserts the given element at end
of the list. boolean offer(E element) - Inserts the given element at
end of the list.
boolean offerFirst(E element) - Inserts the given element at beggining of the list.
boolean offerLast(E element) - Inserts the given element at end of the list.
void push(E element) - Inserts the given element at beggining of the list.
CSE/NRCM
Operations on LinkedList
Accessing Items
The LinkedList class has the following methods to access items.
E get(int position) - Returns element at specified position from the LinkedList.
E element( ) - Returns the first element from the invoking
LinkedList. E getFirst( ) - Returns the first element from the
invoking LinkedList. E getLast( ) - Returns the last element
from the invoking LinkedList.
E peek( ) - Returns the first element from the invoking LinkedList.
E peekFirst( ) - Returns the first element from the invoking LinkedList, and returns null if list is
empty. E peekLast( ) - Returns the last element from the invoking LinkedList, and returns null
if list is empty. int indexOf(E element) - Returns the index value of given element first
occurence in the LinkedList. int lastIndexOf(E element) - Returns the index value of given
element last occurence in the LinkedList. E pop( ) - Returns the first element from the
invoking LinkedList.
Updating Items
The LinkedList class has the following methods to update or change items.
E set(int index, E newElement) - Replace the element at specified index with
newElement in the invoking LinkedList.
CSE/NRCM
Operations on LinkedList
Removing Items
The LinkedList class has the following methods to remove items.
E remove( ) - Removes the first element from the invoking LinkedList.
E remove(int index) - Removes the element at specified index in the invoking
LinkedList. boolean remove(Object element) - Removes the first occurrence of the
given element from the invoking LinkedList.
E removeFirst( ) - Removes the first element from the invoking LinkedList.
E removeLast( ) - Removes the last element from the invoking LinkedList.
boolean removeFirstOccurrence(Object element) - Removes from the first occurrence of
the given
element from the invoking LinkedList.
boolean removeLastOccurrence(Object element) - Removes from the last occurrence of
the given
element from the invoking LinkedList.
E poll( ) - Removes the first element from the LinkedList, and returns null if the list is
empty.
E pollFirst( ) - Removes the first element from the LinkedList, and returns null if the list
is empty. E pollLast( ) - Removes the last element from the LinkedList, and returns null
if the list is empty. E pop( ) - Removes the first element from the LinkedList.
void clear( ) - Removes all the elements from the LinkedList.
CSE/NRCM
JAVA PRIORITYQUEUE CLASS
The PriorityQueue class is a part of java collection framework. It is
available inside the java.util package. The PriorityQueue class extends
AbstractQueue class and implements Serializable interface.
The elements of PriorityQueue are organized as the elements of queue data structure, but it
does not follow FIFO principle. The PriorityQueue elements are organized based on the
priority heap.
The PriorityQueue class is used to create a dynamic queue of elements that can grow or
shrunk as
needed.
🔔 The PriorityQueue is a child class of AbstractQueue
🔔 The PriorityQueue implements interface Serializable.
🔔 The PriorityQueue allows to store duplicate data values, but not null values.
🔔 The PriorityQueue maintains the order of insertion.
🔔 The PriorityQueue used priority heap to organize its elements.
CSE/NRCM
JAVA PRIORITYQUEUE CLASS
PriorityQueue class constructors
The PriorityQueue class has the following constructors.
PriorityQueue( ) - Creates an empty PriorityQueue with the default initial capacity (11) that
orders its elements according to their natural ordering.
PriorityQueue(Collection c) - Creates a PriorityQueue with given collection of elements.
PriorityQueue(int initialCapacity) - Creates an empty PriorityQueue with the specified initial
capacity. PriorityQueue(int initialCapacity, Comparator comparator) - Creates an empty
PriorityQueue with the specified initial capacity that orders its elements according to the
specified comparator.
PriorityQueue(PriorityQueue pq) - Creates a PriorityQueue with the elements in the specified
priority
queue.
PriorityQueue(SortedSet ss) - Creates a PriorityQueue with the elements in the specified
SortedSet.
Operations on PriorityQueue
The PriorityQueue class allow us to perform several operations like adding, accesing, deleting,
updating,
looping, etc. Let's look at each operation with examples.
Adding Items
The PriorityQueue class has the following methods to add items.
boolean add(E element) - Appends given CSE/NRCM
element to the PriorityQueue.
boolean addAll(Collection c) - Appends given collection of elements to the PriorityQueue.
JAVA PRIORITYQUEUE CLASS
Accessing Items
The PriorityQueue class has the following methods to access items.
E element( ) - Returns the first element from the invoking PriorityQueue.
E peek( ) - Returns the first element from the invoking PriorityQueue, returns null if this queue is
empty.
Updating Items
The PriorityQueue class has no methods to update or change items.
Removing Items
The PriorityQueue class has the following methods to remove items.
E remove( ) - Removes the first element from the invoking PriorityQueue.
boolean remove(Object element) - Removes the first occurrence of the given element from the
invoking PriorityQueue.
boolean removeAll(Collection c) - Removes all the elements of specified collection from
the invoking PriorityQueue.
boolean removeIf(Predicate p) - Removes all of the elements of this collection that satisfy the
given
predicate.
boolean retainAll(Collection c) - Removes all the elements except those are in the specified
collection
from the invoking PriorityQueue.
CSE/NRCM
E poll( ) - Removes the first element from the PriorityQueue, and returns null if the list is empty.
void clear( ) - Removes all the elements from the PriorityQueue.
JAVA ARRAYDEQUE CLASS
The ArrayDeque class is a part of java collection framework. It is available inside the java.util
package.
The ArrayDeque class extends AbstractCollection class and implements Deque, Cloneable,
and Serializable interfaces.
The elements of ArrayDeque are organized as the elements of double ended queue data
structure. The ArrayDeque is a special kind of array that grows and allows users to add or
remove an element from both the sides of the queue.
The ArrayDeque class is used to create a dynamic double ended queue of elements that can
grow or
shrunk as needed.
🔔 The ArrayDeque is a child class of AbstractCollection
🔔 The ArrayDeque implements interfaces like Deque, Cloneable, and Serializable.
🔔 The ArrayDeque allows to store duplicate data values, but not null values.
🔔 The ArrayDeque maintains the order of insertion.
🔔 The ArrayDeque allows to add and remove elements at both the ends.
🔔 The ArrayDeque is faster than LinkedList and Stack.
Operations on ArrayDeque
The ArrayDeque class allow us to perform several operations like adding, accesing, deleting,
updating, looping, etc. Let's look at each operation with examples.
Adding Items
The ArrayDeque class has the following methods to add items.
boolean add(E element) - Appends given element to the ArrayDeque.
boolean addAll(Collection c) - Appends given collection of elements to the ArrayDeque.
void addFirst(E element) - Adds given element at front of the
ArrayDeque. void addLast(E element) - Adds given element at end
of the ArrayDeque. boolean offer(E element) - Adds given element
at end of the ArrayDeque.
boolean offerFirst(E element) - Adds given element at front of the
ArrayDeque. boolean offerLast(E element) - Adds given element at end
of the ArrayDeque. void push(E element) CSE/NRCM
- Adds given element at front
of the ArrayDeque.
JAVA ARRAYDEQUE CLASS
Accessing Items
The ArrayDeque class has the following methods to access items.
E element( ) - Returns the first element from the invoking
ArrayDeque. E getFirst( ) - Returns the first element from the
invoking ArrayDeque. E getLast( ) - Returns the last element
from the invoking ArrayDeque.
E peek( ) - Returns the first element from the invoking ArrayDeque, returns null if this queue is
empty. E peekFirst( ) - Returns the first element from the invoking ArrayDeque, returns null if
this queue is empty.
E peekLast( ) - Returns the last element from the invoking ArrayDeque, returns null if this
queue is
empty.
CSE/NRCM
JAVA ARRAYDEQUE CLASS
Updating Items
The ArrayDeque class has no methods to update or change items.
Removing Items
The ArrayDeque class has the following methods to remove items.
E remove( ) - Removes the first element from the invoking ArrayDeque.
E removeFirst( ) - Removes the first element from the invoking ArrayDeque.
E removeLast( ) - Removes the last element from the invoking ArrayDeque.
boolean remove(Object o) - Removes the specified element from the invoking ArrayDeque.
boolean removeFirstOccurrence(Object o) - Removes the first occurrence of the specified
element in
this ArrayDeque.
boolean removeLastOccurrence(Object o) - Removes the last occurrence of the specified
element in
this ArrayDeque.
boolean removeIf(Predicate p) - Removes all of the elements of ArrayDeque collection that
satisfy the
given predicate.
boolean retainAll(Collection c) - Removes all of the elements of ArrayDeque collection
except specified collection of elements.
E poll( ) - Removes the first element from the ArrayDeque, and returns null if the list is empty.
E pollFirst( ) - Removes the first element from the ArrayDeque, and returns null if the list
is empty. E pollLast( ) - Removes the last element from the ArrayDeque, and returns null
JAVA HASHSET CLASS
The HashSet class is a part of java collection framework. It is available inside the java.util
package. The
HashSet class extends AbstractSet class and implements Set interface.
The elements of HashSet are organized using a mechanism called hashing. The HashSet is
used to create hash table for storing set of elements.
The HashSet class is used to create a collection that uses a hash table for storing set of
elements.
🔔 The HashSet is a child class of AbstractSet
🔔 The HashSet implements interfaces like Set, Cloneable, and Serializable.
🔔 The HashSet does not allows to store duplicate data values, but null values are allowed.
🔔 The HashSet does not maintains the order of insertion.
🔔 The HashSet initial capacity is 16 elements.
🔔 The HashSet is best suitable for search operations.
CSE/NRCM
JAVA HASHSET CLASS
HashSet class constructors
The HashSet class has the following constructors.
HashSet( ) - Creates an empty HashSet with the default initial capacity (16).
HashSet(Collection c) - Creates a HashSet with given collection of elements.
HashSet(int initialCapacity) - Creates an empty HashSet with the specified initial
capacity. HashSet(int initialCapacity, float loadFactor) - Creates an empty HashSet
with the specified initial capacity and loadFactor.
Operations on HashSet
The HashSet class allow us to perform several operations like adding, accesing, deleting,
updating,
looping, etc. Let's look at each operation with examples.
Adding Items
The HashSet class has the following methods to add items.
boolean add(E element) - Inserts given element to the HashSet.
boolean addAll(Collection c) - Inserts given collection of elements to the HashSet.
CSE/NRCM
MAP INTERFACE CLASSES IN JAVA
The java collection framework has an interface Map that is available inside the java.util
package. The
Map interface is not a subtype of Collection interface.
The Map interface has the following three classes.
Class Description
HashMap It implements the Map interface, but it doesn't maintain any order.
LinkedHashMap It implements the Map interface, it also extends HashMap class. It maintains the insertion order.
TreeMap It implements the Map and SortedMap interfaces. It maintains the ascending order.
CSE/NRCM
HashMap Class
The HashMap class is a child class of AbstractMap, and it implements the Map interface. The
HashMap
is used to store the data in the form of key, value pair using hash table concept.
Key Properties of HashMap
HashMap is a child class of AbstractMap class.
HashMap implements the interfeaces Map, Cloneable, and
Serializable. HashMap stores data as a pair of key and value.
HashMap uses Hash table concept to store the data.
HashMap does not allow duplicate keys, but values may be
repeated. HashMap allows only one null key and multiple null
values.
HashMap does not follow any oreder.
HashMap has the default capacity 16 entries.
CSE/NRCM
UNIT – V
APPLETS
CSE/NRCM
The Basic GUI Application
import javax.swing.JOptionPane;
public class HelloWorldGUI1
{
public static void main(String[] args) {
JOptionPane.showMessageDialog( null, "Hello
World!" );
}
When this program is run, a window appears on the screen that contains the message “Hello
World!”. The window also contains an “OK” button for the user to click after reading the
message. When the user clicks this button, the window closes and the program ends. By the
way, this program can be placed in a file named HelloWorldGUI1.java, compiled, and run just
like any other Java program.
CSE/NRCM
LIMITATIONS OF AWT
Summary on limitations of AWT
CSE/NRCM
MVC ARCHITECTURE
In real time applications, in the case of server side programming one must follow the
architecture to develop a distributed application.To develop any distributed application, it is
always recommended to follow either 3-tier architecture or 2-tier architecture or n-tier
architecture.
Model :
This is the data layer which consists of the business logic of the
system. It consists of all the data of the application
It also represents the state of the application.
It consists of classes which have the connection to the database.
The controller connects with model and fetches the data and sends to the view layer.
The model connects with the database as well and stores the data into a database which is
connected
to it. CSE/NRCM
MVC ARCHITECTURE
Model :
This is the data layer which consists of the business logic of the system.
It consists of all the data of the application
It also represents the state of the application.
It consists of classes which have the connection to the database.
The controller connects with model and fetches the data and sends to the view layer.
The model connects with the database as well and stores the data into a database which is
connected to it.
View :
This is a presentation layer.
It consists of HTML, JSP, etc. into it.
It normally presents the UI of the application.
It is used to display the data which is fetched from the controller which in turn fetching data from
model
layer classes.
This view layer shows the data on UI of the application.
Controller:
It acts as an interface between View and Model.
It intercepts all the requests which are coming from the view layer.
It receives the requests from the view layer and processes the requests and does the necessary
validation for
the request. CSE/NRCM
This requests is further sent to model layer for data processing, and once the request is processed, it
COMPONENTS
Component is an object having a graphical representation that can be displayed on the screen and
that can
interact with the user. For examples buttons, checkboxes, list and scrollbars of a graphical user
interface.
A Component is an abstract super class for GUI controls and it represents an object with
graphical representation.
CSE/NRCM
COMPONENTS
Every AWT controls inherits properties from Component
class
Component Description
Label The easiest control to use is a label. A label is an object of type Label, and it contains a string,which it
displays. Labels are passive controls that do not support any interaction with theuser. Label defines the
following constructors
Button This class creates a labeled button.
Check Box A check box is a graphical component that can be in either an on (true) or off (false) state.
Check Box Group The CheckboxGroup class is used to group the set of checkbox.
List The List component presents the user with a scrolling list of text items.
Text Field A TextField object is a text component that allows for the editing of a single line of text.
Text Area A TextArea object is a text component that allows for the editing of a multiple lines of text.
Choice A Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the
menu.
Canvas A Canvas control represents a rectangular area where application can draw something or can receive inputs
created by user.
Image An Image control is superclass for all image classes representing graphical images.
Scroll Bar A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
Dialog A Dialog control represents a top-level window with a title and a border used to take some form of input
from the user.
File Dialog A FileDialog control represents a dialog window from which the user can select a file.
CSE/NRCM
COMPONENTS
Commonly used Methods of Component
class:
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(intwidth,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
void remove(Component obj) Here, obj is a reference to the control you want to
remove.
void removeAll( ). You can remove all controls by
CSE/NRCM
CONTAINERS
Abstract Windowing Toolkit (AWT): Abstract Windowing Toolkit (AWT) is used for GUI
programming in java.
CSE/NRCM
CONTAINERS
Container:
The Container is a component in AWT that can contain another components like buttons, textfields,
labels
etc. The classes that extends Container class are known as container.
Window:
The window is the container that have no borders and menubars. You must use frame, dialog or
another
window for creating a window.
Panel:
The Panel is the container that doesn't contain title bar and MenuBars. It can have other
components like
button, textfield etc.
Frame:
The Frame is the container that contain title bar and can have MenuBars. It can have other
components like
button, textfield etc.
CSE/NRCM
Frame
There are two ways to create a frame:
By extending Frame class (inheritance)
By creating the object of Frame class (association)
CSE/NRCM
LAYOUT MANAGERS
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
CSE/NRCM
BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west,
and center. Each region (area) may contain one component only. It is the default layout of a
frame or window. The BorderLayout provides five constants for each region:
public static final int
NORTH public static final
int SOUTH public static
final int EAST public static
final int WEST public
static final int CENTER
CSE/NRCM
FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the
default layout of the applet or panel.
Fields of FlowLayout
class public static final int
LEFT public static final int
RIGHT public static final int
CENTER public static final
int LEADING public static
final int TRAILING
CSE/NRCM
GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is
displayed in each rectangle.
CSE/NRCM
CardLayout
The Java CardLayout class manages the components in such a manner that only one component
is visible at
a time. It treats each component as a card that is why it is known as CardLayout.
public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given
container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with the
given name.
CSE/NRCM
GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline. The components may not be of the same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as its
display area. Each component associates an instance of GridBagConstraints. With the help of the
constraints object, we arrange the component's display area on the grid. The GridBagLayout
manages each component's minimum and
preferred sizes in order to determine the component's size. GridBagLayout components are also
arranged in
the rectangular grid but can have many different sizes and can occupy multiple rows or columns.
Constructor
Modifier and Type Field Description
GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
double[] columnWeights It is used to hold the overrides to the column weights.
int[] columnWidths It is used to hold the overrides to the column minimum width.
protected comptable It is used to maintains the association between a component and its
Hashtable<Component,GridBagConstr gridbag constraints.
aints>
protected GridBagConstraints defaultConstraints It is used to hold a gridbag constraints instance containing the
default values.
protected GridBagLayoutInfo layoutInfo It is used to hold the layout information for the gridbag.
protected static int MAXGRIDSIZE No longer in use just for backward compatibility
protected static int MINSIZE It is smallest grid that can be laid out by the grid bag layout.
protectedstatic int PREFERREDSIZE It is preferred grid size that can be laid out by the grid bag layout.
int[] rowHeights It is used to hold the overrides to the row minimum heights.
double[] rowWeights It is used to hold the overrides to the row weights.
CSE/NRCM
Thank
you
CSE/NRCM