OOPJ - Unit 6 7 8 9 Theory
OOPJ - Unit 6 7 8 9 Theory
If you make any variable as If you make any method as If you make any class as
final, you cannot change the final, you cannot override final, you cannot extend it.
value of final variable(It will it. -> Use to stop Inheritance.
be constant). -> Use To Stop Overriding
- > Use to stop value Example:
change Example: final class A
class A {
Example: { }
class A final void m1() class B extends A // Error
{ {} {
final int i =10; } }
void change() class B extends A
{ { //try to override it
i=15//Error void m1() // Error
} {}
}
}
finally block is a block that is used to execute important code such as closing connection, stream,
resources like port, files etc.
All sub classes of java.lang.Exception Class All sub classes of RunTimeException and sub
except sub classes of RunTimeException are classes of java.lang.Error are unchecked
checked exceptions. exceptions.
Exception Handling: Exception = abnormal condition of program And Handling = Handle it.
- It is mechanism of java to handle abnormal condition of program.
- It is use to handle Run time exception.
- try, catch, finally, throw and throws are use to handle exception in java.
} catch (NumberFormatException e) {
System.out.println("Not a No Error: " + e);
} catch (NegativeValueException e) {
System.out.println("Value Error: " + e);
}
}
}
Output:
1)Run: java CustomExceptionNegativeValueDemo
Command line Array Error java.lang.ArrayIndexOutOfBoundsException: 0
2)Run: java CustomExceptionNegativeValueDemo -2
Value Error: NegativeValueException{value=-2}is negative.
3)Run: java CustomExceptionNegativeValueDemo a
Not No Error:java.lang.NumberFormatException: For input string: "a"
4) )Run: java CustomExceptionNegativeValueDemo 2
You have entered positive value... :) 2
3 Explain the following terms with respect to exception handling.
i) try ii) catch iii) finally iv) throw v)throws OR
Explain the importance of exception handling in java. Which key words are used to handle
exceptions? Write a program to explain the use of these keywords.
Exception Handling: Exception = abnormal condition of program And Handling = Handle it.
- It is mechanism of java to handle abnormal condition of program.
- It is use to handle Run time exception.
- try, catch, finally, throw and throws are use to handle exception in java
1)try block:
Java try block is used to enclose the code that might throw an exception.
try{
//code that may throw exception
2)catch block:
Java catch block is used to handle the Exception. It must be used after the try block only.
Example of try/catch
3) finally block is a block that is used to execute important code such as closing connection, stream,
resources like port, files etc.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword
is mainly used to throw custom exception. We will see custom exceptions later.
The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up
before the code being used.
Syntax :
return_type method_name() throws exception_class_name{
//method code
}
Note: You can write this program in any exception handling question
(Single program contain all 5 exception handling keywords)
Example:
public class EHDemo {
public static void main(String[] args) throws Exception {
try {
int a = -10;
if (a < 0) {
Exception e = new Exception (“a is negative”);
throw e;
}
System.out.println("You have entered positive value... :)" + a);
} catch (Exception e) {
System.out.println("Error " + e);
} finally{
System.out.println("I am finally – always run”);
}
}
}
1 Draw and explain life cycle of thread. Also list and explain various methods of thread class.
Multithreading: is a process of executing multiple threads simultaneously to get fast output and best CPU
utilization.
Thread states :
1)New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
2 Write an application that executes two threads. One thread displays "Good Morning" every 1000
milliseconds & another thread displays "Good Afternoon" every 3000 milliseconds. Create the
threads by implementing the Runnable interface. (OR Any Thread Program)
Thread t;
String msg;
long st;
MAThread(String msg,long st) {
t = new Thread(this);
this.msg = msg;
this.st = st;
t.start();
}
For example, if you have two threads running in your program e.g.Producer and Consumer then
producer thread can communicate to the consumer that it can start consuming now because there are
items to consume in the queue. Similarly, a consumer thread can tell the producer that it can also start
putting items now because there is some space in the queue, which is created as a result of consumption.
A thread can use wait() method to pause and do nothing depending upon some condition. For example,
in the producer-consumer problem, producer thread should wait if the queue is full and consumer thread
should wait if the queue is empty.
If some thread is waiting for some condition to become true, you can use notify and notifyAll
methods to inform them that condition is now changed and they can wake up.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first
Unit-8 IO Programming
1 Write a program using to copy Content of one file File1.txt into another file File2.txt.
import java.io.*;
public class FileReadWriteDemo
{
public static void main(String[] a)
{
String fn="File1.txt";
String fun="File2.txt";
try
{
FileInputStream fin= new FileInputStream(fn);
FileOutputStream fo= new FileOutputStream(fun);
int d;
while((d=fin.read())!=-1)
{
fo.write(d);
}
fin.close();
fo.close();
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found.");
i }
catch(IOException e)
{
System.out.println("IO error.");
}
Sem-5-OOPJ– Hemali Shah – LJIET Page 8
Sem-5 – OOPJ –Unit-6,7,8,9 Theory - 2016
}
}
2 Differentiate the followings:
Text I/O and Binary I/O.
Text I/O Binary I/O
It is also called Character I/O It is also called Byte I/O
Read and write process use char as a data unit Read and write process use byte as a data unit
It is conventional approach of I/O processing It is traditional approach of I/O processing
Have to convert byte to char to process with All internal devices and socket programming
devices(Console Input, Socket programing) work with binary I/O
Reader and Writer is a super class of Text I/O InputStream and OutputStream is super class of
Binary I/O
3 Write a program to count the total no. of chars, words, lines, alphabets, digits, white spaces in a
given file.
import java.io.*;
import java.io.*;
class FileWordReplace {
1 What is collection in Java? Differentiate between Vector and ArrayList. Describe the Java
Collections Framework .
Collections in Java:
Collections in java is a framework that provides an architecture to store and manipulate the group
of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet, Properties etc).
The java.util package contains all the classes and interfaces for Collection framework.
Sem-5-OOPJ– Hemali Shah – LJIET Page 10
Sem-5 – OOPJ –Unit-6,7,8,9 Theory - 2016
Advantage Of Collection Framework:
Name If
Use
Interface
This enables you to work with groups of objects; it is at the top of the collections
Collection
hierarchy.
This extends Collection and an instance of List stores an ordered collection of
List
elements.
This extends Collection to handle sets, which must contain unique elements. Not
Set
allow duplicate elements
SortedSet The This extends Set to handle sorted sets
AbstractCollection -Implements most of the Collection interface. Basic methods are implemented in
this abstract class.
AbstractList - Extends AbstractCollection and implements most of the List interface.
AbstractSequentialList - Extends AbstractList for use by a collection that uses sequential rather than
random access of its elements.
LinkedList -Implements a linked list by extending AbstractSequentialList.
ArrayList -Implements a dynamic array by extending AbstractList.
AbstractSet - Extends AbstractCollection and implements most of the Set interface.
HashSet - Extends AbstractSet for use with a hash table. Use hash function for storing and retrieving
data.
LinkedHashSet - Extends HashSet to allow insertion-order iterations.
TreeSet -Implements a set stored in a tree. Extends AbstractSet.
AbstractMap -Implements most of the Map interface.
HashMap -Extends AbstractMap to use a hash table.
TreeMap -Extends AbstractMap to use a tree. Store value based on key.
WeakHashMap -Extends AbstractMap to use a hash table with weak keys.
LinkedHashMap -Extends HashMap to allow insertion-order iterations.
Java Networking: java.net.* package is use for the java network programing.
network programming refers to writing programs that execute across multiple devices (computers), in
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the
low-level communication details, allowing you to write programs that focus on solving the problem at
hand.
Java socket programming provides facility to share data between different computing devices.
class DisplayIPOfServerDemo
{
public static void main(String args[]) {
try {
InetAddress local = InetAddress.getLocalHost();
System.out.println("Local IP : " + local);
Output:
Local IP : Laptop/192.168.109.20
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism
for the server program to listen for clients and establish connections with them.
The java.net.Socket class represents the socket that both the client and server use to communicate with
each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket
object from the return value of the accept() method.
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
characteristics of OO approach:
Objects – The instances of a class which are used in real functionality – its variables and operations
Abstraction – Specifying what to do but not how to do ; a flexible feature for having a overall view of an
object’s functionality.
Encapsulation – Binding data and operations of data together in a single unit – A class adhere this feature
Polymorphism – Multiple definitions for a single name - functions with same name with different
functionality; saves time in investing many function names Operator and Function overloading
1 Draw class diagram for online restaurant system.(RMS – restaurant management system)
2 ) Abstract class was defined as class that can't be directly instantiated. No object may be a direct
instance of an abstract class.
abstract class but provides no definition. We may assume that abstract class does not have complete
declaration and "typically" can not be instantiated.
3) Constraint: could have an optional name, though usually it is anonymous. A constraint is shown as a
text string in curly braces according to the syntax:
For an element whose notation is a text string (such as a class attribute, etc.), the constraint string may
follow the element text string in curly braces.
Bank account attribute constraints - non empty owner and positive balance.
5) Package:
Package is the only one grouping thing available for gathering structural and behavioral things.
6) Reification: It is promotion of something that is not an object into and object and can be use for meta
application.
* 1...*
Substance SabstanceName
2 Explain Nested States. Draw the Nested states diagram for the phone line.
Nested State: Nest states to show their commonality & share behavior. Refines values & link that object
can have.
In phoneline diagram,all state except idle are nested state as active.
2 Prepare a sequence diagram for issuing book in the library management system.