You are on page 1of 309

1

CSE2006-PROGRAMMING-IN-JAVA

5 - Java Database Connectivity using


TM
JDBC driver, Eclipse
5.a.1 MySQL DB Installation,
Simple SQL Query Execution in MySQL,
JDBC Example

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


2

JDBC Example

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


3

Download MySQL
https://dev.mysql.com/downloads/installer/

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


4

Download MySQL …Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


5

Installation

Double Click to
install

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


6

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


7

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


8

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


9

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


10
Installation … Cntd.
Is your m/c 32Bit or 64Bit?

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


11
Installation … Cntd.
Is your m/c 32Bit or 64Bit?

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


12
Installation … Cntd.
- Select Products according to 32/64 Bit m/c

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


13

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


14

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


15

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


16

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


17

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


18

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


19

Installation … Cntd.

User name: “root”

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


20

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


21

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


22

Installation … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


23
Installation … Cntd.
Completed

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


24
Set Environment Variable for MySQL
- Search for it

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


25

Set Environment Variable for MySQL … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


26

Set Environment Variable for MySQL … Cntd.

Do NOT edit
anything else….
Edit Only PATH
Variable…
!! BE CAREFUL !!!

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


27

Set Environment Variable for MySQL … Cntd.

Do NOT edit anything


else….
Edit Only PATH Variable…
!! BE CAREFUL !!!

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


28

Set Environment Variable for MySQL … Cntd.

Do NOT edit
anything else….
Edit Only PATH
Variable…
!! BE CAREFUL !!!

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


29

Start it… using Services panel

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


30

Start it… using Services Panel … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


31

Start it… using Services Panel … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


32

Open Command Prompt to work

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


33

Login, Check existing DBs in MySQL

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


34

Create New DB, Use it

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


35
Create new table in DB, show all tables,
describe created table

create table student


( schno INT unsigned NOT NULL AUTO_INCREMENT, # Unique ID for the record
name VARCHAR(150) NOT NULL, # Name of the student
course VARCHAR(50) NOT NULL, # Name of the course of the student
PRIMARY KEY (schno) # Make the id the primary key
);

create table student (schno INT unsigned NOT NULL AUTO_INCREMENT, name
VARCHAR(150) NOT NULL, course VARCHAR(50) NOT NULL, PRIMARY KEY (schno) );

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


36
Create new table in DB, show all tables,
describe created table

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


37
Insert data in the newly created Table and
read/display/show it

insert into student (name, course) values


(‘Ajay Kumar’, ‘BTech’), (‘Sandesh
Kumar’, ‘MTech’), (‘Vijay Prasad’, ‘PhD’);

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


38
Insert data in the newly created Table and
read/display/show it …. Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


39

Simple DB Connectivity Example using JDBC

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


40

Create DB Connection “Handle”

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


41

Create DB Connection “Handle” … Cntd.

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


42

Set classpath of JDBC Connector

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


43

Set classpath of JDBC Connector … Cntd.

If you are using cmd prompt for connectivity then you can set classpath:
$ set classpath=z:\Java\mysql-connector-java-8.0.30.jar;.;

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


44

Run your JDBC Connectivity Code/Program

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


45

• For doubts contact at:


– adarsh.patel@vitbhopal.ac.in

MySQL Installation, SQL, JDBC: Adarsh Patel, SCSE, VIT-Bhopal


1

CSE2006-PROGRAMMING-IN-JAVA

5 - JDBC

5.a.2 Simple SQL Query Examples


• Introduction
• Relational-Database Model
• Simple SQL - CRUD Operations: We will need them in JDBC Testing
• Basic SELECT Query
• INSERT Statement
• UPDATE Statement
• DELETE Statement

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


2

Introduction

• DataBase Management System (DBMS)


– Mechanisms for storing and organizing data
– Access, store, modify data without concern for internal
representation (information hiding)
• Structured Query Language (SQL)
– Standard language used with relational databases to perform
queries and manipulate data

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


3

Relational-Database Model

• Relational database
– Logical representation of data, not necessarily the way the
data is stored
– Table
• Rows (entities), columns (attributes)
– Primary key (column or group of columns)
• Unique value for each row
• Not every table has a primary key
• SQL statement
– Query (which data to select from table or tables)

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


4

Relational-Database Model (Cont.)

Number Name Department Salary Location

23603 Jones 413 1100 New Jersey

24568 Kerwin 413 2000 New Jersey


Row 34589 Larson 642 1800 Los Angeles
35761 Myers 611 1400 Orlando

47132 Neumann 413 9000 New Jersey


78321 Stephens 611 8500 Orlando

Primary key Column

“Employee” table sample data.

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


5

Basic SELECT Query

• Simplest form of a SELECT query


– SELECT * FROM tableName
• SELECT * FROM student
• * means all columns (not recommended)
• Select specific fields from a table
– SELECT schno, name FROM student

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


6

INSERT Statement

• Insert a row into a table


– INSERT INTO tableName ( columnName1, … , columnNameN )
VALUES ( value1, … , valueN )
• INSERT INTO student ( name, course )
VALUES ( ‘Amit’, ‘BTech’ )

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


7

UPDATE Statement

• Modify data in a table


– UPDATE tableName
SET columnName1 = value1, … , columnNameN = valueN
WHERE criteria
• UPDATE student
SET course = ‘MTech’
WHERE name = ‘Amit’ AND ……

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


8

DELETE Statement

• Remove data from a table (row or rows)


– DELETE FROM tableName WHERE criteria
• DELETE FROM student
WHERE name = ‘Amit’ AND …..

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


9

• Ref: Deitel & Deitel

• For doubts contact at:


– adarsh.patel@vitbhopal.ac.in

Simple SQL Queries: Adarsh Patel, SCSE, VIT-Bhopal


1

CSE2006-PROGRAMMING-IN-JAVA

UNIT – 4

4.b Collections
• Types
• Wrapper Class
• ArrayList
• Iterator
• Vector
• Stack

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
2

Introduction
• A collection is a data structure - actually, an object that
can hold references to other objects.
– Usually, collections contain references to objects of any type that
has the is-a relationship with the type stored in the collection.
• Package java.util.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
3

Introduction … Cntd.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
4

Type-Wrapper Classes
• Each primitive type has a corresponding type-
wrapper class (in package java.lang).
– Boolean, Byte, Character, Double, Float, Integer,
Long and Short.
• Each type-wrapper class enables you to
manipulate primitive-type values as objects.
• Collections cannot manipulate variables of
primitive types.
– They can manipulate objects of the type-wrapper classes,
because every class ultimately derives from Object.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
5

Type-Wrapper Classes (cont.)


• Each of the numeric type-wrapper classes—Byte,
Short, Integer, Long, Float and Double—
extends class Number.
• The type-wrapper classes are final classes, so
you cannot extend them.
• Primitive types do not have methods, so the
methods related to a primitive type are located in
the corresponding type-wrapper class.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
6

Autoboxing and Auto-Unboxing


• A boxing conversion converts a value of a primitive type to an object
of the corresponding type-wrapper class.
• An unboxing conversion converts an object of a type-wrapper class to
a value of the corresponding primitive type.
• These conversions are performed automatically—called autoboxing
and auto-unboxing.

• Example:
– // create integerArray
Integer[] integerArray = new Integer[5];

– // assign Integer 10 to integerArray[ 0 ]


integerArray[0] = 10;

// get int value of Integer
int value = integerArray[0];

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
7

Interface Collection and Class


Collections
• Interface Collection contains bulk operations for adding, clearing and
comparing objects in a collection.

• A Collection can be converted to an array.

• Interface Collection provides a method that returns an Iterator


object, which allows a program to walk through the collection and
remove elements from the collection during the iteration.

• Class Collections provides static methods that search, sort and


perform other operations on collections.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
8

Lists
• A List (sometimes called a sequence) is an ordered Collection that
can contain duplicate elements.

• List indices are zero based.

• In addition to the methods inherited from Collection, List


provides methods for manipulating elements via their indices,
manipulating a specified range of elements, searching for elements and
obtaining a ListIterator to access the elements.

• Interface List is implemented by several classes, including


ArrayList, LinkedList and Vector.

• Autoboxing occurs when you add primitive-type values to objects of


these classes, because they store only references to objects.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
9

Lists (cont.)
• Class ArrayList and Vector are resizable-array implementations of
List.
• Inserting an element between existing elements of an ArrayList or
Vector is an inefficient operation.
• A LinkedList enables efficient insertion (or removal) of elements in the
middle of a collection, but is much less efficient than an ArrayList for
jumping to a specific element in the collection.
• We discuss the architecture of linked lists in Chapter 21.
• The primary difference between ArrayList and Vector is that operations
on Vectors are synchronized by default, whereas those on ArrayLists are
not.
• Unsynchronized collections provide better performance than synchronized
ones.
• For this reason, ArrayList is typically preferred over Vector in programs
that do not share a collection among threads.

• Vector is a synchronized ArrayList


• Synchronization requires extra checking and atomic operations
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
10

Integer Array List Example

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
11

Integer Array List Example …


(Cntd.)

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
12

ArrayList and Iterator


• List method add adds an item to the end of a list.
• List method size returns the number of elements.
• List method get retrieves an individual element’s value from the
specified index.
for (int i = 0; i < list.size(); i++) {
list.add(value);
System.out.println(list.get(i));
}
• Collection method iterator gets an Iterator for a
Collection.
• Iterator- method hasNext determines whether there are more
elements to iterate through.
– Returns true if another element exists and false otherwise.
• Iterator method next obtains a reference to the next element.
• Collection method contains determine whether a Collection
contains a specified element.
• Iterator method remove removes the current element from a
Collection.
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
13

ArrayList and Iterator


• Type Inference with the <> Notation

– Java SE 7 introduced type inferencing with the <> notation—


known as the diamond notation—in statements that declare and
create generic type variables and objects. For example, line 14 can
be written as:

List<String> list = new ArrayList<>();

– Java uses the type in angle brackets on the left of the declaration
(that is, String) as the type stored in the ArrayList created on
the right side of the declaration.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
14
List interface rather than
ArrayList … Comparison
• List interface is more flexible than ArrayList

• If a LinkedList is needed later, only change the new LinkedList

• This follows the rule to program to the interface.

• Programming to the interface makes the entry points very flexible and
allows the specific implementation to change.
– ArrayList is more efficient for direct access
– LinkedList is more efficient for insert and delete.s

• Declare parameters as interface rather than concrete class – use the


most general class that satisfies the methods used.
– Collection<String> not List<String> or
ArrayList<String>
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
15

String
Array List
Example

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
16

String Array List Example …


(Cntd.)

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
17

Collections Methods
• Class Collections provides several high-performance algorithms
for manipulating collection elements.
• The algorithms (Fig. 16.5) are implemented as static methods.

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
18

Collections Methods … (Cntd.)

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
19

Vector Class and Enumeration


Interface
• Class java.util.Vector
– Array-like data structures that can resize themselves
dynamically
– Arrays are fixed in size after memory allocation
(String[] name = new String[25])
– Vector contains a capacity (number of elements always less
than or equal to capacity)
– Grows by capacity increment if it requires additional space
• Vector v = new Vector(); (capacity=10, doubles)
• Vector v = new Vector(n); (capacity=n, doubles)
• Vector v = new Vector(n,p); (capacity=n,
increment=p)

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
20

Vector Class and Enumeration


Interface … (Cntd.)
• Class java.util.Vector
– Vectors store objects (of any type), but they must be objects
and not primitives 
• This is a job for Wrapper classes ☺
– v.add(object) adds new object as the last element in
the vector
– v.add(i,object) adds new object as element i in the
vector (and shifts everything to the right of this one)
• There must already be an object at element i
– v.remove(object) removes object (and shifts
everything to the left)
– v.remove(i) removes element i (and shifts everything to
the left)
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
21

Vector Class and Enumeration


Interface … (Cntd.)
• Class java.util.Vector
– v.capacity() returns capacity
– v.size() returns current number of elements
– v.trimToSize() sets capacity equal to current number
of elements (size)
• next item added causes capacity to double or increase by p
– v.get(i) returns reference to element i
– v.set(i,object) changes the object at element i
• There must already be an object at element i
– More Vector methods illustrated in the following example…

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
22

Vector Class and Enumeration


