Java
Java
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 1
1 - Basics of Java
Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. This code can be executed on any system that implements
the Java Virtual Machine. Most previous attempts at cross-platform solutions have done so at
the expense of performance. As explained earlier, the Java bytecode was carefully designed so
that it would be easy to translate directly into native machine code for very high performance
by using a just-in-time compiler. Java run-time systems that provide this feature lose none of
the benefits of the platform-independent code.
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a file.
Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke
methods across a network.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time. This makes it possible to dynamically link
code in a safe and expedient manner. This is crucial to the robustness of the Java environment,
in which small fragments of bytecode may be dynamically updated on a running system.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 2
1 - Basics of Java
Relational Operators
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then (A == B) is not
condition becomes true. true.
!= Checks if the values of two operands are equal or not, if values are not (A != B) is
equal then condition becomes true. true.
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is not
of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is
right operand, if yes then condition becomes true. true.
Relational Operators in JAVA, consider A as 10 & B as 20
Bitwise Operators
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is 0000
exists in both operands. 1100
| Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is 0011
operand. 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is 0011
operand but not both. 0001
~ Binary Ones Complement Operator is unary and has (~A ) will give -61 which is 1100
the effect of 'flipping' bits. 0011 in 2's complement form due
to a signed binary number.
<< Binary Left Shift Operator. The left operands value A << 2 will give 240 which is 1111
is moved left by the number of bits specified by the 0000
right operand.
>> Binary Right Shift Operator. The left operands value A >> 2 will give 15 which is 1111
is moved right by the number of bits specified by
the right operand.
>>> Shift right zero fill operator. The left operands value A >>>2 will give 15 which is 0000
is moved right by the number of bits specified by 1111
the right operand and shifted values are filled up
with zeros.
Bitwise Operators in JAVA, consider A as 60 & B as 13
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 3
1 - Basics of Java
Logical Operators
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the (A && B) is
condition becomes true. false.
|| Called Logical OR Operator. If any of the two operands are non-zero, (A || B) is
then the condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its !(A && B) is
operand. If a condition is true then Logical NOT operator will make false. true.
Logical Operators in JAVA, consider A as true & B as false
Assignment Operators
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will assign
operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C
left operand and assign the result to left operand =C+A
-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C
from the left operand and assign the result to left operand =C-A
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C
operand with the left operand and assign the result to left =C*A
operand
/= Divide AND assignment operator, It divides left operand with C /= A is equivalent to C
the right operand and assign the result to left operand =C/A
%= Modulus AND assignment operator, It takes modulus using C %= A is equivalent to
two operands and assign the result to left operand C=C%A
<<= Left shift AND assignment operator C <<= 2 is same as C = C
<< 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C
>> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C
&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^
2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C |
2
Assignment Operators in JAVA
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 4
1 - Basics of Java
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 5
1 - Basics of Java
o It is useful when int type is not large enough to hold the desired value
o Example: long soconds = 1234124231;
char
o It is 16-bit (2 Byte) type
o Range: 0 to 65,536
o Example: char first = ‘A’; char second = 65;
float
o It is 32-bit (4-Byte) type
o It specifies a single-precision value
o Example: float price = 1234.45213f
double
o It uses 64-bit (8-Byte)
o All math functions such as sin(),cos(),sqrt() etc… returns double value
o Example: double pi = 3.14141414141414;
boolean
o The boolean data type has only two possible values: true and false.
o This data type represents one bit of information, but its "size" isn't something that's
precisely defined.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 6
2 – Array & String
Arrays in Java
One-Dimensional Arrays
A One-dimensional array is essentially a list of like-typed variables.
Array declaration:
type var-name[];
Example:
Int student_marks[];
Above example will represent array with no value (null) To link student_marks with actual,
physical array of integers, we must allocate one using new keyword.
Example:
int student_marks[] = new int[20];
Multi-Dimensional Arrays
A In java, Multidimensional arrays are actually array of arrays.
Example:
int runPerOver[][] = new int[50][6];
Manually allocate different size:
Int runPerOver[][] = new int[3][];
runPerOver[0] = new int[6];
runPerOver[1] = new int[7];
runPerOver[2] = new int[6];
Initialization :
Int runPerOver[][] = {
{0,4,2,1,0,6},
{1,56,4,1,2,4,0},
{6,4,1,0,2,2},
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 7
2 – Array & String
Less efficient — you need to create a new string and throw away the old one
even for small changes.
Empty Strings:
o An empty String has no characters. It’s length is 0.
String word1 = "";
String word2 = new String();
Not the same as an uninitialized String (null string)
private String errorMsg;
Copy Constructors :
o Copy constructor creates a copy of an existing String. Also rarely used.
o Not the same as an assignment.
o Copy Constructor: Each variable points to a different copy of the String.
Other Constructors :
o Most other constructors take an array as a parameter to create a String.
char[] letters = {‘J’, ‘a’, ‘v’, ‘a’};
String word = new String(letters);
Methods of String Class in JAVA :
Method Description
char charAt(int index) charAt() function returns the character located at the
specified index.
int indexOf(char ch) Returns the index within this string of the first occurrence of
the specified character.
int compareTo(String o) Compares this String to another Object.
String concat(String str) Concatenates the specified string to the end of this string.
int length() The string length() method returns length of the string.
String trim() The string trim() method eliminates white spaces before
and after string.
String replace(char oc, The string replace() method replaces all occurrence of first
char nc) sequence of character with second sequence of character.
toUpperCase() The java string toUpperCase() method converts this string
into uppercase letter.
toLowerCase() string toLowerCase() method into lowercase letter.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 8
2 – Array & String
o It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
o They are safe for use by multiple threads.
o Every string buffer has a capacity.
Class constructors
Sr. No. Constructor & Description
1 StringBuffer()
This constructs a string buffer with no characters in it and an initial capacity of 16
characters.
2 StringBuffer(CharSequence seq)
This constructs a string buffer that contains the same characters as the specified
CharSequence.
3 StringBuffer(int capacity)
This constructs a string buffer with no characters in it and the specified initial capacity.
4 StringBuffer(String str)
This constructs a string buffer initialized to the contents of the specified string.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 9
3 – Classes, Objects and Methods
Classes in Java.
A class is a blue print from which individual objects are created.
A sample of a class is given below:
public class Dog{
String breed;
int age;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
Objects in Java.
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
Let us now look deep into what are objects. If we consider the real-world we can find many
objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging, running
If you compare the software object with a real world object, they have very similar
characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 10
3 – Classes, Objects and Methods
Constructor in Java.
Every class has a constructor. If we do not explicitly write a constructor for a class the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
Example of a constructor is given below:
public class Puppy{
public Puppy(){
}
Method overloading.
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods
are said to be overloaded, and the process is referred to as method overloading.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call. Thus, overloaded
methods must differ in the type and/or number of their parameters. While overloaded methods
may have different return types, the return type alone is insufficient to distinguish two versions
of a method.
When Java encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
Example of Method Overloading by changing the no. of arguments:
class Calculation{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(int a,int b,int c){
System.out.println(a+b+c);
}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 11
3 – Classes, Objects and Methods
Example of Method Overloading by changing data type of argument
class Calculation2{
void sum(int a,int b){
System.out.println(a+b);
}
void sum(double a,double b){
System.out.println(a+b);
}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
this keyword.
Java defines the this keyword. this can be used inside any method to refer to the current object.
this is always a reference to the object on which the method was invoked.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
this. width = w;
this. height = h;
this. depth = d;
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the
invoking object.
While it is redundant in this case, this is useful in other contexts,
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
static keyword.
Static means one per class, not one for each object no matter how many instance of a class
might exist.
This means that you can use them without creating an instance of a class.Static methods are
implicitly
final, because overriding is done based on the type of the object, and static methods are
attached to a class, not an object.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 12
3 – Classes, Objects and Methods
A static method in a superclass can be shadowed by another static method in a subclass, as long
as the original method was not declared final. However, you can't override a static method with
a nonstatic method.
In other words, you can't change a static method into an instance method in a subclass.
Private
Default
Protected
Public
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 13
3 – Classes, Objects and Methods
Abstract Class.
A Java abstract class is a class which cannot be instantiated, meaning you cannot create new
instances of an abstract class.
The purpose of an abstract class is to function as a base for subclasses.
Declaring an Abstract Class in Java
public abstract class MyAbstractClass {
}
Abstract Methods:
An abstract class can have abstract methods. You declare a method abstract by adding the
abstract keyword in front of the method declaration. Here is a Java abstract method
example:
public abstract class MyAbstractClass {
public abstract void abstractMethod();
}
An abstract method has no implementation. It just has a method signature. Just like methods in
a Java interface.
If a class has an abstract method, the whole class must be declared abstract. Not all methods in
an abstract class have to be abstract methods. An abstract class can have a mixture of abstract
and non-abstract methods.
Subclasses of an abstract class must implement (override) all abstract methods of its abstract
superclass. The non-abstract methods of the superclass are just inherited as they are. They can
also be overridden, if needed.
The Purpose of Abstract Classes:
The purpose of abstract classes is to function as base classes which can be extended by
subclasses to create a full implementation.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 14
4 – Inheritance and Interfaces
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes.
When you inherit from an existing class, you can reuse methods and fields of parent class, and
you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a
type of Employee.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 15
4 – Inheritance and Interfaces
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Multiple inheritance and Hybrid inheritance is not supported in java through class.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 16
4 – Inheritance and Interfaces
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
When an overridden method is called from within a subclass, it will always refer to the version
of that method defined by the subclass. The version of the method defined by the superclass
will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 17
4 – Inheritance and Interfaces
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Final keyword
The final keyword in java is used to restrict the user.
The final keyword can be used in many contexts. Final can be:
1. Variable
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
Example:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Output: Compile Time Error
2. Method
If you make any method as final, you cannot override it.
Example:
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 18
4 – Inheritance and Interfaces
System.out.println("running safely with 100kmph");
}
Interface in java.
Using the keyword interface, you can fully abstract a class’ interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body.
In practice, this means that you can define interfaces that don’t make assumptions about how
they are implemented.
Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
Syntax of interface:
// interface syntax.
Interface myInterface
{
int a=10;
public int getBalance();
public void setBalance(int a);
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 19
4 – Inheritance and Interfaces
To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation.
By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
Interfaces are designed to support dynamic method resolution at run time.
Normally, in order for a method to be called from one class to another, both classes need to be
present at compile time so the Java compiler can check to ensure that the method signatures
are compatible.
All the variables defined in the interface are default final and cannot be changed in subclass.
instanceof keyword.
Sometimes, knowing the type of an object during run time is useful. For example, you might
have one thread of execution that generates various types of objects, and another thread that
processes these objects.
In this situation, it might be useful for the processing thread to know the type of each object
when it receives it. Another situation in which knowledge of an object’s type at run time is
important involves casting.
In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile
time. However, casts involving class hierarchies can produce invalid casts that can be detected
only at run time.
For example, a superclass called A can produce two subclasses, called B and C. Thus, casting a B
object into type A or casting a C object into type A is legal, but casting a B object into type C (or
vice versa) isn’t legal. Because an object of type A can refer to objects of either B or C, how can
you know, at run time, what type of object is actually being referred to before attempting the
cast to type C? It could be an object of type A, B, or C. If it is an object of type B, a run-time
exception will be thrown. Java provides the run-time operator instanceof to answer this
question.
The instanceof operator has this general form:
object instanceof type
The following program demonstrates instanceof:
class A
{
public static void main(String[] ar)
{
String a = “hello”;
Double d = new Double(10.0);
If(a instanceof String)
{
System.out.println(“A is a instance of String”);
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 21
4 – Inheritance and Interfaces
B b = new B(); // object of type B
C c = new C(); // object of type C
This program creates one superclass called A and two subclasses of it, called B and C. Subclasses
B and C override callme( ) declared in A. Inside the main( ) method, objects of type A, B, and C
are declared. Also, a reference of type A, called r, is declared. The program then in turn assigns
a reference to each type of object to r and uses that reference to invoke callme( ). As the output
shows, the version of callme( ) executed is determined by the type of object being referred to at
the time of the call. Had it been determined by the type of the reference variable, r, you would
see three calls to A’s callme( ) method.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 22
5 – Package
Use of Package
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package:
When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be put into an unnamed package.
Example:
package animals;
interface Animal {
public void eat();
}
import animals.Animal;
// OR import animals.*; to import all the classes in the animals package
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member
of a class directly. There is no need to qualify it by the class name.
Advantage of static import:
o Less coding is required if you have access any static member of a class oftenly.
Disadvantage of static import:
o If you overuse the static import feature, it makes the program unreadable and
unmaintainable.
Example of static import:
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
}
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 24
6 – Exception Handling
Checked Exception: These exception are the object of the Exception class or any of its
subclasses except Runtime Exception class. These condition arises due to invalid input, problem
with your network connectivity and problem in database.java.io.IOException is a checked
exception. This exception is thrown when there is an error in input-output operation. In this
case operation is normally terminated.
o List of Checked Exceptions
Exception Reason for Exception
This Exception occurs when Java run-
ClassNotFoundException time system fail to find the specified
class mentioned in the program
This Exception occurs when you
Instantiation Exception create an object of an abstract class
and interface
This Exception occurs when you
Illegal Access Exception create an object of an abstract class
and interface
This Exception occurs when the
Not Such Method Exception method you call does not exist in
class
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 25
6 – Exception Handling
Unchecked Exception: These Exception arises during run-time ,that occur due to invalid
argument passed to method. The java Compiler does not check the program error during
compilation. For Example when you divide a number by zero, run-time exception is raised.
o List of Unchecked Exceptions
Exception Reason for Exception
These Exception occurs, when you
Arithmetic Exception divide a number by zero causes an
Arithmetic Exception
These Exception occurs, when you
Array Store Exception assign an array which is not compatible
with the data type of that array
These Exception occurs, when you
Array Index Out Of Bounds
assign an array which is not compatible
Exception
with the data type of that array
These Exception occurs, when you try
to implement an application without
Null Pointer Exception
referencing the object and allocating
to a memory
These Exception occurs, when you try
to convert a string variable in an
Number Format Exception incorrect format to integer (numeric
format) that is not compatible with
each other
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 26
6 – Exception Handling
Example:
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try
{
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This program gets two chances to deal with the same error. First, main( ) sets up an exception
context and then calls demoproc( ). The demoproc( ) method then sets up another
exceptionhandling context and immediately throws a new instance of NullPointerException,
which is caught on the next line. The exception is then rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of Java’s standard exception objects.
Pay close attention to this line:
throw new NullPointerException("demo");
Here, new is used to construct an instance of NullPointerException. Many of Java’s builtin run-
time exceptions have at least two constructors: one with no parameter and one that takes a
string parameter. When the second form is used, the argument specifies a string that describes
the exception. This string is displayed when the object is used as an argument to print( ) or
println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 28
6 – Exception Handling
Finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the finally block will execute even if no catch
statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also executed just before the
method returns.
This can be useful for closing file handles and freeing up any other resources that might have
been allocated at the beginning of a method with the intent of disposing of them before
returning. The finally clause is optional. However, each try statement requires at least one catch
or a finally clause.
Here is an example program that shows three methods that exit in various ways, none
without executing their finally clauses:
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 29
6 – Exception Handling
System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally
clause is executed on the way out. procB( )’s try statement is exited via a return statement. The
finally clause is executed before procB( ) returns. In procC( ), the try statement executes
normally, without error. However, the finally block is still executed.
Output:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 30
7 – Multithreaded Programming
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 31
7 – Multithreaded Programming
o Timed waiting: A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
o Terminated: A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 33
7 – Multithreaded Programming
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 34
7 – Multithreaded Programming
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 35
7 – Multithreaded Programming
Here, object is a reference to the object being synchronized. A synchronized block ensures that
a call to a method that is a member of object occurs only after the current thread has
successfully entered object's monitor.
Here is an example, using a synchronized block within the run( ) method:
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 36
7 – Multithreaded Programming
Output:
[Hello]
[World]
[Synchronized]
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 37
8 – IO Programming
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream in
the java.io package supports many data such as primitives, Object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. there are two kinds of Streams
o InPutStream : The InputStream is used to read data from a source.
o OutPutStream : The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this tutorial
covers very basic functionality related to streams and I/O.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most frequently used classes are
, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an input file into an
output file:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 38
8 – IO Programming
}
}
}
}
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character
streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most frequently used
classes are FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file
(having unicode characters) into an output file:
Example:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Standard Streams
All the programming languages provide support for standard I/O where user's program can take
input from a keyboard and then produce output on the computer screen.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 39
8 – IO Programming
If you are aware if C or C++ programming languages, then you must be aware of three standard
devices STDIN, STDOUT and STDERR. Similar way Java provides following three standard
streams.
o Standard Input: This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
o Standard Output: This is used to output the data produced by the user's program
and usually a computer screen is used to standard output stream and represented as
System.out.
o Standard Error: This is used to output the error data produced by the user's program
and usually a computer screen is used to standard error stream and represented as
System.err.
Reader
The Java Reader is the base class of all Reader's in the Java IO API. Subclasses include a
BufferedReader, PushbackReader, InputStreamReader, StringReader and several others.
Here is a simple Java IO Reader example:
while(data != -1){
data = reader.read();
Writer
The Java Writer class is the base class of all Writers in the Java IO API. Subclasses include
BufferedWriter and PrintWriter among others.
Here is a simple Java IO Writer example:
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 40
8 – IO Programming
writer.close();
File Class
Java File class represents the files and directory pathnames in an abstract manner. This class is
used for creation of files and directories, file searching, file deletion etc.
The File object represents the actual file/directory on the disk. Below given is the list of
constructors to create a File object.
SR.NO Methods with Description
2 File(String pathname)
This constructor creates a new File instance by converting the given pathname
string into an abstract pathname.
4 File(URI uri)
This constructor creates a new File instance by converting the given file: URI
into an abstract pathname.
Once you have File object in hand then there is a list of helper methods which can be used
manipulate the files.
SR.NO Methods with Description
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 41
8 – IO Programming
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 42
8 – IO Programming
FileOutputStream
Java FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented
data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
Example :
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e)
{
system.out.println(e);
}
}
}
FileInputStream
Java FileInputStream class obtains input bytes from a file.It is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video etc.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 43
8 – IO Programming
Example :
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}
catch(Exception e){
system.out.println(e);
}
}
}
InputStreamReader
The Java.io.InputStreamReader class is a bridge from byte streams to character streams.It reads
bytes and decodes them into characters using a specified charset.
Constructors:
S.N. Constructor & Description
1 InputStreamReader(InputStream in)
This creates an InputStreamReader that uses the default charset.
Methods:
S.N. Method & Description
1 void close()
This method closes the stream and releases any system resources associated
with it.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 44
8 – IO Programming
2 String getEncoding()
This method returns the name of the character encoding being used by this
stream.
3 int read()
This method reads a single character.
5 boolean ready()
This method tells whether this stream is ready to be read.
OutputStreamWriter
The Java.io.OutputStreamWriter class is a bridge from character streams to byte streams.
Characters written to it are encoded into bytes using a specified charset.
Constructors:
S.N. Constructor & Description
1 OutputStreamWriter(OutputStream out)
This creates an OutputStreamWriter that uses the default character encoding.
Methods:
S.N. Method & Description
1 void close()
This method closes the stream, flushing it first.
2 void flush()
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 45
8 – IO Programming
3 String getEncoding()
This method returns the name of the character encoding being used by this
stream.
5 void write(int c)
This method writes a single character.
FileReader
This class inherits from the InputStreamReader class. FileReader is used for reading streams of
characters.
This class has several constructors to create required objects. Below given are the list of
constructors provided by the FileReader class.
Contractors:
SR.NO Constructors and Description
1 FileReader(File file)
This constructor creates a new FileReader, given the File to read
from.
2 FileReader(FileDescriptor fd)
This constructor creates a new FileReader, given the FileDescriptor to
read from.
3 FileReader(String fileName)
This constructor creates a new FileReader, given the name of the file
to read from.
Methods:
SR.NO Methods with Description
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 46
8 – IO Programming
Reads a single character. Returns an int, which represents the character read.
Example:
import java.io.*;
file.createNewFile();
writer.flush();
writer.close();
for(char c : a)
fr.close();
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 47
8 – IO Programming
FileWriter
This class inherits from the OutputStreamWriter class. The class is used for writing streams of
characters.
This class has several constructors to create required objects. Below given is the list of them
Contractors:
SR.NO Constructors and Description
1 FileWriter(File file)
This constructor creates a FileWriter object given a File object.
3 FileWriter(FileDescriptor fd)
This constructor creates a FileWriter object associated with the given
file descriptor.
4 FileWriter(String fileName)
This constructor creates a FileWriter object, given a file name.
Methods:
SN Methods with Description
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 48
8 – IO Programming
BufferedReader
The Java.io.BufferedReader class reads text from a character-input stream, buffering characters
so as to provide for the efficient reading of characters, arrays, and lines.Following are the
important points about BufferedReader:
o The buffer size may be specified, or the default size may be used.
o Each read request made of a Reader causes a corresponding read request to be made of
the underlying character or byte stream.
Constructors:
S.N. Constructor & Description
1 BufferedReader(Reader in)
This creates a buffering character-input stream that uses a default-sized
input buffer.
Methods:
S.N. Method & Description
1 void close()
This method closes the stream and releases any system resources associated
with it.
2 int read()
This method reads a single character.
4 String readLine()
This method reads a line of text.
5 void reset()
This method resets the stream.
6 long skip(long n)
This method skips characters.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 49
8 – IO Programming
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 50
9 – Collection Classes
List Interface.
The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements.
o Elements can be inserted or accessed by their position in the list, using a zero-based
index.
o A list may contain duplicate elements.
o In addition to the methods defined by Collection, List defines some of its own, which
are summarized in the following below Table.
o Several of the list methods will throw an UnsupportedOperationException if the
collection cannot be modified, and a ClassCastException is generated when one
object is incompatible with another.
Methods :
SN Methods with Description
6 ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 51
9 – Collection Classes
Removes the element at position index from the invoking list and returns the deleted
element. The resulting list is compacted. That is, the indexes of subsequent elements
are decremented by one
a1.add("Ayan");
System.out.print("\t" + a1);
l1.add("Mahnaz");
l1.add("Ayan");
System.out.println();
ArrayList Class.
The java.util.ArrayList class provides resizable-array and implements the List interface.Following
are the important points about ArrayList:
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 52
9 – Collection Classes
o It implements all optional list operations and it also permits all elements, includes
null.
o It provides methods to manipulate the size of the array that is used internally to
store the list.
o The constant factor is low compared to that for the LinkedList implementation.
Constructors:
S.N. Constructor & Description
1 ArrayList()
This constructor is used to create an empty list with an initial capacity sufficient to
hold 10 elements.
3 ArrayList(int initialCapacity)
This constructor is used to create an empty list with an initial capacity.
Methods:
S.N. Method & Description
3 void clear()
This method removes all of the elements from this list.
4 boolean contains(Object o)
This method returns true if this list contains the specified element.
5 E get(int index)
This method returns the element at the specified position in this list.
6 int indexOf(Object o)
This method returns the index of the first occurrence of the specified element in this
list, or -1 if this list does not contain the element.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 53
9 – Collection Classes
7 boolean isEmpty()
This method returns true if this list contains no elements.
8 int lastIndexOf(Object o)
This method returns the index of the last occurrence of the specified element in this
list, or -1 if this list does not contain the element.
9 boolean remove(Object o)
This method removes the first occurrence of the specified element from this list, if it is
present.
11 int size()
This method returns the number of elements in this list.
12 Object[] toArray()
This method returns an array containing all of the elements in this list in proper
sequence (from first to last element).
LinkedList Class.
The LinkedList class extends AbstractSequentialList and implements the List interface. It
provides a linked-list data structure.
Constructors:
SN Constructors and Description
1 LinkedList( )
This constructor builds an empty linked list.
2 LnkedList(Collection c)
This constructor builds a linked list that is initialized with the elements of the collection
c.
Methods:
SN Methods with Description
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 54
9 – Collection Classes
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >
size()).
2 boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order
that they are returned by the specified collection's iterator. Throws
NullPointerException if the specified collection is null
3 void addFirst(Object o)
Inserts the given element at the beginning of this list.
4 void addLast(Object o)
Appends the given element to the end of this list.
5 void clear()
Removes all of the elements from this list.
6 boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and
only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8 Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if this list is
empty.
9 Object getLast()
Returns the last element in this list. Throws NoSuchElementException if this list is
empty.
10 int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if the
List does not contain this element.
11 int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 55
9 – Collection Classes
13 boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws
NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if the
specified index is is out of range (index < 0 || index >= size()).
14 Object removeFirst()
Removes and returns the first element from this list. Throws NoSuchElementException if
this list is empty.
15 Object removeLast()
Removes and returns the last element from this list. Throws NoSuchElementException if
this list is empty.
17 int size()
Returns the number of elements in this list.
18 Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
Example :
import java.util.*;
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 56
9 – Collection Classes
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
Enumeration Interface.
The Enumeration interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code. However, it is used by several methods defined by the legacy
classes such as Vector and Properties, is used by several other API classes, and is currently in
widespread use in application code.
The methods declared by Enumeration are summarized in the following table:
SN Methods with Description
1 boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to
extract, and false when all the elements have been enumerated.
2 Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example:
import java.util.Vector;
import java.util.Enumeration;
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 57
9 – Collection Classes
Vector Class.
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
o Vector is synchronized.
o Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.
Constructors :
SR.NO Constructor and Description
1 Vector( )
This constructor creates a default vector, which has an initial size of 10
2 Vector(int size)
This constructor accepts an argument that equals to the required size, and
creates a vector whose initial capacity is specified by size:
4 Vector(Collection c)
creates a vector that contains the elements of collection c
Methods
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 58
9 – Collection Classes
2 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector,
in the order that they are returned by the specified Collection's Iterator.
4 int capacity()
Returns the current capacity of this vector.
5 void clear()
Removes all of the elements from this Vector.
7 boolean containsAll(Collection c)
Returns true if this Vector contains all of the elements in the specified
Collection.
8 Enumeration elements()
Returns an enumeration of the components of this vector.
9 Object firstElement()
Returns the first component (the item at index 0) of this vector.
12 boolean isEmpty()
Tests if this vector has no components.
13 Object lastElement()
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 59
9 – Collection Classes
16 boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained in the specified
Collection.
18 int size()
Returns the number of components in this vector.
Example:
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 60
9 – Collection Classes
Properties Class.
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object
returned by System.getProperties( ) when obtaining environmental values.
Properties define the following instance variable. This variable holds a default property list
associated with a Properties object.
Constructors:
SR.No Constructors and Description
1 Properties( )
This constructor creates a Properties object that has no default values
2 Properties(Properties propDefault)
creates an object that uses propDefault for its default values. In both cases, the
property list is empty
Methods :
SN Methods with Description
6 Enumeration propertyNames( )
Returns an enumeration of the keys. This includes those keys found in the default
property list, too.
After writing the string specified by description, the property list is written to the
output stream linked to streamOut
Example :
import java.util.*;
public class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 62
10 – Networking with java.net
InetAddress class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.gtu.ac.in, www.google.com,
www.facebook.com etc.
Methods :
SN Methods with Description
import java.net.*;
public class InetDemo{
System.out.println(e);
}
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 63
10 – Networking with java.net
Socket Class.
This class implements client sockets (also called just "sockets"). A socket is an endpoint for
communication between two machines.
The actual work of the socket is performed by an instance of the SocketImpl class. An
application, by changing the socket factory that creates the socket implementation, can
configure itself to create sockets appropriate to the local firewall.
Constructors:
S.N. Constructor & Description
1 Socket()
Creates an unconnected socket, with the system-default type of SocketImpl.
1 close()
Closes this socket.
2 connect(SocketAddress endpoint)
Connects this socket to the server.
3 getInetAddress()
Returns the address to which the socket is connected.
4 getPort()
Returns the remote port number to which this socket is connected.
5 isConnected()
Returns the connection state of the socket.
6 getInputStream()
returns the InputStream attached with this socket.
7 getOutputStream()
returns the OutputStream attached with this socket.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 64
10 – Networking with java.net
ServerSocket Class.
This class implements server sockets. A server socket waits for requests to come in over the
network. It performs some operation based on that request, and then possibly returns a result
to the requester.
The actual work of the server socket is performed by an instance of the SocketImpl class. An
application can change the socket factory that creates the socket implementation to configure
itself to create sockets appropriate to the local firewall.
Constructors:
SN Constructors and Description
1 ServerSocket()
This constructor builds an empty linked list.
2 ServerSocket(int port)
Creates a server socket, bound to the specified port.
Methods:
SN Methods with Description
1 accept()
Listens for a connection to be made to this socket and accepts it.
2 close()
Closes this socket.
3 getInetAddress()
Returns the local address of this server socket.
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 65
10 – Networking with java.net
System.out.println(e);
}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
1 DatagramSocket()
it creates a datagram socket and binds it with the available Port Number on the
localhost machine.
2 DatagramSocket(int port)
it creates a datagram socket and binds it with the given Port Number.
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 66
10 – Networking with java.net
The Commonly Used Methods of Datagram Socket:
SN Methods with Description
1 send(DatagramPacket p)
Sends a datagram packet from this socket.
2 receive(DatagramPacket p)
Receives a datagram packet from this socket.
DatagramPacket:
Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it
may arrive in any order. Additionally, packet delivery is not guaranteed.
The Commonly Used Constructors of DatagramPacket:
SN Methods with Description
//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 67
10 – Networking with java.net
Prof. Arjun Bala, CE Department | 2150704 – Object Oriented Programming with Java 68
11 – Introduction to Object orientation
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 69
11 – Introduction to Object orientation
iii. Inheritance
Sharing of attributes and operations based on a hierarchical relationship. Each subclass inherits
all features of super class and adds its unique features.
A super class has general information that subclasses refine and elaborate. Each subclass
incorporates, or inherits all the features of its super class and adds its own unique features.
Subclasses need not repeat the features of the super class.
Example, Scrolling Window, and Fixed Window are subclasses of Window.
The ability to factor out common features of several classes into a super class can greatly
reduce repetition within designs and programs and is one of the main.
Figure : Inheritance
iv. Polymorphism
Polymorphism means that the same operation may behave differently for different classes.
Example, the move operation behaves differently for a pawn than for the queen in a chess
game.
Polymorphism- a Greek term means ability to take more than one form.
The same operation may behave differently on different classes
An operation is a procedure or transformation that an object performs or is subject to.
An implementation of an operation by a specific class is called a method.
An Operation is a procedure or transformation that an object performs.
Implementation of operation by a specific class is called method.
Modeling as a Design Technique and modeling concepts
Abstraction
Abstraction is fundamental human capability that permits us to deal with complexity.
A process allowing focusing on most important aspects while ignoring less important details.
Abstraction is the selective examination of certain aspects of a problem.
The goal of abstraction is to isolate those aspects that are important for some purpose and
suppress those aspects that are unimportant.
Abstraction determines what is, and is not, important.
The purpose of an abstraction is to limit the universe so we can understand. A good model
captures the crucial aspects of a problem and omits the others.
In building model we must not search for absolute truth but for adequacy.
There is no single “correct” model, only adequate and inadequate ones.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 70
11 – Introduction to Object orientation
Property of Abstraction:-
All the abstraction are incomplete and inaccurate.
No Abstraction is perfect.
E.g. All human words and language are abstractions (incomplete description of real world).
No single model is sufficient to represent any situation.
Abstraction does not destroy usefulness of a system.
The purpose is to limit the universe which eliminates the complexity.
Software model that contains extra detail unnecessarily limits choice of design decisions and
diverts from the real issues.
State Model
Describes history and behavior of a system with respect to time.
Explains context of events and organization of events with states.
Actions and events in state model become operations on object in class model.
Interaction Model
Explains interactions between objects.
It also explains, how individual object collaborate to achieve behavior of system as a whole.
i. Use Case Model: Document major theme for interactions between system and outside
actors.
ii. Sequence Model: Describes object that interact and time sequence of their interactions.
iii. Activity Model: shows flow of control among processing steps of a computation.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 71
12 – Class Modeling
Class Modeling
A class modeling captures static structure of a system by characterizing the objects in the
system, the relationships between the objects, and the attributes and operations for each class
of objects.
Class model is most important among three models.
Emphasizes on building a system around objects rather than functionality.
Class Model closely corresponds to the real world and is consequently more flexible with
respect to the change.
The purpose of class modeling is to describe object.
Object:
Object is a concept, abstraction, or a thing with identity that has meaning for an application
E.g. Two apples each have identity and are distinguishable.
Objects are instances of classes.
It often appears as a proper nouns or specific references in problem descriptions
Some objects have real world counterparts (name of a person/company).
While some object have conceptual entity (formula for solving quadratic equation).
Choice of object depends on judgment and the nature of a problem. There can be many correct
representations. All Object have identity and distinguishable.
Identity means objects are distinguished by their inherent existence and not by descriptive
properties.
Real-world objects share two characteristics: They all have attributes and behavior.
Class:
Class describes a group of objects with the same properties (attributes), behaviour (operations),
kinds of relationship, and Semantics. (E.g.: Person, Company, Process and Window).
A software unit that implements one or more interfaces.
Classes often appear as common noun and noun phrase in problem description.
By grouping objects into class, we abstract a problem.
Class Diagram
Class Diagram provides a Graphical notation for modeling classes and their relationships,
thereby describing possible objects.
The most widely used diagram of UML.
Models the static design view of a system.
Useful in modeling business objects.
Used to specify the structure, interfaces and relationships between classes that underlie the
system architecture.
Primary diagram for generating codes from UML models.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 72
12 – Class Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 73
12 – Class Modeling
8 ordering It is used to
indicate an
ordered set of
objects with no
duplication
allowed.
9 bag A bag is a
collection of
unordered
elements with
Duplicates
allowed.
10 sequence A sequence is an
ordered
collection of
elements with
duplicates
allowed.
11 qualified Qualification
association increases the
precision of a
model.
It is used to avoid
many to many
multiplicities and
it converts into
one to one
multiplicity.
12 generalization Generalization
organizes classes
by their
superclass and
sub-class
relationship.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 74
12 – Class Modeling
13 Enumeration An enumeration
is a data type that
has a finite set
of values.
15 Composition It is a form of
aggregation.
Composition
implies
ownership of the
parts by the
whole.
16 Abstract class It is a class that
has no direct
instances.
18 package A package is a
group of
elements with
common theme.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 75
12 – Class Modeling
Examples:
Class Diagram for Library Management System
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 76
12 – Class Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 77
12 – Class Modeling
Class Diagram for Online Restaurant System
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 78
12 – Class Modeling
Class Diagram for Online Reservation System
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 79
12 – Class Modeling
Class Diagram for Online Shopping System
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 80
12 – Class Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 81
12 – Class Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 82
13 – Advanced Class Modeling
- The idea of the role is that the same classifier can play the same or different roles in other
associations.
- For example, Professor could be an author of some Books or an editor.
Association end could be owned either by end classifier, or association itself
Association ends of associations with more than two ends must be owned by the association.
Ownership of association ends by an associated classifier may be indicated graphically by
a small filled circle (aka dot).
The dot is drawn at the point where line meets the classifier.
It could be interpreted as showing that the model includes a property of the type represented
by the classifier touched by the dot.
This property is owned by the classifier at the other end.
The "ownership" dot may be used in combination with the other graphic line-path notations for
properties of associations and association ends. These include aggregation type and
navigability.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 83
13 – Advanced Class Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 84
13 – Advanced Class Modeling
Composition
Composition is a restricted form of aggregation with two additional constraints.
Figure of Composition
Abstract Class
An abstract class is a class that has no direct instances but whose descendant classes have
direct instances.
A concrete class is a class in which it can have direct instances.
Abstraction is a process to allow focusing on most important aspects while ignoring less
important details.
In the UML notation an abstract class name is listed in an italic font. Or you may place the
keyword {abstract} below or after the name.
Use abstract class to define the signature for an operation without supplying a corresponding
method.
An abstract operation defines the signature of an operation for which each concrete subclass
must provide its own implementation.
As shown in example draw () is an abstract operation.
Within abstract class (Graphic Object), draw () is just a definition and not implementation.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 85
13 – Advanced Class Modeling
Each subclass (Circle and Rectangle) must apply method draw () in its implementation. In other
words all the super class are abstract class all the subclass are concrete class.
It is advisable to avoid concrete super class.
We can eliminate concrete super class by introducing other class. Differentiate Abstract class
and Concrete class
Multiple Inheritance
Multiple Inheritance permits the class to have more than one super class
Here subclass inherit feature form its all super class.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 86
13 – Advanced Class Modeling
In the multiple inheritance diamond problem example above Button class inherits two different
implementations of equals() while it has no own implementation of the operation.
When button.equals() is called, it is unknown which implementation from Rectangle or from
Clickable will be used.
It may arise conflicts among parallel definition creates ambiguities that implementation must
resolve.
Meta Data
Metadata is data that describes other data.
Data about data.
All the UML software models are inherently metadata, since describe the thing being modeled.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 87
13 – Advanced Class Modeling
i. Natural Language
ii. Formal Language such as Object Constraint Language (OCL)
As shown in above example, represents that no employee’s salary can exceed salary of
employee Boss (A constraint between two things at same time).
Another example, for maximum student in a Batch.
Constraints on Generalization
The semantics of generalization imply certain structural constraints.
With the single inheritance the subclass is mutually exclusive.
Furthermore, each instance of an abstract super class corresponds to exactly one subclass
instance and each instance of a concrete super class corresponds to at most one subclass
instance.
UML defines certain keywords to demonstrate constraint.
i. Disjoint:
o The subclasses are mutually exclusive.
o Each object of subclass belongs to exactly one of the subclasses.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 88
13 – Advanced Class Modeling
ii. Overlapping:
o In an overlapping specialization, an individual of the parent class may be a member of
more than one of the specialized subclasses.
o The subclasses can share some objects.
o An object may belong to more than one subclass.
iii. Complete:
o Generalization that lists all possible subclasses.
iv. Incomplete:
o Generalization in which some of the subclasses is missing.
v. Static
o Generalization in which subclass are static in nature.
vi. Dynamic
o Generalization in which subclass are dynamic with respect to time.
Constraints on Links
Multiplicity is constraint on cardinality of set.
Multiplicity restricts number of object related to given object.
Qualification also adds constraint on an association.
An association class has a constraint that an ordinary class does not have; i.e. it derives identity
from instance of related classes.
Derived Data.
A derived element is a function of one or more elements, which in turn may be derived.
A derived element is redundant, because other element completely determines it.
Classes, association and attribute may be derived.
The notation for derived elements is a slash (/) in front of element name.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 89
13 – Advanced Class Modeling
Packages.
A package is a group of elements with a common theme.
A package partitions a model, making it easier to understand and manage.
Large applications may require several tiers of packages.
The notation for a package is a box with a tab. The purpose of the tab is to suggest the enclosed
contents.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 90
14 – State Modeling
State Modeling
State Diagram explains behavior of the system.
A State Diagram is a graph whose nodes are states and arcs are transition between the states
caused by the event.
State Modeling examines changes to the object and their relationship over time.
The behavior of an entity is not only a direct consequence of its input, but it also depends on its
preceding state.
The history of an entity can best be modeled by a finite state diagram.
State diagram can show the different states of an entity also how an entity responds to various
events by changing from one state to another.
The major dynamic modeling concepts are events, which represent external stimuli, and states,
which represent values of objects.
State Diagram is a standard computer science concept/a graphical representation that relates
events and states.
State model describes:
i. Sequence of operation that occur in response of external stimuli.
ii. What the specific operation do.
iii. What they operate on.
iv. How that operation are implemented
Signal Event
Grouping every event into event classes and gives each event class a name to indicate common
structure and behaviour is known as Signal Event.
It is a one-way transmission of information from one object to another. It is event of sending or
receiving signal.
The UML notation is the keyword signal in guillemets (<< >>) above the signal class name in the
top section of a box.
The difference between signal and signal event is :
o Signal: one way transmission between object.
o Signal event: an occurrence in time.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 91
14 – State Modeling
Time Events
A time event is an event caused by the occurrence of an absolute time or the elapse of a time
interval.
The UML notation for an absolute time is the keyword when followed by a parenthesized
expression involving time.
This event is caused by the occurrence of an absolute time or the elapsed of a time interval.
The notation for a time interval is the keyword after followed by a parenthesized expression
that evaluates to time duration.
Explain State
A state is an abstraction of the attribute values and links of an object.
The response of an object to an event may include an action or a change of state by the object.
A state corresponds to the interval between two events revived by an object. Events represent
points in time; states represent intervals of time.
A state has duration; it occupies an interval of time.
A state is often associated with the value of an object satisfying some condition.
In the simplest case, each enumerated value of an attribute defines a separate state.
The State having suggestive name and natural language description of its purpose.
Write the characteristics of a state Alarm Ringing.
The below figure shows for the state Alarm Ringing on a watch.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 94
14 – State Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 95
14 – State Modeling
Activity Effects
The effect is a reference to a behavior that is executed in response to an event.
An activity is the actual behavior that can be invoked by any number of effects.
E.g. disconnect Phone Line might be an activity that is executed in response to hang up event.
Activities can also represent internal control operations, such as setting attributes or generating
other events.
Such activities have no real-world counterparts but instead are mechanisms for structuring
control within an implementation.
E.g. program might increment an internal counter every time when specific event occurs.
State diagram activity is denoted as slash (“/”) and name or description of the activity, following
the event that causes it.
As shown in figure below, when right button is pressed, menu is displayed when it is released,
menu is erased. While menu is visible, the highlighted menu item is updated whenever cursor
moves.
Paper Jam
Do/flash warning light
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 96
14 – State Modeling
Activity which is more concise to attach the activity of a state should be specified inside the
state.
When the state is entered by an incoming transition, entry activity is performed.
An entry activity is equivalent to attaching the activity to every incoming transition.
If incoming transition already has an activity, it is performed first.
Exit activities are less common compared entry activities and occasionally useful.
Whenever state is exited, by any outgoing transition, the exit activity is performed first.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 97
14 – State Modeling
This diagram shows the states of door controller. User generates depress event with a
pushbutton to open and close the door. Each event reverses the direction of the door. For
safety door must open fully before it can be closed. Motor Up and Motor Down are activities
which generates the control.
Motor generates door open and door closed events when the motion has been completed.
If a state has multiple activities, they are performed in following order:
Completion Transition
Main purpose of state is to perform sequential activity.
When an activity is completed, transition fires to another state.
An arrow without an event name indicates an automatic transition that fires when activity
associated with the source state is completed.
Such unlabeled transition is known as Completion Transition.
Stuck Condition: Guard condition is tested only once, when event occurs. If a state has one or
more completion transition, but none of the guard condition is satisfied, then the state remains
active and may become “stuck”.
The completion event does not occur second time, therefore no completion transition will fire
later to change the state.
If the state has completion transition leaving it, normally the guard condition should cover
every possible outcome.
We can use some special condition such as else to apply if all other condition is false.
Better approach is not to use guard condition on a completion transition, instead change event
should be used.
Sending Signals
Object can perform activity by sending signal and system of objects interacts by exchanging
signals.
The activity “send target.S (attributes)” send signal S with given attributes to the target object
or objects.
E.g. phone line sends connect (phone number) signal to the switcher when complete number
has been dialed.
A signal can be directed at a set of object or single object.
If target is set of objects, each of them receives separate copy of signal and each of them
independently processes the signal.
Race condition: If object can receive signals from more than one object, the order in which
concurrent signals are received may affect the final state. This is known as race condition.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 98
14 – State Modeling
The below diagram explain state diagram for telephone line with activities:
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 99
15 – Interaction Modeling
Interaction Modeling
Interaction model is the third leg of the tripod and describes interaction with the system.
Class model describes object in the system and relationship among them.
State model describes life history of an object.
Interaction model describes how the object interacts to produce useful results.
Interaction model and state software model describes whole behavior of the system.
Interaction can be modeled at different level of abstraction. At higher level, use case describes
how a system interacts with outside actors.
Each use case represents piece of functionality that a system provides to its user.Use cases are
helpful for capturing informal requirements.
Sequence diagram provides more detail and show the messages exchanged among a set of
objects over the time.
Sequence diagrams are good for showing the behavior sequence seen by users of a system.
Activity diagrams provide further detail and show the flow of control among the steps of
computation.
Activity diagram documents the steps necessary to implement an operation or a business
process in a sequence diagram.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 100
15 – Interaction Modeling
A use case diagram at its simplest is a representation of a user's interaction with the system and
depicting the specifications of a use case.
A use case diagram contains four components.
i. The boundary, which defines the system of interest in relation to the world around it.
ii. The actors, usually individuals involved with the system defined according to their
roles.
iii. The use cases, which the specific roles are played by the actors within and around the
system.
iv. The relationships between and among the actors and the use cases.
Purpose:
The main purpose of the use case diagram is to capture the dynamic aspect of a system.
Use case diagram shows, what software is suppose to do from user point of view.
It describes the behavior of system from user’s point.
It provides functional description of system and its major processes.
Use case diagram defines the scope of the system you are building.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 102
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 103
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 104
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 105
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 106
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 107
15 – Interaction Modeling
Sequance models
Introduction
Sequence diagrams model the dynamic aspects of a software system.
The emphasis is on the “sequence” of messages rather than relationship between objects.
A sequence diagram maps the flow of logic or flow of control within a usage scenario into a
visual diagram enabling the software architect to both document and validate the logic during
the analysis and design stages.
Sequence diagrams provide more detail and show the message exchanged among a set of
objects over time.
Sequence diagrams are good for showing the behavior sequences seen by users of a diagram
shows only the sequence of messages not their exact timing.
Sequence diagrams can show concurrent signals.
Purpose
The main purpose of this diagram is to represent how different business objects interact.
A sequence diagram shows object interactions arranged in time sequence.
It depicts the objects and classes involved in the scenario and the sequence of messages
exchanged between the objects needed to carry out the functionality of the scenario.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 108
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 109
15 – Interaction Modeling
Issue book
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 110
15 – Interaction Modeling
Return book
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 111
15 – Interaction Modeling
Create account
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 112
15 – Interaction Modeling
Transaction
Exceptional case
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 113
15 – Interaction Modeling
Supply order
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 114
15 – Interaction Modeling
Product not available
Product Exchange
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 115
15 – Interaction Modeling
Sequence diagram for Bus reservation system:-
Reservation
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 116
15 – Interaction Modeling
Activity Diagram
Introduction
An activity diagram is a type of flow chart with additional support for parallel behavior.
This diagram explains overall flow of control.
Activity diagram is another important diagram in UML to describe dynamic aspects of the
system.
Activity diagram is basically a flow chart to represent the flow from one activity to another
activity
The activity can be described as an operation of the system.
The control flow is drawn from one operation to another. This flow can be sequential, branched
or concurrent. This distinction is important for a distributed system.
Activity diagrams deals with all type of flow control by using different elements like fork, join
etc.
Purpose
Contrary to use case diagrams, in activity diagrams it is obvious whether actors can perform
business usecases together or independently from one another.
Activity diagrams allow you to think functionally.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 117
15 – Interaction Modeling
4 Initial activity Initial node is a control node at which flow starts
when the activity is invoked. Activity may have more
than one initial node. Initial nodes are shown as a
small solid circle.
5 Final activity Final node is a control final node that stops all flows in
an activity. Activity final nodes are shown as a solid
circle with a hollow circle inside. It can be thought of
as a goal notated as "bull’s eye," or target.
6 Fork A fork in the activity diagram has a single incoming
transition and multiple outgoing transitions exhibiting
parallel behavior.The incoming transition triggers the
parallel outgoing transitions.
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 118
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 119
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 120
15 – Interaction Modeling
Activity diagram for ATM
Verify PIN number
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 121
15 – Interaction Modeling
Transaction
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 122
15 – Interaction Modeling
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 123
15 – Interaction Modeling
Payment
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 124
15 – Interaction Modeling
Activity Diagram for Online Reservation System
Booking Process
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 125
15 – Interaction Modeling
Server Operation
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 126
15 – Interaction Modeling
Activity diagram for Online Shopping
Purchase Product
Prof. Arjun Bala, Prof. Chirag Patel, CE Department | 2150704 – Object Oriented Programming with Java 127