Download Unit3(1)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
UNIT-III
TUTORIAL
1. What is exception? Give its types.
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a runtime error.
Types:
2. What is exception handling? Give its general form.
Java uses its exception handling mechanism to differentiate the endof-file condition
from file errors when input is being performed. Exception handling provides a powerful
mechanism for controlling complex programs that have many dynamic run-time characteristics.
General form :
try{
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is caught
*/
}
3. How a divide by zero exception monitored using try and catch blocks?
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present, the following statement
will generate
int b = 42 / a;
a divide-by-zero exception. */
System.out.println("a = " + a);
try {
// nested try block
/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a);
// division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
4. What is the need of multiple catch statements? give example.
In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, you can specify two or more catch clauses, each catching a
different type of exception.
Eg: class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
5. Define throw.
In java, it is possible for your program to throw an exception explicitly, using
the throw statement. The general form of throw is shown here:
Syntax:
throw ThrowableInstance;
ThrowableInstance- object of type Throwable
6. Define throws. Give its general form.
If a method is capable of causing an exception that it does not handle, it must specify
this behavior by including a throws clause in the method's declaration. A throws clause lists
the types of exceptions that a method might throw. This is necessary for all exceptions,
except those of type Error or RuntimeException, or any of their subclasses.
General form:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw
7. What is the need of finally method in exception handling?
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method. For example, if a method opens a file upon
entry and closes it upon exit, then you will not want the code that closes the file to be
bypassed by the exception-handling mechanism. The finally keyword is designed to
address this contingency.
8. What is checked and unchecked exceptions?
In the language of Java, some exceptions are called unchecked exceptions because the
compiler does not check to see if a method handles or throws these exceptions.
Eg: ArithmeticException , SecurityException,etc.
Exceptions that must be included in a method's throws list if that method can generate
one of these exceptions and does not handle it itself. These are called checked exceptions.
Eg: ClassNotFoundException, InstantiationException,etc
9. Write a sample program for chained exception.
try {
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}
In this example, when an IOException is caught, a new SampleException exception is
created with the original cause attached and the chain of exceptions is thrown up to the
next higher level exception handler.
10. Write a few built in exceptions in java.
Exception
ArithmeticException
ClassCastException
NullPointerException
NumberFormatException
format.
SecurityException
ClassNotFoundException
InterruptedException
thread.
NoSuchFieldException
Meaning
Arithmetic error, such as divide-by-zero.
Invalid cast.
Invalid use of a null reference.
Invalid conversion of a string to a numeric
Attempt to violate security.
Class not found.
One thread has been interrupted by another
A requested field does not exist.
11. Write a sample program for arithmetic exception.
Refer ques no.: 3
12. Define thread.
Java provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution.
13. List out the states of thread.
Different states of a thread are :
1. New state – After the creations of Thread instance the thread is in this state but
before the start() method invocation. At this point, the thread is considered not
alive.
2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A
thread first enters runnable state after the invoking of start() method but a thread
can return to this state after either running, waiting, sleeping or coming back from
blocked state also. On this state a thread is waiting for a turn on the processor.
3. Running state – A thread is in running state that means the thread is currently
executing. There are several ways to enter in Runnable state but there is only one
way to enter in Running state: the scheduler select a thread from runnable pool.
4. Dead state – A thread can be considered dead when its run() method completes.
If any thread comes on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that are
hold by another thread.
16. Write the two ways to create a thread.
In the most general sense, we create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
• we can implement the Runnable interface.
• we can extend the Thread class, itself.
17. What is the use of isAlive() and join() method in thread?
Two ways exist to determine whether a thread has finished.
(i) isAlive():
General form: final boolean isAlive( ) returns true if the thread upon which it is called is
still running. It returns false otherwise.
(ii) join():
General form: final void join( ) throws InterruptedException. This method waits until the
thread on which it is called terminates.
18. What is thread priority? Give the use of setpriority and getpriority methods.
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run.
 To set a thread's priority, use the setPriority( ) method, which is a member of Thread.