Interface … (Cntd.)
• Class java.util.Enumeration
– Enumeration object generates a series of elements
(Enumeration e = v.elements();)
• v is a Vector
• elements() method returns an enumeration of all
elements in the vector
– e.hasMoreElements()
– e.nextElement()
– Notice the similarity to StringTokenizer
– Enumeration can also be used with Hashtable

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
23
1 // Fig. 21.1: VectorTest.java Outline
2 // Using the Vector class.
3 import java.util.*;
4 VectorTest.java
5 public class VectorTest {
6 private static final String colors[] = { "red", "white", "blue" };
7 Line 10
8 public VectorTest()
9 { Create VectorLines
with14, 17 and 19
initial
10 Vector vector = new Vector();
capacity of 10 elements and
11 printVector( vector ); // print vector
12
Line of
capacity increment 24 zero
13 // add elements to the vector
14 vector.add( "magenta" ); Line 25
15
16 for ( int count = 0; count < colors.length; count++ )
17 vector.add( colors[ count ] ); Call Vector method add to add
18 objects to the end of the Vector
19 vector.add( "cyan" );
20 printVector( vector ); // print vector Call Vector method firstElement to return
21 Calla Vector
reference method lastElement
to the first element in thetoVector
return
22 // output the first and last elements a reference to the last element in the Vector
23 try {
24 System.out.println( "First element: " + vector.firstElement() );
25 System.out.println( "Last element: " + vector.lastElement() );
26 }

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
24
27 Outline
28 // catch exception if vector is empty Vector method contains returns
29 catch ( NoSuchElementException exceptionboolean
) { that indicates whether
30 exception.printStackTrace(); Vector contains a specific ObjectVectorTest.java
31 }
32
33 // does vector contain "red"? Line 34
34 if ( vector.contains( "red" ) )
35 System.out.println( "\n\"red\" found at index " + Line 36
36 vector.indexOf( "red" ) + "\n" );
Vector method remove removes the first
37 else
38
occurrence of its argument Object fromLine
System.out.println( "\n\"red\" not found\n" );
Vector
40
39 Vector method indexOf
40 vector.remove( "red" ); // remove the stringindex
returns "red"of first location in Lines 52-53
41 System.out.println( "\"red\" has been removed" );
Vector containing the argument
42 printVector( vector ); // print vector
43
44 // does vector contain "red" after remove operation?
45 if ( vector.contains( "red" ) )
46 System.out.println( "\"red\" found at index " +
47 vector.indexOf( "red" ) );
48 else
49 System.out.println( "\"red\" not found" );
50
51 // print the size and capacity of vector
52 System.out.println( "\nSize: " + vector.size() +
Vector methods size and
53 "\nCapacity: " + vector.capacity() ); capacity return number of
54 elements in Vector and
55 } // end constructor Vector capacity, respectively

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
25
56 Outline
57 private void printVector( Vector vectorToOutput )
58 { Vector method isEmpty
59 if ( vectorToOutput.isEmpty() ) returns true if there are no VectorTest.java
60 System.out.print( "vector is empty" ); // vectorToOutput
elements in theis Vector
empty
61
62 else { // iterate through the elements Line 59
63 System.out.print( "vector contains: " ); Vector method elements
64 Enumeration items = vectorToOutput.elements(); Line 64
returns Enumeration for
65
66 while ( items.hasMoreElements() )
iterating Vector elements
67 System.out.print( items.nextElement() + " " );
68 }
69
70 System.out.println( "\n" );
71 }
72
73 public static void main( String args[] )
74 {
75 new VectorTest(); // create object and call its constructor
76 }
77
78 } // end class VectorTest

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
26
vector is empty Outline
vector contains: magenta red white blue cyan
VectorTest.java
First element: magenta
Last element: cyan

"red" found at index 1

"red" has been removed


vector contains: magenta white blue cyan

"red" not found

Size: 4
Capacity: 10

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
27
21.3 Stack Class of Package
java.util
• Stack
– Implements stack data structure
– Extends class Vector
– Stores references to Objects (as does Vector)
– Methods
• Stack() (the only constructor, creates empty stack)
• push(object) (put object on top of stack)
• pop() (remove and return object on top of stack)
• peek() (look at item on top of stack without removing it)
• empty() (boolean)
• search(object) (returns distance from top of stack to
where item is located or -1)

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
28
1 // Fig. 21.2: StackTest.java Outline
2 // Program to test java.util.Stack.
3 import java.util.*;
4 StackTest.java
5 public class StackTest {
6
7 public StackTest() Line 9
8 {
9 Stack stack = new Stack(); Create empty Stack
Lines 18, 20, 22 and
10
24
11 // create objects to store in the stack
12 Boolean bool = Boolean.TRUE;
13 Character character = new Character( '$' );
14 Integer integer = new Integer( 34567 );
15 String string = "hello";
16
17 // use push method
18 stack.push( bool );
19 printStack( stack );
20 stack.push( character );
21 printStack( stack );
Stack method push adds
22 stack.push( integer ); Object to top of Stack
23 printStack( stack );
24 stack.push( string );
25 printStack( stack );
26

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
29
27 // remove items from stack Outline
28 try {
Stack method pop removes
29 Object removedObject = null;
30 Object from top of Stack
StackTest.java
31 while ( true ) {
32 removedObject = stack.pop(); // use pop method
33 System.out.println( removedObject.toString() + " popped" ); Line 32
34 printStack( stack );
35 } Line 46
36 }
37
38 // catch exception if stack is empty when item popped
Line 51
39 catch ( EmptyStackException emptyStackException ) {
40 emptyStackException.printStackTrace();
41 }
42 } Stack method isEmpty returns
43 true if Stack is empty
44 private void printStack( Stack stack )
45 {
46 if ( stack.isEmpty() )
47 System.out.print( "stack is empty" ); // the stack is empty
48
49 else {
50 System.out.print( "stack contains: " ); Stack extends Vector, so
51 Enumeration items = stack.elements(); class Stack may use method
52 elements to obtain
Enumeration for Stack

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
30
53 // iterate through the elements Outline
54 while ( items.hasMoreElements() )
55 System.out.print( items.nextElement() + " " );
56 } StackTest.java
57
58 System.out.println( "\n" ); // go to the next line
59 }
60
61 public static void main( String args[] )
62 {
63 new StackTest();
64 }
65
66 } // end class StackTest

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
31
Outline
stack contains: true

stack contains: true $ StackTest.java


stack contains: true $ 34567

stack contains: true $ 34567 hello

hello popped
stack contains: true $ 34567

34567 popped
stack contains: true $

$ popped
stack contains: true

true popped
stack is empty

java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:79)
at java.util.Stack.pop(Stack.java:61)
at StackTest.<init>(StackTest.java:32)
at StackTest.main(StackTest.java:63)

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
32

ConcurrentModificationException
• Java is inherently multi-threaded, particularly in GUI code.
– ArrayList are not thread-safe, Vector is thread-safe.
– Use Collections.synchronizedList(new
ArrayList<T>())to get a synchronized version of ArrayList.
– Or use CopyOnWriteArrayList
• If a Collection is modified structurally without using the Iterator (i.e.
add, remove, change backing array) the Iterator becomes invalid.
• Any operation performed with the iterator fails immediately and
throws a ConcurrentModificationException.
– This is known as “fail-fast”
– the failbit in C++ istreams (i.e.
cin.setstate(ios::failbit)) is fail-fast

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
33

• Ref: Deitel & Deitel

• For doubts contact at:


– adarsh.patel@vitbhopal.ac.in

Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
1

3b – Multithreading
• Introduction
• Thread States: Life Cycle of a Thread
• Thread Priorities and Thread Scheduling
• Creating and Executing Threads
• Thread Synchronization
• Producer/Consumer Relationship without
Synchronization
• Producer/Consumer Relationship with Synchronization
• Producer/Consumer Relationship: Circular Buffer
• Daemon Threads
• Runnable Interface
• Discovering Design Patterns: Concurrent Design Patterns
2

Introduction

• Concurrency = performing operations in parallel


• Computer supports concurrency with multiple
processors
• Single processor computers simulate concurrency
(time slicing)
• Ada was first major programming language to
support concurrency
• Standard C and C++ do not
• Java provides built-in multithreading
– “Threads of execution” improve the performance of some
programs
3

Introduction

• Thread class is in java.lang


• Examples of threads
– Search multiple files for the same item
– Continue to run applet while image, sound, or video file is
loading
• Threads may be synchronized
• Garbage collection is done via thread in Java
• Thread behavior not as portable as we would like
(usually because of underlying operating system)
• Each thread has a priority
4

Simple Thread Example


class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName()+" is scheduled on processor: The value of i from "+getName()+" = "+i);

/* try {
} sleep((int)(Math.random() * 1000));
System.out.println("DONE! " + getName()); }
} catch (InterruptedException e)
{ }
*/
public static void main (String[] args) {
new SimpleThread("Thread1").start();
new SimpleThread("Thread2").start();
new SimpleThread("Thread3").start();
}// End main
}//End Class
5

Simple Thread Example: Output


Thread1 is scheduled on processor: The value of i from Thread1 = 0
Thread3 is scheduled on processor: The value of i from Thread3 = 0
Thread2 is scheduled on processor: The value of i from Thread2 = 0
Thread3 is scheduled on processor: The value of i from Thread3 = 1
Thread3 is scheduled on processor: The value of i from Thread3 = 2
Thread2 is scheduled on processor: The value of i from Thread2 = 1
Thread2 is scheduled on processor: The value of i from Thread2 = 2
Thread1 is scheduled on processor: The value of i from Thread1 = 1
.
.
.
Thread1 is scheduled on processor: The value of i from Thread1 = 7
Thread3 is scheduled on processor: The value of i from Thread3 = 9
Thread2 is scheduled on processor: The value of i from Thread2 = 8
Thread2 is scheduled on processor: The value of i from Thread2 = 9
Thread1 is scheduled on processor: The value of i from Thread1 = 8
DONE! Thread3
DONE! Thread2
Thread1 is scheduled on processor: The value of i from Thread1 = 9
DONE! Thread1
6

Thread States: Life Cycle of a Thread

• Thread states
– Born state
• Thread has been created
– Ready (Runnable) state
• Thread’s start method invoked
• Thread can now execute
– Running state
• Thread is assigned a processor and running (dispatching the
thread)
– Dead state
• Thread has completed or exited
• Eventually disposed of by system
7

Thread States: Life Cycle of a Thread

• Thread states
– Blocked state
• Thread must wait on something
– Waiting state
• Thread waits on notification from another thread
– Sleeping state
• Thread waits until designated sleep time expires
8

Fig. 3b.1.a Thread life-cycle statechart diagram, 5e

Born
/new

start

Ready

thread dispatch
quantum expiration (assign a
yield
timeout expires

processor)

I/O completes
interrupt
notifyAll

interrupt

acquire lock
notify

Running

Waiting Sleeping Blocked


Terminate

sleep interval When a thread completes


expires (returns from its run method),
interrupt it reaches the Dead state
(shown here as the final state)
9

Fig. 3b.1.b Thread life-cycle statechart diagram, 10e


10

Thread Priorities and Thread Scheduling

• Java thread priority


– Priority in range 1-10
– Threads with higher priority more important, should be
allocated processor time before lower priority threads
• Timeslicing
– Each thread assigned time on the processor (called a
quantum)
• Thread scheduler keeps highest priority thread(s)
running
• Starvation = lower priority threads never get run
11

Fig. 3b.2 Thread priority scheduling example


Ready threads

Thread.MAX_PRIORITY Priority 10 A B

Priority 9 C

Priority 8

Priority 7 D E F

Priority 6 G

Thread.NORM_PRIORITY Priority 5 H I

Priority 4

Priority 3

Priority 2 J K

Thread.MIN_PRIORITY Priority 1
12

Creating and Executing Threads

• Threads must be started via start() and must


have a run() method
• Sleep state
– Thread method sleep called
– Thread sleeps for a set time interval (int
milliseconds) then awakens
– While sleeping a thread might throw an
InterruptedException
• Good idea to name all threads (for debugging and
in case of run time errors)
• Program that starts thread(s) will not terminate
until last thread dies
13
1 // Fig. 3b.3: ThreadTester.java Outline
2 // Multiple threads printing at different intervals.
3
4 public class ThreadTester { ThreadTester.ja
5
6 public static void main( String [] args )
va
7 {
8 // create and name each thread Lines 9-11
9 PrintThread thread1 = new PrintThread( "thread1" );
create three
10 PrintThread thread2 = new PrintThread( "thread2" );
Lines 15-17
PrintThreads
11 PrintThread thread3 = new PrintThread( "thread3" );
12
13 System.err.println( "Starting threads" );
14
15 thread1.start(); // start thread1 and place it in ready state
16 thread2.start(); // start thread2 and place it in ready state call start methods
17 thread3.start(); // start thread3 and place it in ready state
18
19 System.err.println( "Threads started, main ends\n" );
20
21 } // end main
22
23 } // end class ThreadTester
24
14
25 // class PrintThread controls thread execution Outline
26 class PrintThread extends Thread {
27 private int sleepTime;
28 ThreadTester.ja
29 // assign name to thread by calling superclass constructor PrintThread
va
30 public PrintThread( String name )
extends Thread
31 {
32 super( name ); Line 26
33
34 // pick random sleep time between 0 and 5 seconds
Line 35
35 sleepTime = ( int ) ( Math.random() * 5001 );
36 } Constructor initializes
37 Line 39
38 // method run is the code to be executed by new thread
sleepTime to 0-
39 public void run() 5000
40 { When the thread
41 // put thread to sleep for sleepTime amount of time enters the running
42 try {
43 System.err.println(
state, run is called
44 getName() + " going to sleep for " + sleepTime );
45
46 Thread.sleep( sleepTime );
47 }
48
15
49 // if thread interrupted during sleep, print stack trace Outline
50 catch ( InterruptedException exception ) {
51 exception.printStackTrace();
52 } ThreadTester.ja
53
54 // print thread name
va
55 System.err.println( getName() + " done sleeping" );
56
57 } // end method run
58
59 } // end class PrintThread

Starting threads
Threads started, main ends

thread1 going to sleep for 1217


thread2 going to sleep for 3989
thread3 going to sleep for 662
thread3 done sleeping
thread1 done sleeping
thread2 done sleeping
16
Outline
Starting threads
thread1 going to sleep for 314
thread2 going to sleep for 1990 ThreadTester.ja
Threads started, main ends
va
thread3 going to sleep for 3016
thread1 done sleeping
thread2 done sleeping
thread3 done sleeping
17

