Professional Documents
Culture Documents
Ilovepdf Merged
Ilovepdf Merged
CSE2006-PROGRAMMING-IN-JAVA
JDBC Example
Download MySQL
https://dev.mysql.com/downloads/installer/
Installation
Double Click to
install
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Installation … Cntd.
Do NOT edit
anything else….
Edit Only PATH
Variable…
!! BE CAREFUL !!!
Do NOT edit
anything else….
Edit Only PATH
Variable…
!! BE CAREFUL !!!
create table student (schno INT unsigned NOT NULL AUTO_INCREMENT, name
VARCHAR(150) NOT NULL, course VARCHAR(50) NOT NULL, PRIMARY KEY (schno) );
If you are using cmd prompt for connectivity then you can set classpath:
$ set classpath=z:\Java\mysql-connector-java-8.0.30.jar;.;
CSE2006-PROGRAMMING-IN-JAVA
5 - JDBC
Introduction
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)
INSERT Statement
UPDATE Statement
DELETE Statement
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
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
6
• Example:
– // create integerArray
Integer[] integerArray = new Integer[5];
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
7
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.
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.
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
11
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
12
– 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
• 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
String
Array List
Example
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
16
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
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
19
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
20
Ref: Deitel and Deitel, “Java How to Program. CSE2006: Collections : Adarsh Patel, SCSE, VIT-Bhopal (only for internal use)
22
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
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
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 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
Introduction
/* 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
• 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
– 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
Born
/new
start
Ready
thread dispatch
quantum expiration (assign a
yield
timeout expires
processor)
I/O completes
interrupt
notifyAll
interrupt
acquire lock
notify
Running
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
Starting threads
Threads started, main ends
Thread Synchronization
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
Producer writes 1 1 1
Consumer reads 1 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 reads 4 4 0
Producer done producing.
Terminating Producer.
Initial State -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 3 3 0
Producer writes 4 4 1
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
Daemon Threads
Runnable Interface
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
Throwable
Exception Error
• 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
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
• 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()
These classes
are called
Derived class
Inheritance
class Vehicle
Attributes:
Engine_no, color
Methods:
apply_breaks()
• 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 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. }
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;
A A A
B C B
B
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;
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
26. superObjA.i=10;
27. superObjA.j=20;
28. superObjA.showij();
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
27. superObjA.j=20; A
28. superObjA.showij();
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
CubeWeight
# weigth: double
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()
Polymorphism
Poly: Morphism:
Many Types
Polymorphism
Using
Using
Method
Method Overriding
Overloading
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
Launcher
(java.exe), Runtime
AppletViewer, Libraries
etc..)
Development JRE
tools
Compile
r
JVM
JVM JVM
(Windows
(Linux) (Mac)
)
2
3
4
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.
Java Datatypes
Primitiv Non-
e primitive
+ 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
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
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");
}
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];
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;
………
}
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.
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
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
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.
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.