General form: final void setPriority(int level) where level specifies the new priority setting
for the calling thread.
 we can obtain the current priority setting by calling the getPriority( ) method of Thread.
General form: final int getPriority( )
19. What is synchronization?
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization.
20. What is synchronized statement? Give its general form.
Synchronized statement is an easy and effective means of achieving synchronization.
A synchronized block ensures that a call to a method that is a member of object occurs only after
the current thread has successfully entered object's monitor.
General form:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized.
21. How interthread communication takes place in thread?
Java provides a very efficient way through which multiple-threads can
communicate with each-other. This way reduces the CPU’s idle time i.e. A process
where, a thread is paused running in its critical region and another thread is allowed to
enter (or lock) in the same critical section to be executed. This technique is known as
Interthread communication which is implemented by some methods. These methods
are defined in "java.lang" package and can only be called within synchronized code
shown as:
Method
wait( )
Description
It indicates the calling thread to give up the monitor and
go to sleep until some other thread enters the same monitor
and calls method notify() or notifyAll().
It wakes up the first thread that called wait() on the same
object.
notifyAll( Wakes up (Unloack) all the threads that called wait( ) on
)
the same object. The highest priority thread will run first.
notify( )
22. Define deadlock.
A special type of error that we need to avoid that relates specifically to multitasking is
deadlock, which occurs when two threads have a circular dependency on a pair of
synchronized objects. Deadlock is a difficult error to debug for two reasons:
• In general, it occurs only rarely, when the two threads time-slice in just the right way.
• It may involve more than two threads and two synchronized objects.
23. Define stream.
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information. A stream is linked to a physical device by the Java
I/O system. All streams behave in the same manner, even if the actual physical devices
to which they are linked differ.
Types:
1. Byte streams
2. character streams
24. What are the abstract classes in byte stream class?
Byte streams are defined by using two class hierarchies. At the top are two abstract
classes: InputStream and OutputStream. Each of these abstract classes has several
concrete subclasses, that handle the differences between various devices, such as disk
files, network connections, and even memory buffers
25. What are the abstract classes in character stream class?
Character streams are defined by using two class hierarchies. At the top are two
abstract classes, Reader and Writer. These abstract classes handle Unicode character streams.
Java has several concrete subclasses of each of these.
26. What is the advantage of using system class?
27. How you read a console input? Give examples.
In Java, console input is accomplished by reading from System.in. To obtain a
character-based stream that is attached to the console, we wrap System.in in a
BufferedReader object, to create a character stream. BuffereredReader supports a
buffered input stream. Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader) Where inputReader is the stream that is linked to the
instance of BufferedReader that is being created and Reader is an abstract class.
28. What is the use of print stream class?
System.out and System.err are objects of type PrintStream where System.out refers
to the standard output stream. By default, this is the console.System.err refers
to the standard error stream, which also is the console by default.
29. What is file? List out the constructors used for creating the file.
A File object is used to obtain or manipulate the information associated with a disk
file, such as the permissions, time, date, and directory path, and to navigate subdirectory
hierarchies.Files are a primary source and destination for data within many programs. The
following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
Here, directoryPath is the path name of the file, filename is the name of the file, and
dirObj is a File object that specifies a directory.
30. How to find whether a given object is a file or directory?
31. Give a sample program for list() method.
import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
33.what is serialization?
Serialization is the process of writing the state of an object to a byte stream. This is
useful when you want to save the state of your program to a persistent storage area, such as a
file. At a later time, you may restore these objects by using the process of deserialization.
Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a
Java object on one machine to invoke a method of a Java object on a different machine.
34. What is the use of serializable and externalizable interfaces?
The Serializable interface defines no members. It is simply
used to indicate that a class may be serialized. If a class is serializable, all of its
subclasses are also serializable
The Externalizable interface have been designed so that much
of the work to save and restore the state of an object occurs automatically.
The Externalizable interface defines these two methods:
void readExternal(ObjectInput inStream)
throws IOException, ClassNotFoundException
void writeExternal(ObjectOutput outStream)
throws IOException
In these methods, inStream is the byte stream from which the object is to be read, and
outStream is the byte stream to which the object is to be written.