Thread Synchronization

• Multiple threads may share an object (database,


printer, buffer, …) and may need to be
synchronized
• Java uses monitors for thread synchronization
• The sychronized keyword
– Every synchronized method of an object has a monitor
– One thread inside a synchronized method at a time
– All other threads block until method finishes
– Next highest priority thread runs when method finishes
– Thread can wait to allow other synchronized threads to run
– Thread can notify waiting threads or notifyAll
18
Producer/Consumer Relationship without
Synchronization
• Buffer
– Shared memory region
• Producer thread
– Calls wait if consumer has not read previous message in
buffer
– Writes to empty buffer and calls notify for consumer
• Consumer thread
– Calls wait if buffer empty or unchanged
– Reads data from buffer and calls notify for producer
• Without synchronization
– Produced data might not be consumed
– Some data might be consumed multiple times
19
1 // Fig. 3b.4: Buffer.java Outline
2 // Buffer interface specifies methods called by Producer and Consumer.
3
4 public interface Buffer { Buffer.java
5 public void set( int value ); // place value into Buffer
6 public int get(); // return value from Buffer
7 }
20
1 // Fig. 3b.5: Producer.java Outline
2 // Producer's run method controls a thread that
3 // stores values from 1 to 4 in sharedLocation.
4 Producer
Producer.java
extends
5 public class Producer extends Thread {
6 private Buffer sharedLocation; // reference to shared object
Thread
7 Line 5
8 // constructor
This is a shared object
9 public Producer( Buffer shared ) Line 6
10 {
11 super( "Producer" );
12 sharedLocation = shared;
Line 16
13 }
14 Lines 22-23
15 // store values from 1 to 4 in sharedLocation
16 public void run() Method run is overridden
17 {
18 for ( int count = 1; count <= 4; count++ ) {
19
20 // sleep 0 to 3 seconds, then place value in Buffer
21 try {
22 Thread.sleep( ( int ) ( Math.random() * 3001 ) ); The thread goes to sleep,
23 sharedLocation.set( count );
then the buffer is set
24 }
25
21
26 // if sleeping thread interrupted, print stack trace Outline
27 catch ( InterruptedException exception ) {
28 exception.printStackTrace();
29 } Producer.java
30
31 } // end for
32
33 System.err.println( getName() + " done producing." +
34 "\nTerminating " + getName() + ".");
35
36 } // end method run
37
38 } // end class Producer
22
1 // Fig. 3b.6: Consumer.java Outline
2 // Consumer's run method controls a thread that loops four
3 // times and reads a value from sharedLocation each time.
4 Consumer
Consumer.java
extends
5 public class Consumer extends Thread {
6 private Buffer sharedLocation; // reference to shared object
Thread
7 Line 5
8 // constructor
This is a shared object
9 public Consumer( Buffer shared ) Line 6
10 {
11 super( "Consumer" );
12 sharedLocation = shared;
Line 16
13 }
14 Lines 24-25
15 // read sharedLocation's value four times and sum the values
16 public void run() Method run is overridden
17 {
18 int sum = 0;
19
20 for ( int count = 1; count <= 4; count++ ) {
21
22 // sleep 0 to 3 seconds, read value from Buffer and add to sum
23 try {
24 Thread.sleep( ( int ) ( Math.random() * 3001 ) ); The thread goes to sleep,
25 sum += sharedLocation.get(); then the buffer is read
26 }
27
23
28 // if sleeping thread interrupted, print stack trace Outline
29 catch ( InterruptedException exception ) {
30 exception.printStackTrace();
31 } Consumer.java
32 }
33
34 System.err.println( getName() + " read values totaling: " + sum +
35 ".\nTerminating " + getName() + ".");
36
37 } // end method run
38
39 } // end class Consumer
24
1 // Fig. 3b.7: UnsynchronizedBuffer.java Outline
2 // UnsynchronizedBuffer represents a single shared integer.
3
4 public class UnsynchronizedBuffer implements Buffer {
This class implements the
UnsynchronizedB
Buffer interface
5 private int buffer = -1; // shared by producer and consumer threads
6
uffer.java
7 // place value into buffer
8 public void set( int value )
The data is a single
Line 4integer
9 {
10 System.err.println( Thread.currentThread().getName() + This method sets
Linethe
5 value
11 " writes " + value ); in the buffer
12
13 buffer = value; Lines 8 and 13
14 }
15 Lines 17 and 22
16 // return value from buffer
17 public int get()
18 {
19 System.err.println( Thread.currentThread().getName() +
20 " reads " + buffer );
This method reads the
21 value in the buffer
22 return buffer;
23 }
24
25 } // end class UnsynchronizedBuffer
25
1 // Fig. 3b.8: SharedBufferTest.java Outline
2 // SharedBufferTest creates producer and consumer threads.
3
4 public class SharedBufferTest { SharedBufferTes
5
6 public static void main( String [] args )
t.java
7 {
8 // create shared object used by threads Line 9
9 Buffer sharedLocation = new UnsynchronizedBuffer(); Create a Buffer object
10
Lines 12-13
11 // create producer and consumer objects
12 Producer producer = new Producer( sharedLocation ); Create a Producer and
13 Consumer consumer = new Consumer( sharedLocation ); Lines 15-16
a Consumer
14
15 producer.start(); // start producer thread
16 consumer.start(); // start consumer thread Start the Producer and
17 Consumer threads
18 } // end main
19
20 } // end class SharedCell
26
Outline
Consumer reads -1
Producer writes 1
Consumer reads 1 SharedBufferTes
Consumer reads 1
Consumer reads 1
t.java
Consumer read values totaling: 2.
Terminating Consumer.
Producer writes 2
Producer writes 3
Producer writes 4
Producer done producing.
Terminating Producer.

Producer writes 1
Producer writes 2
Consumer reads 2
Producer writes 3
Consumer reads 3
Producer writes 4
Producer done producing.
Terminating Producer.
Consumer reads 4
Consumer reads 4
Consumer read values totaling: 13.
Terminating Consumer.
27
Outline
Producer writes 1
Consumer reads 1
Producer writes 2 SharedBufferTes
Consumer reads 2
Producer writes 3
t.java
Consumer reads 3
Producer writes 4
Producer done producing.
Terminating Producer.
Consumer reads 4
Consumer read values totaling: 10.
Terminating Consumer.
28
Producer/Consumer Relationship with
Synchronization
• Synchronize threads to ensure correct data
– Consumer consumes only after producer produces
– Producer produces only after consumer consumes
29
1 // Fig. 3b.9: SynchronizedBuffer.java This class implements Outline
the
2 // SynchronizedBuffer synchronizes access to a single shared integer. Buffer interface
3
4 public class SynchronizedBuffer implements Buffer { SynchronizedBuf
5 private int buffer = -1; // shared by producer and consumer threads
6
Remember
private int occupiedBufferCount = 0; // count of occupied buffers
fer.java
the number of
7 filled spaces
8 // place value into buffer Line 4
9 public synchronized void set( int value )
Method set is declared
10 { synchronized
Line 6
11 // for output purposes, get name of thread that called this method
12 String name = Thread.currentThread().getName(); Get the name of the thread
13 Line 9
14 // while there are no empty locations, place thread in waiting state
15 while ( occupiedBufferCount == 1 ) { Line 12
16
17 // output thread information and buffer information, then wait
18 try { Wait while the Lines
buffer15 and 21
is filled
19 System.err.println( name + " tries to write." );
20 displayState( "Buffer full. " + name + " waits." );
21 wait();
22 }
23
24 // if waiting thread interrupted, print stack trace
25 catch ( InterruptedException exception ) {
26 exception.printStackTrace();
27 }
30
28 Outline
29 } // end while
30
31 buffer = value; // set new buffer value Write to the buffer
SynchronizedBuf
32
33 // indicate producer cannot store another value
fer.java
34 // until consumer retrieves current buffer value
35 ++occupiedBufferCount; Line 31
Increment the buffer count
36
37 displayState( name + " writes " + buffer );
Line 35
38
39 notify(); // tell waiting thread to enter ready state Alert a waiting thread
40 Line 39
41 } // end method set; releases lock on SynchronizedBuffer
42 Line 44
43 // return value from buffer
44 public synchronized int get()
Method get is declared
45 { synchronized
Line 47
46 // for output purposes, get name of thread that called this method
47 String name = Thread.currentThread().getName(); Get the name of the thread
48
31
49 // while no data to read, place thread in waiting state Outline
50 while ( occupiedBufferCount == 0 ) {
51
52 // output thread information and buffer information, then wait SynchronizedBuf
53 try { Wait while the buffer is empty
54 System.err.println( name + " tries to read." );
fer.java
55 displayState( "Buffer empty. " + name + " waits." );
56 wait(); Lines 50 and 56
57 }
58
Line 68
59 // if waiting thread interrupted, print stack trace
60 catch ( InterruptedException exception ) {
61 exception.printStackTrace(); Line 72
62 }
63 Line 74
64 } // end while
65
66 // indicate that producer can store another value
67 // because consumer just retrieved buffer value
68 --occupiedBufferCount; Decrement the buffer count
69
70 displayState( name + " reads " + buffer );
71
72 notify(); // tell waiting thread to become ready to execute Alert a waiting thread
73
74 return buffer; Return the buffer
32
75 Outline
76 } // end method get; releases lock on SynchronizedBuffer
77
78 // display current operation and buffer state SynchronizedBuf
79 public void displayState( String operation )
80 {
fer.java
81 StringBuffer outputLine = new StringBuffer( operation );
82 outputLine.setLength( 40 );
83 outputLine.append( buffer + "\t\t" + occupiedBufferCount );
84 System.err.println( outputLine );
85 System.err.println();
86 }
87
88 } // end class SynchronizedBuffer
33
1 // Fig. 3b.10: SharedBufferTest2.java Outline
2 // SharedBufferTest2creates producer and consumer threads.
3
4 public class SharedBufferTest2 { SharedBufferTes
5
6 public static void main( String [] args )
t2.java
7 { Create a Buffer object
8 // create shared object used by threads; we use a SynchronizedBuffer Line 11
9 // reference rather than a Buffer reference so we can invoke
10 // SynchronizedBuffer method displayState from main
Line 19
11 SynchronizedBuffer sharedLocation = new SynchronizedBuffer();
12
13 // Display column heads for output Lines 22-23
14 StringBuffer columnHeads = new StringBuffer( "Operation" );
15 columnHeads.setLength( 40 );
16 columnHeads.append( "Buffer\t\tOccupied Count" );
17 System.err.println( columnHeads );
18 System.err.println();
19 sharedLocation.displayState( "Initial State" ); Output initial state
20
21 // create producer and consumer objects
22 Producer producer = new Producer( sharedLocation ); Create a Producer and
23 Consumer consumer = new Consumer( sharedLocation );
a Consumer
24
34
25 producer.start(); // start producer thread Outline
26 consumer.start(); // start consumer thread Start the Producer and
27 Consumer threads
28 } // end main SharedBufferTes
29
30 } // end class SharedBufferTest2
t2.java

Lines 25-26
Operation Buffer Occupied Count

Initial State -1 0

Consumer tries to read.


Buffer empty. Consumer waits. -1 0

Producer writes 1 1 1

Consumer reads 1 1 0

Consumer tries to read.


Buffer empty. Consumer waits. 1 0

Producer writes 2 2 1

Consumer reads 2 2 0

Producer writes 3 3 1
35
Outline
Consumer reads 3 3 0

Consumer tries to read. SharedBufferTes


Buffer empty. Consumer waits. 3 0
t2.java
Producer writes 4 4 1

Consumer reads 4 4 0
Producer done producing.
Terminating Producer.

Consumer read values totaling: 10.


Terminating Consumer.

Operation Buffer Occupied Count

Initial State -1 0

Consumer tries to read.


Buffer empty. Consumer waits. -1 0

Producer writes 1 1 1

Consumer reads 1 1 0

Producer writes 2 2 1
36
Producer tries to write. Outline
Buffer full. Producer waits. 2 1

Consumer reads 2 2 0 SharedBufferTes


Producer writes 3 3 1
t2.java

Consumer reads 3 3 0

Producer writes 4 4 1

Producer done producing.


Terminating Producer.
Consumer reads 4 4 0

Consumer read values totaling: 10.


Terminating Consumer.

Operation Buffer Occupied Count

Initial State -1 0

Producer writes 1 1 1

Consumer reads 1 1 0

Producer writes 2 2 1
37
Consumer reads 2 2 0 Outline
Producer writes 3 3 1
SharedBufferTes
Consumer reads 3 3 0
t2.java
Producer writes 4 4 1

Producer done producing.


Terminating Producer.
Consumer reads 4 4 0

Consumer read values totaling: 10.


Terminating Consumer.
38

Daemon Threads

• Run for benefit of other threads


– Do not prevent program from terminating
– Garbage collector is a daemon thread
• Set daemon thread with method call
threadname.setDaemon(true)
39

Runnable Interface

• A class cannot extend more than one class


• Implement Runnable for multithreading support
– public class UserInfo extends JFrame
implements Runnable
{
Thread st;

st.start();

public void run()
{…}
}
40
Discovering Design Patterns: Concurrent Design
Patterns
• Concurrency Design Patterns
– Single-Threaded Execution design pattern
• Stops several threads from invoking a method concurrently
(synchronized)
– Guarded Suspension design pattern
• Suspends and resumes a thread’s activity when a condition met
(wait and notify)
– Balking design pattern
• Causes method to balk if an object occupies a certain state
(wait or throw exception)
41
Discovering Design Patterns: Concurrent Design
Patterns
• Concurrency Design Patterns
– Read/Write Lock design pattern
• Multiple read on an object but exclusive write (wait and
notify)
– Two-Phase Termination design pattern
• Uses two-phase termination process to ensure resources freed
(can be done in run method)
42

• Ref: Deitel & Deitel, 4e, 5e, 10e

• For doubts contact at:


– adarsh.patel@vitbhopal.ac.in
1

3.a Exception Handling


3.a.1 Introduction
3.a.2 Exception-Handling Overview
3.a.3 Exception-Handling Example: Divide by Zero
3.a.4 Java Exception Hierarchy
3.a.5 Rethrowing an Exception
3.a.6 finally Clause
3.a.7 Stack Unwinding
3.a.8 printStackTrace, getStackTrace
and getMessage
3.a.10 Declaring New Exception Types
3.a.11 Constructors and Exception Handling
2

3.a.1 Introduction

• Exception handling
– Exception is an indication of problem during execution
• “exception” occurs infrequently
• e.g., divide by zero
– Promotes robust and fault-tolerant software
– Java’s Exception Handling nearly identical to C++
3

3.a.2 Exception-Handling Overview

• Mixing program code with error-handling code


makes program difficult to read, modify, maintain,
debug
• Uses of exception handling
– Process exceptions from program components
– Handle exceptions in a uniform manner in large projects
– Remove error-handling code from “main line” of execution
• A method detects an error and throws an exception
– Exception handler processes the error
– Uncaught exceptions yield adverse effects
• Might terminate program execution
4

3.a.2 Exception-Handling Overview

• Code that could generate errors put in try blocks


– Code for error handling enclosed in a catch clause
– The finally clause always executes
• Termination model of exception handling
– The block in which the exception occurs expires
immediately
• throws clause specifies exceptions method
throws (or by methods it calls)
• Simple problems that can easily be fixed can be
handled as “errors”
• Use Exception Handling for more complicated
situations
5

3.a.2 Exception-Handling Overview

• Typical exceptions – array index out of range,


overflow, division by zero, invalid method
parameters, memory allocation problems
• Most significant use of Exception Handling –
problem occurs in a method, but resolution must
be done in calling method (one or more levels
above)
• Method that detects problem “throws an
exception”
• Method that resolves problem “catches the
exception”
6

3.a.3 Exception-Handling Example: Divide by Zero

• Common programming mistake


• Throws ArithmeticException
• NumberFormatException is thrown if
parseInt, parseDouble, etc. are given
bad strings
• Program catches an exception in an “appropriate”
catch block (same class or superclass)
• Program continues executing with code after the
last catch block (not back inside the try block)
7
1 // Fig. 3.a.1: DivideByZeroTest.java Outline
2 // An exception-handling example that checks for divide-by-zero.
3 import java.awt.*;
4 import java.awt.event.*; DivideByZeroTes
5 import javax.swing.*;
6
t.java
7 public class DivideByZeroTest extends JFrame
8 implements ActionListener {
9
10 private JTextField inputField1, inputField2, outputField;
11 private int number1, number2, result;
12
13 // set up GUI
14 public DivideByZeroTest()
15 {
16 super( "Demonstrating Exceptions" );
17
18 // get content pane and set its layout
19 Container container = getContentPane();
20 container.setLayout( new GridLayout( 3, 2 ) );
21
22 // set up label and inputField1
23 container.add(
24 new JLabel( "Enter numerator ", SwingConstants.RIGHT ) );
25 inputField1 = new JTextField();
26 container.add( inputField1 );
8
27 Outline
28 // set up label and inputField2; register listener
29 container.add( new JLabel( "Enter denominator and press Enter ",
30 SwingConstants.RIGHT ) ); DivideByZeroTes
31 inputField2 = new JTextField();
32 container.add( inputField2 );
t.java
33 inputField2.addActionListener( this );
34 Line 51
35 // set up label and outputField
36 container.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
Lines 52-53
37 outputField = new JTextField();
38 container.add( outputField );
39
40 setSize( 425, 100 );
41 setVisible( true );
42
43 } // end DivideByZeroTest constructor
44
45 // process GUI events The try block
46 public void actionPerformed( ActionEvent event )
47 {
48 outputField.setText( "" ); // clear outputField Read integers from
49
JTextFields
50 // read two numbers and calculate quotient
51 try {
52 number1 = Integer.parseInt( inputField1.getText() );
53 number2 = Integer.parseInt( inputField2.getText() );
9
54
Method quotientOutline
55 result = quotient( number1, number2 );
56 outputField.setText( String.valueOf( result ) );
attempts division
57 } DivideByZeroTes
58
59 // process improperly formatted input
t.java
Catch
60 catch ( NumberFormatException numberFormatException ) {
61 JOptionPane.showMessageDialog( this,
NumberFormatException
Line 55
62 "You must enter two integers", "Invalid Number Format",
63 JOptionPane.ERROR_MESSAGE );
Line 60
64 }
65
66 // process attempts to divide by zero Line 67
Catch
67 catch ( ArithmeticException arithmeticException ) {
68 JOptionPane.showMessageDialog( this,
ArithmeticException
Line 77
69 arithmeticException.toString(), "Arithmetic Exception",
70 JOptionPane.ERROR_MESSAGE );
71 }
72
73 } // end method actionPerformed
74
75 // demonstrates throwing an exception when a divide-by-zero occurs
76 public int quotient( int numerator, int denominator )
77 throws ArithmeticException Method quotient throws
78 { ArithmeticException
79 return numerator / denominator;
80 }
10
81 Outline
82 public static void main( String args[] )
83 {
84 DivideByZeroTest application = new DivideByZeroTest(); DivideByZeroTes
85 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
86 }
t.java
87
88 } // end class DivideByZeroTest
11

3.a.4 Java Exception Hierarchy

• Exceptions (like everything in Java) are objects


• Superclass Throwable
– Subclass Exception
• Exceptional situations
• Should be caught by program
– Subclass Error
• Typically not caught by program
• Checked exceptions (include any you create)
– “catch or declare” requirement
• Unchecked exceptions (subclass of
RuntimeException, e.g.,
NumberFormatException)
– Good idea to catch, but not required
12
Fig. 3.a.2 Inheritance hierarchy for class
Throwable

Throwable

Exception Error

RuntimeException IOException AWTError ThreadDeath OutOfMemoryError


13

3.a.5 Rethrowing an Exception

• Rethrow exception if catch cannot handle it


• This typically involves a try block (with its catch
blocks) inside another try block
• Inner catch block throws it to the outer catch block
… or even on to the calling method
14

3.a.6 finally Clause

• Resource leak
– Caused when resources are not released by a program
– files, database connections, network connections
• The finally block (optional)
– Appears after catch blocks
– Always executes whether or not any exception is thrown
– Use to release resources (e.g., close file)
15
1 // Fig. 3.a.3: UsingExceptions.java Outline
2 // Demonstration of the try-catch-finally exception handling mechanism.
3 public class UsingExceptions {
4 UsingExceptions
5 public static void main( String args[] )
6 {
.java
7 try {
8 throwException(); // call method throwException
9 }
10
11 // catch Exceptions thrown by method throwException
12 catch ( Exception exception ) {
13 System.err.println( "Exception handled in main" );
14 }
15
16 doesNotThrowException();
17 }
18
19 // demonstrate try/catch/finally
20 public static void throwException() throws Exception
21 {
22 // throw an exception and immediately catch it
23 try {
24 System.out.println( "Method throwException" );
25 throw new Exception(); // generate exception
26 }
16
27 Outline
28 // catch exception thrown in try block
29 catch ( Exception exception ) {
30 System.err.println( UsingExceptions
31 "Exception handled in method throwException" );
32 throw exception; // rethrow for further processing Rethrow .java
Exception
33
34 // any code here would not be reached Line 32
35 }
36
Lines 38-40
37 // this block executes regardless of what occurs in try/catch
38 finally {
The finally block executes,
39 System.err.println( "Finally executed in throwException" ); even though Exception thrown
40 }
41
42 // any code here would not be reached
43
44 } // end method throwException
45
46 // demonstrate finally when no exception occurs
47 public static void doesNotThrowException()
48 {
49 // try block does not throw an exception
50 try {
51 System.out.println( "Method doesNotThrowException" );
52 }
17
53 Outline
54 // catch does not execute, because no exception thrown
55 catch ( Exception exception ) {
56 System.err.println( exception ); UsingExceptions
57 }
58
.java
59 // this clause executes regardless of what occurs in try/catch
The finally block
60 finally { Lines 60-63
61 System.err.println( always executes
62 "Finally executed in doesNotThrowException" );
63 }
64
65 System.out.println( "End of method doesNotThrowException" );
66
67 } // end method doesNotThrowException
68
69 } // end class UsingExceptions

Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException
18

3.a.7 Stack Unwinding

• Exception not caught in scope


– Method terminates
– Stack unwinding occurs (all local variables go out of scope,
control reverts to statement that called method)
– Another attempt to catch exception (if this is inside a try
block)
– And on and on and on….
19
1 // Fig. 3.a.4: UsingExceptionsNew.java Outline
2 // Demonstration of stack unwinding.
3 public class UsingExceptionsNew {
4 UsingExceptions
5 public static void main( String args[] )
6 {
.java
7 // call throwException to demonstrate stack unwinding
8 try { Line 9
9 throwException();
Call method
10 } throwException
Line 13
11
12 // catch exception thrown in throwException
Catch Exception
Line 19 from
13 catch ( Exception exception ) {
14 System.err.println( "Exception handled in main" );
method throwExcetion
15 } Line 24
16 }
17
18 // throwException throws exception that is not caught in this method
19 public static void throwException() throws Exception
20 {
21 // throw an exception and catch it in main Method declares a
22 try { throws clause
23 System.out.println( "Method throwException" );
24 throw new Exception(); // generate exception
25 } Throw an Exception
26
20
27 // catch is incorrect type, so Exception is not caught Outline
28 catch ( RuntimeException runtimeException ) {
29 System.err.println(
30 "Exception handled in method throwException" ); UsingExceptions
31 }
32
.java
33 // finally clause always executes
34 finally {
35 System.err.println( "Finally is always executed" );
36 }
37
38 } // end method throwException
39
40 } // end class UsingExceptions

Method throwException
Finally is always executed
Exception handled in main
21
3.a.8 printStackTrace, getStackTrace
and getMessage
• Throwable class
– Method printStackTrace
• Prints method call stack (helpful in debugging)
– Method getStackTrace
• Obtains stack-trace information
– Method getMessage
• Returns descriptive string
• Uncaught exception – default exception handler –
displays complete stack trace
22
1 // Fig. 3.a.5: UsingExceptionsNew2.java Outline
2 // Demonstrating getMessage and printStackTrace from class Exception.
3 public class UsingExceptionsNew2 {
4 UsingExceptions
5 public static void main( String args[] )
6 {
.java
7 try {
8 method1(); // call method1 Line 8
Call method1
9 }
10
Lines 13-14
11 // catch Exceptions thrown from method1
12 catch ( Exception exception ) { Print information generated
13 System.err.println( exception.getMessage() + "\n" ); Lines 25-26
by getMessage and
14 exception.printStackTrace();
printStackTrace
15
16 // obtain the stack-trace information
17 StackTraceElement[] traceElements = exception.getStackTrace();
18
19 System.out.println( "\nStack trace from getStackTrace:" );
20 System.out.println( "Class\t\tFile\t\t\tLine\tMethod" );
Print StackTraceElements
21
22 // loop through traceElements to get exception description
23 for ( int i = 0; i < traceElements.length; i++ ) {
24 StackTraceElement currentElement = traceElements[ i ];
25 System.out.print( currentElement.getClassName() + "\t" );
26 System.out.print( currentElement.getFileName() + "\t" );
23
27 System.out.print( currentElement.getLineNumber() + "\t" ); Outline
28 System.out.print( currentElement.getMethodName() + "\n" );
29
30 } // end for statement UsingExceptions
31
32 } // end catch
.java
Print StackTraceElements
33
34 } // end method main Lines 27-28
35
36 // call method2; throw exceptions back to main
method1 Line 37 a
declares
37 public static void method1() throws Exception
38 { throw clause
39 method2(); Line 39
Call method2
40 }
41 Line 43
42 // call method3; throw exceptions back to method1
43 public static void method2() throws Exception
method2 declares a
44 { throwLine 45
clause
45 method3(); Call method3
46 } Line 49
47
48 // throw Exception back to method2
49 public static void method3() throws Exception
method3Line 51 a
declares
50 { throw clause
51 throw new Exception( "Exception thrown in method3" );
52 } Throw an
Exception that
propagates back to
main
24
53 Outline
54 } // end class Using Exceptions

Exception thrown in method3


UsingExceptions
java.lang.Exception: Exception thrown in method3 .java
at UsingExceptions.method3(UsingExceptions.java:51)
at UsingExceptions.method2(UsingExceptions.java:45)
at UsingExceptions.method1(UsingExceptions.java:39)
at UsingExceptions.main(UsingExceptions.java:8)

Stack trace from getStackTrace:


Class File Line Method
UsingExceptions UsingExceptions.java 51 method3
UsingExceptions UsingExceptions.java 45 method2
UsingExceptions UsingExceptions.java 39 method1
UsingExceptions UsingExceptions.java 8 main
25

3.a.10 Declaring New Exception Types

• Extend existing exception class

public class TooSmallException extends


ArithmeticException
{
public TooSmallException ()
{
super (“Value is less than 100”);
}
public TooSmallException (String message)
{
super (message);
}
}
26

3.a.11 Constructors and Exception Handling

• Constructor cannot return a value to indicate an


error
• Throw exception if constructor causes error
– For example, if invalid initialization value given to
constructor and there is no sensible way to correct this
• Ref: Deitel and Deitel

• For doubts contact at:


adarsh.patel@vitbhopal.ac.in
Inheritance
Inheritance
Inheritance
class Doctor class Footballer class Businessman
Attributes: Attributes: Attributes:
Age, Height, Weight Age, Height, Weight Age, Height, Weight
Methods: Methods: Methods:
Talk() Talk() Talk()
Walk() Walk() Walk()
Eat() Eat() Eat()
Diagnose() Playfootball() Runbusiness()

• All of the classes have common attributes (Age, Height, Weight) and methods (Walk,
Talk, Eat).
• However, they have some special skills like Diagnose, Playfootball and Runbusiness.
• In each of the classes, you would be copying the same code for Walk, Talk and Eat for
each character.
Inheritance
• The mechanism of a class to derive properties and
characteristics from another class is called Inheritance. Base Class
• It is the most important feature of Object Oriented
Programming.
• Inheritance is the process, by which class can
acquire(reuse) the properties and methods of another Derived Class
class.
• Base Class: The class whose properties are inherited by sub
class is called Base Class/Super class/Parent class.
• Derived Class: The class that inherits properties from
another class is called Sub class/Derived Class/Child class.
• Inheritance is implemented using super class and sub class
relationship in object-oriented languages.
Inheritance
class Person
class Person
is called
Attributes: Base class
Age, Height, Weight
Methods:
Talk() , Walk(), Eat()

class Doctor class Footballer class Businessman


Methods: Methods: Methods:
Diagnose() Playfootball() Runbusiness()

These classes
are called
Derived class
Inheritance
class Vehicle
Attributes:
Engine_no, color
Methods:
apply_breaks()

class Car class Bus class Truck


Attributes: Attributes: Attributes:
Private_vehicle Public_vehicle Goods_vehicle
Inheritance: Advantages
• Promotes reusability
• When an existing code is reused, it leads to less
development and maintenance costs. Base Class

• It is used to generate more dominant


objects.
• Avoids duplicity and data redundancy. Derived Class
• Inheritance makes the sub classes follow a
standard interface.
Implementing Inheritance

• Subclass-Superclass Relationship
Introduction
• Inheritance is the process, by which a class can acquire(reuse) the properties
and methods of another class.
• The mechanism of deriving a new class from an old class is called inheritance.
• The new class is called derived class and old class is called base class.
• The derived class may have all the features of the base class and the
programmer can add new features to the derived class.
• Inheritance is also known as “IS-A relationship” between parent and child
classes.
• For Example :
• Car IS A Vehicle
• Bike IS A Vehicle
• EngineeringCollege IS A College
• MedicalCollege IS A College
• MCACollege IS A College
Inheritance Example
class Vehicle
Attributes:
Engineno, color
Methods:
applybreaks()

class Car class Bus class Truck


Attributes: Attributes: Attributes:
privatevehicle publicvehicle goodsvehicle
How to implement Inheritance in java
• To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
Syntax:
class subclass-name extends superclass-name
{
// body of class…
}
Implementing Inheritance in java
class A
{
Class A
//SuperClass or ParentClass or BaseClass Base Class
}
the keyword “extends” is used to create a subclass of A

class B extends A
Class B
{ Derived Class
//SubClass or ChildClass or DerivedClass
}
Implementing Inheritance in java
1. class Person Person
2. { name:String
3. String name; Contact:long
4. long contact;
5. }

6. class Employee extends Person


7. {
Employee Customer
8. int empID;
9. String designation; empID:int customerID:int
10. } Designation:Strin InvoiceNo:int
g
11. Class Customer extends Person
12. {
13. int customerID;
14. int invoiceNo;
15. }
Implementing Inheritance in java
1. class Person
Person
2. {
3. String name; name:String
Contact:long
4. long contact;
5. public void dispContact() dispContact():void
6. { System.out.println(“num=”+contact);
7. }
8. }
9. class Employee extends Person
10. {
11. int empID; Employee Customer
12. String designation; empID:int customerID:int
13. } Designation:Strin InvoiceNo:int
14. Class Customer extends Person g
15. {
16. int customerID;
17. int invoiceNo;
18. }
Property of Inheritance
Property of Inheritance
A class member that has been declared as
private will remain private to its class. It is not
accessible by any code outside its class,
Base class A can’t access attributes including subclasses.
and methods of Derived Class B Class A
Base Class

Derived Class B can’t access


private members of Base class A

Class B
Derived Class Derived Class B can access attributes
and methods of Base class A
Inheritance by Example
Example1: InheritanceDemo1
A
#i:int
~j:int
showij():void

B
~k:int
showk():void
add():void
Example1: InheritanceDemo.java
1. class A{ 16. class InheritanceDemo{
2. protected int i; 17. public static void main(String[]
3. int j; args)
4. void showij(){ 18. {
5. System.out.println("i="+i+" j="+j); 19. A superObjA= new A();
6. } 20. superObjA.i=10;
7. } 21. superObjA.j=20;

8. class B extends A{ //inheritance 22. B subObjB= new B();


9. int k; 23. subObjB.k=30;
10. void showk(){
11. System.out.println("k="+k); 24. superObjA.showij();
12. } 25. subObjB.showk();
13. void add(){ 26. subObjB.add();
System.out.println("i+j+k="+(i+j+k)); 27. } Outpu
t
14. } 28. } i=10 j=20
15. } k=30
i+j+k=30
Types of Inheritance in Java
1. Single Inheritance 2. Hierarchical Inheritance 3. Multilevel Inheritance

A A A

B C B
B

4. Multiple Inheritance 5. Hybrid Inheritance

A B A Note: Multiple and Hybrid


Inheritance is not supported in Java
with the Class Inheritance, we can
B C still use those Inheritance with
C Interface which we will learn in later
part of the Unit
D
Single Inheritance A

B
Single Inheritance: InheritanceDemo.java
1. class A{ 16. class InheritanceDemo{
2. protected int i; 17. public static void main(String[]
3. int j; args)
4. void showij(){ 18. {
5. System.out.println("i="+i+" j="+j); 19. A superObjA= new A();
6. } 20. superObjA.i=10;
7. } 21. superObjA.j=20;

8. class B extends A{ //inheritance 22. B subObjB= new B();


9. int k; 23. subObjB.i=100 A
10. void showk(){ 24. subObjB.j=100;
11. System.out.println("k="+k); 25. subObjB.k=30;
12. } B
13. void add(){ 26. superObjA.showij();
System.out.println("i+j+k="+(i+j+k)); 27. subObjB.showk(); Outpu
t
14. } 28. subObjB.add(); i=10 j=20
15. } 29. } k=30
30. } i+j+k=230
Hierarchical Inheritance A

B C
1. class A{ 14.class C extends A{
2. protected int i; 15. int m;
3. int j; 16. void showm(){
OOP Java is the easiest, scoring and my favorite subject

4. void showij(){ 17. System.out.println("inside


5. System.out.println("inside class C:k="+m);
class A:i="+i+" j="+j); 18. }
6. } 19. void add_ijm(){
7. } 20. System.out.println(i+"+"+j+
"+"+m+"="+(i+j+m));
8. class B extends A{ 21. }
9. int k; 22.}
10. void showk(){
System.out.println("inside
class B:k="+k); A
11. }
12. void add_ijk(){
B C
System.out.println(i+"+"+j+"+"+
k+"="+(i+j+k)); InheritanceLevel.java
13. }}
23. class InheritanceLevel{
24. public static void main(String[] args) {
InheritanceLevel.java
25. A superObjA= new A(); OOP Java is the easiest, scoring and my favorite subject

26. superObjA.i=10;
27. superObjA.j=20;
28. superObjA.showij();

29. B subObjB= new B(); A


30. subObjB.i=100;
31. subObjB.j=200;
32. subObjB.k=300; B C
33. subObjB.showk();
34. subObjB.add_ijk();

35. C subObjC= new C(); Outpu


t
36. subObjC.i=1000; inside class A:i=10 j=20
37. subObjC.j=2000;; inside class B:k=300
38. subObjC.m=3000; 100+200+300=600
39. subObjC.showm(); inside class C:k=3000
40. subObjC.add_ijm(); 1000+2000+3000=6000
41. }
42. }
A

Multilevel Inheritance C
1. class A{ 14.class C extends B{
2. protected int i; 15. int m;
3. int j; 16. void showm(){
OOP Java is the easiest, scoring and my favorite subject

4. void showij(){ 17. System.out.println("inside


5. System.out.println("inside class C:k="+m);
class A:i="+i+" j="+j); 18. }
6. } 19. void add_ijkm(){
7. } 20. System.out.println(i+"+"+j+
"+"+k+"+"+m+"="+(i+j+k+m));
8. class B extends A{ 21. }
9. int k; 22.}
10. void showk(){
System.out.println("inside A
class B:k="+k);
11. } B
12. void add_ijk(){
System.out.println(i+"+"+j+"+"+ C
k+"="+(i+j+k));
13. }} InheritanceMultilevel.java
23. class InheritanceMultilevel{
24. public static void main(String[] args) { InheritanceMultilevel.java
25. A superObjA= new A();
26. superObjA.i=10; OOP Java is the easiest, scoring and my favorite subject

27. superObjA.j=20; A
28. superObjA.showij();

29. B subObjB= new B(); B


30. subObjB.i=100;
31. subObjB.j=200;
C
32. subObjB.k=300;
33. subObjB.showk();
34. subObjB.add_ijk();

35. C subObjC= new C(); Outpu


36. subObjC.i=1000; t
37. subObjC.j=2000; inside class A:i=10 j=20
38. subObjC.k=3000; inside class B:k=300
39. subObjC.m=4000; 100+200+300=600
40. subObjC.showm(); inside class C:k=4000
41. subObjC.add_ijkm(); 1000+2000+3000+4000=10000
42. }
Derived Class with Constructor
Derived Class with Constructor
Cube CubeInherit
# height: double cw1:CubeWeight
# width: double cw2:CubeWeight
# depth: double
main(): void
Cube()
volume(): double

CubeWeight
# weigth: double
CubeWeight(double, double, double,
double):double
1. class Cube{ 22. class CubeInherit{
2. protected double 23. public static void main(String[] args) {
height,width,depth; 24. CubeWeight cw1= new
OOP Java is the easiest, scoring and my favorite subject

3. Cube(){ 25. CubeWeight(10,10,10,20.5);


4. System.out.println("inside 26. CubeWeight cw2= new
5. default Constructor:CUBE"); 27. CubeWeight(100,100,100,200.5);
6. } 28. System.out.println("cw1.volume()="
7. double volume(){ +cw1.volume());
8. return height*width*depth; 29. System.out.println("cw2.volume()="
9. } +cw2.volume());
10. } 30. }}
11. class CubeWeight extends Cube{
12. double weigth;
13. CubeWeight(double h,double w,double d, double m)
14. {
15. System.out.println("inside Constructor:
Outpu CubeInherit.java
t
16. CUBEWEIGTH"); inside default Constructor:CUBE
17. height=h; inside Constructor:CUBEWEIGTH
18. width=w; inside default Constructor:CUBE
19. depth=d; inside Constructor:CUBEWEIGTH
20. weigth=m; cw1.volume()=1000.0
21. }} cw2.volume()=1000000.0
Super Keyword
Super Keyword
• Whenever a subclass needs to refer to its immediate superclass, it can do so by
use of the keyword super. Super has two general forms:
1. Calls the superclass constructor.
2. Used to access a members(i.e. instance variable or method) of the superclass.
Using super to Call Superclass Constructors
• Call to super must be first statement in constructor
Cube CubeInherit
# height: double cw1:CubeWeight
# width: double cw2:CubeWeight
# depth: double
Using “super” main(): void
Cube(double, double, double)
volume(): double

CubeWeight
# weigth: double

CubeWeight(double, double, double, double)


1. class Cube{ 22. class CubeInheritSuper{
2. protected double 23. public static void main(String[] args) {
height,width,depth; 24. CubeWeight cw1= new
OOP Java is the easiest, scoring and my favorite subject

3. Cube(double h,double w,double d){ CubeWeight(10,10,10,20.5);


4. System.out.println("Constructor: 25. CubeWeight cw2= new
5. CUBE"); CubeWeight(100,100,100,200.5);
26. System.out.println("cw1.volume()="+cw1.volume());
6. height=h;
27. System.out.println("cw1.weigth="+cw1.weigth);
7. width=w; 28. System.out.println("cw2.volume()="+cw2.volume());
8. depth=d; 29. System.out.println("cw2.weigth="+cw2.weigth);
9. } 30. }
10. double volume(){ 31. }
11.
12.
return height*width*depth;
}
CubeInheritSuper.java
Outpu
13. } t
14. class CubeWeight extends Cube{ Constructor:CUBE
15. double weigth; Constructor:CUBEWEIGTH
16. CubeWeight(double h,double w,double d, double m){ Constructor:CUBE
17. super(h,w,d); //call superclassConstructor Constructor:CUBEWEIGTH
18. System.out.println("Constructor:CUBEWEIGTH"); cw1.volume()=1000.0
19. weigth=m; cw1.weigth=20.5
20. } cw2.volume()=1000000.0
21. } Using super to Call Superclass Constructors cw2.weigth=200.5
Using super to access members
• The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.
• Syntax:
member can be either a
method or an instance
super.member variable.

• This second form of super is most applicable to situations in which member


names of a subclass hide members by the same name in the superclass.
Using super to access members: SuperMemberDemo.java
1. class A{ 15.class SuperMemberDemo{
2. int i; 16. public static void main(String[]
3. } args)
17. {
4. class B extends A{ 18. B b= new B(12,56);
5. int i,k; 19. b.show();
6. B(int a,int b){ 20. }
7. super.i=a; 21.}
8. this.i=b;
9. }
10. void show(){
11. System.out.println("super.i="+super.i);
Outpu
12. System.out.println("this.i="+this.i); t
13. } super.i=12
14.} this.i=56
Using super to access members: SuperMemberDemo.java
1. class A{ 19. class SuperMemberDemo{
2. int i=33; 20. public static void
3. void show(){ main(String[] args)
4. System.out.println("inside A:i="+i); 21. {
5. } 22. B b= new B(12,56);
6. } 23. b.show();
24. }
7. class B extends A{ 25. }
8. int i,k;
9. B(int a,int b){
10. super.show();
11. super.i=a;
12. this.i=b;
13. }
14. void show(){ Outpu
15. System.out.println("super.i="+super.i); t
16. System.out.println("this.i="+this.i); inside A:i=33
17. } super.i=12
18. } B.i=56
Points to remember for super
• When a subclass calls super( ), it is calling the constructor of its immediate
superclass.
• This is true even in a multileveled hierarchy.
• super( ) must always be the first statement executed inside a subclass
constructor.
• If a constructor does not explicitly call a superclass constructor, the Java
compiler automatically inserts a call to the no-argument constructor of the
superclass.
• The most common application of super keyword is to eliminate the ambiguity
between members of superclass and sub class.
Why Inheritance
1. Reusability of code
2. To implement polymorphism at run time (method overriding).
Class A
Base Class

Class B
Derived Class
Access Control
Access Control
Access Modifier Description
Private(-) The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default(~) The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
Protected(#) The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
Public(+) The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside
the package.
Access Control
Access Same Class Same Package Sub Class Universal
Modifier
Private

Default

Protected

Public
Exercise
1. Why multiple and Hybrid inheritance is not supported in java.
2. Implement inheritance in java using following diagram.
Shape
#String name
+ String color
Shape()

Circle Rectangle Triangle


~ radius: double ~height: double ~length: double
~PI: double ~width: double ~width: double
calCircleArea(): double calRectArea(): double calTriArea(): double
Interview Questions
1. Which class in Java is superclass of every other class?
2. Can a class extend itself?
3. Can we assign superclass to subclass?
4. Can a class extend more than one class?
Polymorphism
Polymorphism
Polymorphism: It is a Greek term means, “One name many Forms”

Polymorphism

Poly: Morphism:
Many Types

 Most important concept of object


oriented programming
 In OOP, Polymorphism is the ability of an
object to take on many forms.
Polymorphism
• Polymorphism is the method in an object-oriented programming language that
does different things depending on the class of the object which calls it.
• Polymorphism can be implemented using the concept of overloading and
overriding.
Polymorphism: Advantages
• Single variable can be used to store multiple
data types.
• Easy to debug the codes.
• It allows to perform a single act in different
ways.
• Polymorphism allows the object to decide
which form of the function to implement at
compile-time (overloading) as well as run-
time (overriding).
• Reduces coupling, increases reusability and
makes code easier to read.
Implementing Polymorphism

Polymorphism

Using
Using
Method
Method Overriding
Overloading
Implementing Polymorphism

• Overloading & Overrding


Implementing Polymorphism

Polymorphism

Using
Using
Method
Method Overriding
Overloading
Method Overloading
Method Overloading: Compile-time Polymorphism
• Definition: When two or more methods are implemented that share same name but
different parameter(s), the methods are said to be overloaded, and the process is
referred to as method overloading
• Method overloading is one of the ways that Java implements polymorphism.
• When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
• E.g. public void draw()
public void draw(int height, int width)
public void draw(int radius)
• Thus, overloaded methods must differ in the type and/or number of their parameters.
• While in overloaded methods with different return types and same name &
parameter are not allowed ,as the return type alone is insufficient for the compiler to
distinguish two versions of a method.
Method Overloading: Compile-time Polymorphism
19. class OverloadDemo{
1. class Addition{ 20.public static void
2. int i,j,k; main(String[] args){
3. void add(int a){ 21. Addition a1= new Addition();
4. i=a; 22. //call all versions of add()
5. System.out.println("add i="+i); 23. a1.add(20);
6. } 24. a1.add(30,50);
7. void add(int a,int b){\\overloaded add() 25. a1.add(10,30,60);
8. i=a; 26. }
9. j=b; 27.}
10. System.out.println("add i+j="+(i+j));
11. }
12. void add(int a,int b,int c){\\overloaded add()
13. i=a; Outpu
14. j=b; t
15. k=c; add i=20
16. System.out.println("add i+j+k="+(i+j+k)); add i+j=80
17. } add i+j+k=100
18.}
Method Overriding
Method Overriding: Run-time Polymorphism
• 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.
• Definition: If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
Method Overriding: OverrideDemo.java
1. class OverrideDemo{
1. class Shape{ 2. public static void
2. void draw(){ main(String[] args) {
3. System.out.println("Draw 3. Circle c= new Circle();
Shape"); 4. c.draw(); //child class meth()
4. } 5. Square sq= new Square();
5. } 6. sq.draw();//child class meth()
6. class Circle extends Shape{ 7. Shape sh= new Shape();
7. void draw(){ 8. sh.draw();//parentClass meth()
8. System.out.println("Draw 9. }
Circle"); 10. }
9. }
10.}
11.class Square extends Shape{ When an overridden method is called from
12. void draw(){ within a subclass, it will always refer to the
13. System.out.println("Draw version of that method defined by the
Square");
Outpu subclass. The version of the method
14. } t defined by the superclass will be hidden.
15.} Draw Circle
Draw Square
Draw Shape
Method Overriding: OverrideDemo.java
1. class Shape{ 1. class OverrideDemo{
2. void draw(){ 2. public static void
3. System.out.println("Draw main(String[] args) {
Shape"); 3. Circle c= new Circle();
4. } 4. c.draw();
5. } 5. Square sq= new Square();
6. class Circle extends Shape{
7. void draw(){ 6. sq.draw();
8. super.draw(); 7. }
9. System.out.println("Draw 8. }
Circle");
10. } Here, super.draw( ) calls the superclass version of
11.} draw( ).
Outpu
12.class Square extends Shape{ t
13. void draw(){ Draw Shape
14. System.out.println("Draw Draw Circle
Square"); Draw Square
15. }
16.}
Overridden methods in Java are similar to virtual functions in C++ and C#.
Why Overriding?
• Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
• Method overriding is used for runtime polymorphism.
• By combining inheritance with overridden methods, a superclass can define the
general form of the methods that will be used by all of its subclasses.
• Dynamic, run-time polymorphism is one of the most powerful mechanisms that
object-oriented design brings to bear on code reuse and robustness.
Method Overriding: Points to remember
• Method overriding occurs only when the names and the type signatures of the
two methods are identical. If they are not, then the two methods are simply
overloaded.
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Overloading vs Overriding
Overloading vs Overriding: Java Methods
Method Overloading Method Overriding
Overloading:Method with same name different signature Overriding:Method with same name same signature
Known as Compile-time Polymorphism Known as Run-time Polymorphism
It is performed within class. It occurs in two classes with IS-A (inheritance) relationship.
Inheritance and method hiding is not involved here. Here subclass method hides the super class method.
 Outline
Looping

 Introduction to Java
 Features of Java
 Components of Java
 JDK
 JRE
 JVM
 Installing JDK
 Setting Path Variable
 Hello World Program with Java
 Compiling Java Code
 Running Java Code
JAVA
 Java is a general-purpose computer-programming language that is open source,
platform independent, object-oriented and specifically designed to have as few
implementation dependencies as possible.
 Java was originally developed by James Gosling at Sun Microsystems and released
in 1995.
 Java was
Current initially namedJava
Version as Oak
SE 15 language and renamed to JAVA in 1995.
(as of feb-2021)
Version we will use Java SE 11 (LTS)
Setup size 149 MB (Linux), 152 MB (Windows x64)
Download Link https://www.oracle.com/in/java/technologies/javase-jdk11-downloads.html
Official Website https://java.com
Integrated Development 1. Eclipse (going to use this IDE in later chapters)
Environment 2. NetBeans
(IDE) 3. IntelliJ IDEA Community Edition
4. BlueJ

Dr. Ashish Kumar Sahu


Features of JAVA
Simple: Java inherits C/C++ syntax and many object-oriented features of C++.

Object Oriented: “Everything is an object” paradigm, which possess some


state, behavior and all the operations are performed using these objects.

Robust: Java has a strong memory management system. It helps in


eliminating error as it checks the code during compile and runtime.

Multithreaded: Java supports multiple threads of execution, including a set of


synchronization primitives. This makes programming with threads much easier.

Dr. Ashish Kumar Sahu


Features of JAVA (Cont.)
Architectural Neutral: Java is platform independent which means that any
application written on one platform can be easily ported to another platform.

Interpreted: Java is compiled to bytecodes, which are interpreted by a Java


run-time environment.

High Performance: Java achieves high performance through the use of


bytecode which can be easily translated into native machine code. With the use
of JIT (Just-In-Time) compilers, Java enables high performance.

Dr. Ashish Kumar Sahu


Features of JAVA (Cont.)

Distributed: Java provides a feature which helps to create distributed


applications. Using Remote Method Invocation (RMI), a program can invoke a
method of another program across a network and get the output. You can
access files by calling the methods from any machine on the internet.

Dynamic: Java has ability to adapt to an evolving environment which supports


dynamic memory allocation due to which memory wastage is reduced and
performance of the application is increased.

Dr. Ashish Kumar Sahu


Components of Java
 Java Virtual Machine (JVM)
JDK  Java Runtime Environment
(JRE)
 Java Development Kit (JDK)
Compiler Java
(javac.exe) Packages
Java (math, util, JVM
Application awt etc…)

Launcher
(java.exe), Runtime
AppletViewer, Libraries
etc..)
Development JRE
tools

Dr. Ashish Kumar Sahu


Java Development Kit (JDK)
 JDK contains tools needed ,
 To develop the Java programs and
 JRE to run the programs.
 The tools include
 compiler (javac.exe),
 Java application launcher (java.exe),
 Appletviewer, etc…
 Java application launcher (java.exe) opens a JRE, loads the class, and invokes its
main method.

Dr. Ashish Kumar Sahu


Java Runtime Environment (JRE)
 The JRE is required to run java applications.
 It combines the Java Virtual Machine (JVM), platform core classes and supporting
libraries.
 JRE is part of the Java Development Kit (JDK), but can be downloaded separately.
 It does not contain any development tools such as compiler, debugger, etc.

Dr. Ashish Kumar Sahu


Java Virtual Machine (JVM)
 JVM is a virtual machine that enables a computer to run Java programs as well as
programs written in other languages and compiled to Java Bytecode.
 Bytecode is a highly optimized set of instructions designed to be executed by the
Java Virtual Machine(JVM).
 Byte code is intermediate representation of java source code.
 Java compiler provides byte code by compiling Java Source Code.
 Extension for java class file or byte code is ‘.class’, which is platform independent.
 JVM is virtual because , It provides a machine interface that does not depend on the
operating system and machine hardware architecture.
 JVM interprets the byte code into the machine code.
 JVM itself is platform dependent, but Java is Not.

Dr. Ashish Kumar Sahu


How Java become Platform Independent?
Source code .java file
(Program)

Compile
r

Bytecode .class file

JVM
JVM JVM
(Windows
(Linux) (Mac)
)

Machine Machine Machine


Code Code Code

Dr. Ashish Kumar Sahu


Installing JDK
 Download JDK for Windows platform (.exe) from
 https://www.oracle.com/technetwork/java/javase/downloads/index.html
 Install the executable of JDK
 Set the path variable of System variables by performing following steps
 Go to "System Properties" (Right click This PC → Properties → Advanced System Settings)
 Click on the "Environment variables" button under the "Advanced" tab
 Then, select the "Path" variable in System variables and click on the "Edit" button
 Click on the "New" button and add the path where Java is installed, followed by \bin. By default,
Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when
you installed it). In that case, You will have to add a new path with: C:\Program
Files\Java\jdk-11.0.1\bin
 Then, click "OK", and save the settings
 At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on
your machine

Dr. Ashish Kumar Sahu


Setting Path Variable

2
3
4

Dr. Ashish Kumar Sahu


Hello World Java Program File must be saved as
HelloWorld.java
public class HelloWorld
Main method from where execution will start
{
public static void main(String[] args)
{ String must start with capital
letter
System.out.println("Hello World");
} System must start with capital
} letter

 We have to save this in HelloWorld.java file as it has public class named HelloWorld.
 String and System are inbuilt Java Classes.
 Classes in java are always written in Camel case.

Dr. Ashish Kumar Sahu


How to execute Java Program?
1. Save the program with the same name as the public class with .java extension.

Dr. Ashish Kumar Sahu


How to execute Java Program?
2. Open command prompt (cmd) / terminal & navigate to desired directory / folder.

3. Compile the “.java” file with javac command.

4. Execute the “.class” file with java command without extension.

Dr. Ashish Kumar Sahu


Identifiers
 They are used for class names, method names and variable names.
 An identifier may be any descriptive sequence of
 uppercase(A…Z) and lowercase(a..z) letters
 Numbers(0..9)
 Underscore(_) and dollar-sign($) characters
 Examples for valid Identifiers,
 AvgTemp
 count
 a4
 $test
 this_is_ok
 Examples for invalid Identifiers,
 2count (Identifiers can not start with digit)
 High-temp (Identifiers can not contain dash)
 Ok/NotOK (Identifiers can not contains slash)

Dr. Ashish Kumar Sahu


Data Types

Java Datatypes

Primitiv Non-
e primitive

Floating-point Characte Boolea


Integers Class
numbers rs n

Dr. Ashish Kumar Sahu


Primitive Data Types
Data Type Size Range Example
byte 1 Byte -128 to 127 byte a = 10;
short 2 Bytes -32,768 to 32,767 short a = 200;
int 4 Bytes -2,147,483,648 to int a = 50000;
2,147,483,647
long 8 Bytes -9,223,372,036,854,775,808 to long a = 20;
9,223,372,036,854,775,807
float 4 Bytes 1.4e-045 to 3.4e+038 float a = 10.2f;

double 8 Bytes 4.9e-324 to 1.8e+308 double a = 10.2;

char 2 Bytes 0 to 65536 (Stores ASCII of char a = ‘a’;


character)
boolean Not true or false boolean a = true;
defined

Dr. Ashish Kumar Sahu


Escape Sequences
 Escape sequences in general are used to signal an alternative interpretation of a
series of characters.
 For example, if you want to put quotes within quotes you must use the escape
sequence, \", on the interior quotes.
System.out.println("Good Morning \"World\"");

Escape Sequence Description


\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New Line
\t Tab

Dr. Ashish Kumar Sahu


Type Casting
 Assigning a value of one type to a variable of another type is known as Type Casting.
 In Java, type casting is classified into two types,
 Widening/Automatic Type Casting (Implicit)

 Narrowing Type Casting(Explicitly done)

Dr. Ashish Kumar Sahu


Automatic Type Casting
 When one type of data is assigned to other type of variable , an automatic type
conversion will take place if the following two conditions are satisfied:
 The two types are compatible
 The destination type is larger than the source type
 Such type of casting is called “widening conversion”.
 Example:
int can always hold values of byte and short
public static void main(String[] args) {
byte b = 5;
// √ this is correct
int a = b;
}

Dr. Ashish Kumar Sahu


Casting Incompatible Types
 To create a conversion between two incompatible types, you must use a cast
 A cast is an explicit type conversion.
 Such type is called “narrowing conversion”.
 Syntax:
(target-type) value
 Example:
public static void main(String[] args) {
int a = 5;
// × this is not correct
byte b = a;
// √ this is correct
byte b = (byte)a ;
}

Dr. Ashish Kumar Sahu


Operators
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Conditional / Ternary Operator
7. Instance of Operator

Dr. Ashish Kumar Sahu


Arithmetic Operator Note : A = 10 & B =
20

Operator Description Example

+ Addition A + B = 30

- Subtraction A - B = -10

* Multiplication A * B = 200

/ Division B/A=2

% Modulus B%A=0

++ Increment B++ = 21

-- Decrement B-- = 19

Dr. Ashish Kumar Sahu


Relational Operators Note : A = 10 & B =
20

Operator Description Example


== Equals (A == B) is not true.

!= Not Equals (A != B) is true.

> Greater than (A > B) is not true.

< Less than (A < B) is true.

>= Greater than equals (A >= B) is not true.

<= Less than equals (A <= B) is true.

Dr. Ashish Kumar Sahu


Bitwise Operators Note : A = 60 & B =
13
Operato
Description Example
r
& Binary AND Operator A & B = 12 which is 0000 1100

| Binary OR Operator A | B = 61 which is 0011 1101

^ Binary XOR Operator A ^ B = 49 which is 0011 0001


~A = -61 which is 1100 0011
~ Binary Ones Complement Operator in 2's complement form due to
a signed binary number.
A << 2 = 240 which is 1111
<< Binary Left Shift Operator
0000
>> Binary Right Shift Operator. A >> 2 = 15 which is 1111
A >>>2 = 15 which is 0000
>>> Shift right zero fill operator.
1111

Dr. Ashish Kumar Sahu


Logical Operators Note : A = true & B =
false

Operator Description Example

&& Logical AND operator (A && B) is false.

|| Called Logical OR Operator (A || B) is true.

! Called Logical NOT Operator !(A && B) is true.

Dr. Ashish Kumar Sahu


Assignment Operators
Operator Description Example
C = A + B will assign value of
= Simple assignment operator
A + B into C
C += A is equivalent to C = C
+= Add AND assignment operator
+A
C -= A is equivalent to C = C -
-= Subtract AND assignment operator
A
C *= A is equivalent to C = C *
*= Multiply AND assignment operator
A
C /= A is equivalent to C = C /
/= Divide AND assignment operator
A
C %= A is equivalent to C = C
%= Modulus AND assignment operator
%A
C <<= 2 is same as C = C <<
<<= Left shift AND assignment operator
2
C >>= 2 is same as C = C >>
>>= Right shift AND assignment operator
2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
Dr. Ashish Kumar Sahu
Conditional Operator (Ternary)
 Conditional Operator ( ? : )
 Syntax:
variable x = (expression) ? value if true : value if false
 Example:
b = (a == 1) ? 20 : 30;

Dr. Ashish Kumar Sahu


Operator Precedence & Associativity
 How does java evaluate 1 + 10 * 9 ?
 (1 + 10 ) * 9 = 99 OR 1 + (10 * 9) = 91
 To get the correct answer for the given problem Java came up with Operator
precedence. ( multiplication have higher precedence than addition so correct answer
will be 91 in this case)
 For Operator, associativity means that when the same operator appears in a row,
then to which direction the expression will be evaluated.
 How does java evaluate 1 * 2 + 3 * 4 / 5 ???
2 + 12 / 5
2 + 2.4
4.4

Dr. Ashish Kumar Sahu


Precedence of Java Operators
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Dr. Ashish Kumar Sahu


 Outline
Looping

 If statement
 Two way if statement
 Nested if statement
 Switch statement
 Conditional Expression
 While loop
 Do-while loop
 For loop
 Nested loop
 Break and continue statement
 Common mathematical expression
Control Statements
 Control Statements in Java is one of the fundamentals required for Java
Programming. It allows the smooth flow of a program.
 Statement can simply be defined as an instruction given to the computer to perform
specific operations.
 A control statement in java is a statement that determines whether the other
statements will be executed or not.
 Control statements in Java,
 If statement
 If-else statement
 If-else ladder statement
 Switch statement

Dr. Ashish Kumar Sahu


if statement
 if statement tests the condition. It executes the if block if condition is true.
public class IfStatementDemo{
public static void main(String[] ar)
{
int a = 10, b = 20;
if( a < b ) {
System.out.println("A is smaller than B");
}
}
}

Dr. Ashish Kumar Sahu


if-else statement
 if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
public class IfElseStatementDemo{
public static void main(String[] ar)
{
int a = 10, b = 20;
if(a<b) {
System.out.println("A is smaller than B");
}
else {
System.out.println(“A is not smaller than B");
}
}
}

Dr. Ashish Kumar Sahu


if-else statement
 if-else-if ladder statement executes one condition from multiple statements.
int marks = 65;

if (marks < 60) {


System.out.println("fail");
} else if (marks >= 60 && marks < 80) {
System.out.println("B grade");
} else if (marks >= 80 && marks < 90) {
System.out.println("A grade");
} else if (marks >= 90 && marks < 100) {
System.out.println("A+ grade");
} else {
System.out.println("Invalid!");
}

Dr. Ashish Kumar Sahu


Nested If statement
 We can also use if/else if statement inside another if/else if statement, this is known
as nested if statement.
int username = Integer.parseInt(args[0]);
int password = Integer.parseInt(args[1]);
double balance = 123456.25;

if(username==1234){
if(password==987654){
System.out.println("Your Balance is ="+balance);
}
else{
System.out.println("Password is invalid");
}
}
else{
System.out.println("Username is invalid");
}

Dr. Ashish Kumar Sahu


switch statement
 switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
public class SwitchExampleDemo {
public static void main(String[] args)
{
int number = 20;
switch (number) {
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
default:
System.out.println("Not 10 or 20");
}
}
}

Dr. Ashish Kumar Sahu


Programs to perform (Conditional Statements)
 Write a Java program to get a number from the user and print whether it is positive or
negative.
 Write a program to find maximum no from given 3 no.
 The marks obtained by a student in 5 different subjects are input through the
keyboard.
 The student gets a division as per the following rules:
 Percentage above or equals to 60-first division
 Percentage between 50 to 59-second division
 Percentage between 40 and 49-Third division
 Percentage less than 40-fail
Write a program to calculate the division obtained by the student.
 Write a Java program that takes a number from the user and displays the name of
the weekday accordingly (For example if user enter 1 program should return
Monday) .

Dr. Ashish Kumar Sahu


Looping Statement
 Looping in programming languages is a feature which facilitates the execution of a
set of instructions/functions repeatedly while some condition evaluates to true.
 Java provides three ways for executing the loops. While all the ways provide similar
basic functionality, they differ in their syntax and condition checking time.
 While loop
 Do-while loop
 For
 Foreach (will cover this after array)

Dr. Ashish Kumar Sahu


While Loop
 while loop is used to iterate a part of the program several times. while is entry
control loop.
 If//code
the number of iteration is not fixed, it is recommended to use while loop.
will print 1 to 9
public class WhileLoopDemo {
public static void main(String[] args) {
int number = 1;
while(number < 10) {
System.out.println(number);
number++;
}
}
}

Dr. Ashish Kumar Sahu


Do-while Loop
 do-while loop is executed at least once because condition is checked after loop body.
//code will print 1 to 9
public class DoWhileLoopDemo {
public static void main(String[] args) {
int number = 1;
do {
System.out.println(number);
number++;
}while(number < 10) ;
}
}

Dr. Ashish Kumar Sahu


For Loop
 for loop is used to iterate a part of the program several times.
 If the number of iteration is fixed, it is recommended to use for loop.
//code will print 1 to 9
public class ForLoopDemo {
public static void main(String[] args)
{
for(int number=1;number<10;number++)
{
System.out.println(number);
}
}
}

Dr. Ashish Kumar Sahu


Nested Loop

Dr. Ashish Kumar Sahu


Programs to perform (Looping Statements)
 Write a program to print first n odd numbers.
 Write a program to check that the given number is prime or not.
 Write a program to draw given patterns,

Dr. Ashish Kumar Sahu


Break statement
 When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
//code will print 1 to 4 followed by “After Loop”
public class BreakDemo{
public static void main(String[] args)
{
for(int number=1;number<10;number++)
{
if(number==5) {
break;
}
System.out.println(number);
}
System.out.println(“After Loop”);
}
}

Dr. Ashish Kumar Sahu


Continue statement
 The continue statement is used in loop control structure when you need to
immediately jump to the next iteration of the loop. It can be used with for loop or
while
//codeloop.
will print 1 to 9 but not 5, followed by “After Loop”
public class ContinueDemo {
public static void main(String[] args)
{
for(int number=1;number<10;number++)
{
if(number==5) {
continue;
}
System.out.println(number);
}
System.out.println(“After Loop”);
}
}

Dr. Ashish Kumar Sahu


Math class
 The Java Math class provides more advanced mathematical calculations other
than arithmetic operator.
 The java.lang.Math class contains methods which performs basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
 All the methods of class Math are static.
 Fields :
 Math class comes with two important static fields
 E : returns double value of Euler's number (i.e 2.718281828459045).
 PI : returns double value of PI (i.e. 3.141592653589793).

Dr. Ashish Kumar Sahu


Methods of class Math

Dr. Ashish Kumar Sahu


Methods of class Math (Cont.)

Dr. Ashish Kumar Sahu


Methods of class Math (Cont.)

Dr. Ashish Kumar Sahu


Methods of class Math (Cont.)

Dr. Ashish Kumar Sahu


Methods of class Math (Cont.)

Dr. Ashish Kumar Sahu


Math Example

public class MathDemo {


public static void main(String[] args) {
double sinValue = Math.sin(Math.PI / 2);
double cosValue = Math.cos(Math.toRadians(80));
int randomNumber = (int)(Math.random() * 100);
// values in Math class must be given in Radians
// (not in degree)
System.out.println("sin(90) = " + sinValue);
System.out.println("cos(80) = " + cosValue);
System.out.println("Random = " + randomNumber);
}
}

Dr. Ashish Kumar Sahu


 Outline
Looping

 Array
 Method
Array
 An array is a collection of similar type of elements that have contiguous memory
location and shares a common name.
 Syntax : data_type variable_name[] = new type[size_of_array];
Example : int a[] = new int[10];

35 13 28 106 35
a 42 5 83 97 14
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

 The data_type specifies the type of the elements that can be stored in an array, like int, float,
char etc...
 The size_of_array indicates the maximum number of elements that can be stores inside the
array.
 In the example, data type of an array is int and maximum elements that can be stored in an array
are 10.
 Important point about Java array.
 An array is derived datatype.
 An array is dynamically allocated.
Dr. Ashish Kumar Sahu
One-Dimensional Array
 An array using one subscript to represent the list of elements is called one
dimensional array.
 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 array of integers, we must allocate one using new
keyword.
Example: int student_marks[] = new int[20];

Dr. Ashish Kumar Sahu


Example (Array)
public class ArrayDemo{
public static void main(String[] args) {
int a[]; // or int[] a
// till now it is null as it does not assigned any memory

a = new int[5]; // here we actually create an array


a[0] = 5;
a[1] = 8;
a[2] = 15;
a[3] = 84;
a[4] = 53;

/* in java we use length property to determine the length


* of an array, unlike c where we used sizeof function */
for (int i = 0; i < a.length; i++) {
System.out.println("a["+i+"]="+a[i]);
}
}
}

Dr. Ashish Kumar Sahu


 Outline
Looping

 Class
 Object
Class
 Class is derived datatype, it combines members of different datatypes into one.
 Defines new datatype (primitive ones are not enough).
 For Example : Car, College, Bus etc..
 This new datatype can be used to create objects.
 A class is a template for an object .
Example :
class Car{
String company;
String model;
double price;
double milage;
………
}

Dr. Ashish Kumar Sahu


Car Class

Class: Car

Properties (Describe)
Company
Model Methods (Functions)
Color Start
Mfg. Year Drive
Price Park
Fuel Type On_break
Mileage On_lock
Gear Type On_turn
Power Steering
Anti-Lock braking system
Dr. Ashish Kumar Sahu
Object
 An object is an instance of a class.
 An object has a state and behavior.
Example: A dog has
states - color, name, breed as well as
behaviors – wagging the tail, barking, eating.
 The state of an object is stored in fields (variables), while methods (functions)
display the object's behavior.

Dr. Ashish Kumar Sahu


Objects of Class Bird

Dr. Ashish Kumar Sahu


Objects of a class Car

Honda City Hyundai Sumo


i20 Grand

Mercedes E Swift Dzire


class

Dr. Ashish Kumar Sahu


Rectangle Class
 Properties in rectangle Class
 length
 width
 borderColor
 backgroundColor

length = 3
length = 5 length = 5
width = 3
width = 2 width = 2
borderColor=red
borderColor=black borderColor=none
length = 2 backgroundColo
backgroundColor=white backgroundColor=yellow
width = 5 r=white
borderColor=bla
ck
backgroundColo
r=white

Dr. Ashish Kumar Sahu


Creating Object & Accessing members
 new keyword creates new object
 Syntax:
ClassName objName = new ClassName();
Example :
SmartPhone iPhone = new SmartPhone();
 Object variables and methods can be accessed using the dot (.) operator
 Example:
iPhone.storage = 8000;

Dr. Ashish Kumar Sahu


class Box {
double length;
length = 10
length
double breadth;
double height; myBox1
} breadth = 20
breadth
class BoxDemo {
public static void main(String args[]) { height = 30
height
Box myBox1 = new Box();
Box myBox2 = new Box();
double vol;
length
length =3
myBox1.length = 10;
myBox1.breadth = 20; myBox2 breadth
breadth
=6
myBox1.height = 30;
height
height
=9
myBox2.length = 3;
myBox2.breadth = 6;
myBox2.height = 9;

vol = myBox1.length * myBox1.breadth * myBox1.height;


System.out.println("Volume is " + vol);
vol = myBox2.length * myBox2.breadth * myBox2.height;
System.out.println("Volume is " + vol);
}
}
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 01 – Introduction to Java 69
Introducing methods
 Methods represents the behavior of a class.
 Remember : a Method is always invoked relative to an object. (except ….)
 Syntax:
access_specifier return_type method_name(argument_list)
{
// code
}

Dr. Ashish Kumar Sahu


Example (method)
public class SmartPhone {
String manufacturer;
String model;
double storage;
double screenSize;
public String getManufacturer(){
return manufacturer;
}
public void setManufacturer(String a){
manufacturer = a;
}
}
public class Demo {
public static void main(String args[]) {
SmartPhone sp = new SmartPhone();
sp.setManufacturer("Samsung");
String name = sp.getManufacturer();
System.out.println(name);
}
}

Dr. Ashish Kumar Sahu


Constructor
 A constructor is a “special” member method which initializes the objects of class.

Properties of constructor:
 Constructor is invoked automatically whenever an object of class is created.
 Constructor name must be same as class name.
 Constructors do not have return types and they cannot return values, not even void.
 All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
 Types of Constructor
1. Default Constructor
2. Parameterized Constructor

Dr. Ashish Kumar Sahu


Default Constructor
 Default constructor is the one which invokes by default when object of the class is
created.
 It is generally used to initialize the default value of the data members.
 It is also called no argument constructor.
class Rect{ public class RectDemo{
int len; public static void main(String[] args) {
int wid; Rect r1 = new Rect();
boolean isFilled; System.out.println(r1.len);
}
public Rect(){ }
len = 6;
wid = 6;
isFilled = false;
}
}

Dr. Ashish Kumar Sahu


Parameterized Constructor
 Constructors that can take arguments are called parameterized constructors.
 Sometimes it is necessary to initialize the various data elements of different objects
with different values when they are created.
 We can achieve this objective by passing arguments to the constructor when the
objects are created.
class Rect{ public class RectDemo{
int len; public static void main(String[] args) {
int wid; Rect r1 = new Rect(6,6,false);
boolean isFilled; System.out.println(r1.len);
}
public Rect(int l, int w, boolean isF){ }
len = l;
wid = w;
isFilled = isF;
}

Dr. Ashish Kumar Sahu


this keyword
 this is a reference variable that refers to the current object.
 this can be used to invoke current object's method.
 this() can be used to invoke current class constructor
 this can be passed as a parameter to constructor and method call.
 this can be used to return the current object from the method.

Dr. Ashish Kumar Sahu


class Box {
double length;
double breadth;
double height;
Box(double
Box(double length, l, double b, breadth,
double double h) {
double height) {
System.out.println("Constructing Box");
this.length
length
length l;= length;
== length; Creates
length ambiguity
is instance for as
variable
this.breadth
breadth b;= breadth;
breadth == breadth; well as compiler
length is formal
this.height
height =
height = h; = height;
height; parameter of method
}
void volume() {
double volume = length * breadth * height;
System.out.println("Volume is " + volume);
}
}
class BoxDemo {
public static void main(String args[]) {
Box myBox1 = new Box(10,20,30);
Box myBox2 = new Box(3,6,9);
myBox1.volume();
myBox2.volume();
}
} Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 01 – Introduction to Java 76
Understanding the Scope of Variable

Dr. Ashish Kumar Sahu


Method Overloading
public class OverloadingMethods {
 Overloading allows public static void main(String[] ar) {
different methods to have int ans1 = sum(5,2); // will return 7
same name, but different int ans2 = sum(5,2,6); // will return 13
signatures. double ans3 = sum(5.8,6.4); // will return 12.2
// print ans1,ans2,ans3 in order to see the result
 Signature can differ by }
number of input // Overloaded sum(). This sum takes two int parameters
parameters or type of public static int sum(int x, int y) {
return (x + y);
input parameters or both. }
 Overloading is related to // Overloaded sum(). This sum takes three int parameters
public static int sum(int x, int y, int z) {
compile time (or static)
return (x + y + z);
polymorphism. }
// Overloaded sum(). This sum takes two double
parameters
public static double sum(double x, double y) {
return (x + y);
}
}
static keyword
 static keyword is mainly used for memory management.
 It can be used with
 Variables
 Methods
 Blocks
 Nested classes
 Basically, static is used for a constant variable or a method that is same for every
instance of a class.
 The static variable can be used to refer to the common property of all objects.
 The static variable gets memory only once in the class area at the time of class
loading.
 It makes your program memory efficient.
 Syntax
static type variablename;
Dr. Ashish Kumar Sahu
class Student {
int rollNo;
String name;
static String
String collegecollege = "DIET";
= "DIET";
.
.
.
}
class StudentDemo {
public static void main(String args[]) {
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
.
. student1 student2 student3
.
rollNo
}
}
name

college DIET DIET DIET

college DIET
Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 01 – Introduction to Java 80
static method
 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.
 Restrictions
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.

Dr. Ashish Kumar Sahu


class Student {
int rollno;
String name;
static String college="abc";
static void change() {
college = "DIET"; We can not use non-static
rollno = 10; variables in static methods
}
Student(int r, String n) {
rollno = r;
name = n;
}
void display() {
System.out.println(rollno+" "+name+" "+college);
}
}
class TestStaticMethod {
public static void main(String args[]) {
Student.change();
Student s1 = new Student(111,"Tom");
Student s2 = new Student(222,"Jerry");
s1.display();
s2.display();
}
} Prof. Arjun V. Bala #3140705 (OOP-I)  Unit 01 – Introduction to Java 82
static block
 static block is executed exactly once, when the class is first loaded.
 It is used to initialize static variables of the class.
 It will be executed even before the main method.
 Syntax:
static {
//initialisation of static variables…
}

Dr. Ashish Kumar Sahu


Mutable and Immutable
 The content of mutable object can be changed, while content of immutable objects
can not be changed.
class MutableClass{ class ImmutableClass{
int a; int a;
void add5() { int add5() {
a = a + 5; return ( a + 5 );
} }
} }
public class MutableClassDemo { public class MutableClassDemo {
public static void main(String[] args) { public static void main(String[] args) {
MutableClass m1 = new MutableClass(); ImmutableClass m1 = new ImmutableClass();
m1.a = 10; m1.a = 10;
m1.add5(); int ans = m1.add5();
System.out.println(m1.a); System.out.println("A in m1 = " + m1.a);
} System.out.println("returned = " + ans);
} }
}

Dr. Ashish Kumar Sahu


Passing Objects as Argument
class Time{
 In order to int hour;
understand how int minute;
and why we need int second;
public Time(int hour, int minute, int second) {
to pass object as this.second = second;
an argument in this.minute = minute;
methods, lets this.hour = hour;
}
see the below void add(Time t) { public class TimeDemo {
example. this.second += t.second; public static void main(String[] args) {
if(this.second>=60) { Time t1 = new Time(11,59,55);
this.minute++; Time t2 = new Time(0,0,5);
this.second-=60;
} t1.add(t2);
this.minute += t.minute;
if(this.minute>=60) { System.out.println(t1.hour + ":" +
this.hour++; t1.minute + ":" + t1.second);
this.minute-=60; }
} }
this.hour += t.hour;
}
}
Dr. Ashish Kumar Sahu
Array of Objects
 We can create an array of object in java.
 Similar to primitive data type array we can also create and use arrays of derived
data types (class).
class Student{ public class ArrayOfObjectDemo {
int rollNo; public static void main(String[] args) {
String name; Student[] stu = new Student[3];

public Student(int rollNo, String name) { stu[0] = new Student(101,"darshan");


this.rollNo = rollNo; stu[1] = new Student(102,"arjun");
this.name = name; stu[2] = new Student(103,"java");
}
stu[0].printStudentDetail();
void printStudentDetail() { stu[1].printStudentDetail();
System.out.println("| "+ stu[2].printStudentDetail();
rollNo }
+" | -- | "+ }
name +" |");
}
}
Dr. Ashish Kumar Sahu
Package (Not part of this Unit)
 A Package can be defined as a grouping of related types providing access
protection and name space management.
 Programmers can define their own packages to bundle group of classes/interfaces,
etc.
 Packages are used in Java in order to
1. prevent naming conflicts
2. control access,
3. make searching/locating of classes/interfaces easier.
 It is a good practice to group related classes implemented so that a programmer can
easily determine that the classes, interfaces are related.

Dr. Ashish Kumar Sahu


Creating a package
 To create a package you need to write package statement followed by the name of
the package.
 Syntax : package package_name;
 Example : package darshan_student;
class Student {
// code
}

 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 will be put into an
unnamed package.

Dr. Ashish Kumar Sahu


Package (Example)
package myPackage;
public class Animal {
public String name;
public void eat(){
System.out.println("Organic Food !!!!");
}
public static void main(String[] args){
Animal a = new Animal();
a.eat();
}
}
.
Represent the current
 To compile directory
javac –d . Animal.java
 To Run the class file
java myPackage.Animal

Dr. Ashish Kumar Sahu


Programs
 Write a class named Rectangle to represent a rectangle. It contains following
members:
Data: width (double) and height (double) that specify the width and height of the
rectangle.
Methods:
1. A no-arg constructor that creates a default rectangle.
2. A constructor that creates a rectangle with the specified width and height.
3. A method named getArea() that returns the area of this rectangle.
4. A method named getPerimeter() that returns the perimeter.
 Write a program to create circle class with area function to find area of circle.
 Define time class with hour and minute. Also define addition method to add two time
objects.
 Declare a class called student having following data members:id_no,
no_of_subjects_registered, subject_code, subject_credits,
grade_obtained and spi. Define constructor and calculate_spi methods.
Define main to instantiate an array for objects of class student to process data of n
students.
Dr. Ashish Kumar Sahu

You might also like