Java Unit 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

A.

M JAIN COLLEGE (SHIFT-II)


DEPARTMENT OF SOFTWARE APPLICATIONS
PREVIOUS YEAR QUESTION AND ANSWER
PROGRAMMING IN JAVA (UNIT-IV)

2Marks

1)List the two categories of errors?(apr-14)


Errors are classified into two categories, they are
1.Compile-time errors-missing semicolons,brackets.
2.Run-time errors-dividing an integer by zero.

2)What is Stream?(nov-13,apr-14,nov-15,apr-15)
A stream is a path of communication between the source and destination. It represent the
ordered sequence of data. A stream is linked to physical device by the java I/O stream. The data
flows There are two types of stream,
1.Input stream-reads.
2.output stream-writes.

3)What is an exception?(apr-12,nov-14,apr-15)
An exception is an abnormal condition, which occurs during the execution of a program
Exceptions are error events like division by zero, opening of a file that does not exist.

4) What is use of throw statement? (nov-13)


Whenever a program does not want to handle exception using the try block, it can use the
throws clause. The throws clause is responsible to handle the different types of exceptions
generated by the program. This clause usually contains a list of the various types of exception
that are likely to occur in the
program.

5)What is ByteStream?(nov-14)
Byte stream classes that provide support for creating and manipulating streams and files
for reading(input stream) and writing(output stream) bytes. It is a unidirectional(ie)that can
transmit bytes in only one direction.

6)Define applet?(apr-12)
An applet is a dynamic and interactive program that runs inside a web page displayed by
a Java capable browser. This can also be executed using the appletviewer.

7)What is remote applet?(apr-16)


The remote applets are applet types that are developed and stored in remote
computer.The web page requires internet connection to locate and load the remote applet from
remote computer.
8)What is object serialization?(apr-16)
object serialization is a process where an object can be represented as a sequence of bytes
that includes the object's data as well as information about the object's type and the types of data
stored in the object.

9)Write the syntax of PARAM tag?(apr-13)


The param tag are user-defined tags used in applet. The tag has name attribute and value
attribute . synatx:<PARAM name=text VALUE="text">.

10)What is a file?(apr-13)
File class that provides support for creating files and directories. It's a collection of
record. some of the operations of files are creating, opening, closing, deleting.

11)What is local applet?(nov-15)


Local applets are applet types that are developed and stored in local system. It does not
require internet connection for it's execution. It simply searches the directories in the local
system and locates and loads the specified applet for execution.

12)List any two drawing methods of graphics class?(apr-15)


1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
5marks:

1)Write a note on Byte Stream Classes?(apr-12,apr-15)


Byte stream classes that provide support for creating and manipulating streams and files
for reading and writing bytes. It is a unidirectional(ie)that can transmit bytes in only one
direction.

Input Stream class:


Input Stream class is an abstract class. It is the super class of all classes representing an
input stream of bytes. classes that are used to read 8-bit bytes. We cannot create instance of this
class. The Input Stream class defines methods for performing input functions such as;
1) reading bytes
2) closing streams
3) Marking positions in streams
4) skipping ahead in a stream
5)Finding the number of bytes in a stream.

Data Input

Hierarchy of inputstreamclasses

Commonly used methods:


1) read()-reads a byte from the input stream.
2)read(byte b[ ])-reads an array of bytes into b.
3) reset()-goes back to the beginning of the stream.
4)close()-closes the input stream.
5)skip(n)-skips over n bytes from the input stream.

OutputStream classes:
OutputStream class is an abstract class.It is the super class of all classes representing an
output stream of bytes. we cannot instantiate it.The methods that are designed to perform tasks
are;
1)writing bytes.
2)closing streams.
3)flushing streams.

Data Output

Hierarchy of output stream classes

Commonly used methods are:


1) write()-writes a byte to the output stream.
2) write(byte b[ ])-write all bytes in the array b to output stream.
3)close()-closes the output stream.
4)flush()-flushes the output stream.

2)Write a note on I/O Stream Classes?(nov-13)


Java uses the concept of stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
1.Byte stream classes -that provide support for handling I/O operations on bytes
2.character stream classes- that provide support for managing I/O operations on characters.
java stream class

Byte stream classes Character stream classes

Inputstreamclasses outputstreamclasses Readerclasses Writerclasses

Byte stream classes:


Byte stream classes that provide support for creating and manipulating streams and files
for reading and writing bytes. It is a unidirectional(ie)that can transmit bytes in only one
direction.

Input Stream class:


Input Stream class is an abstract class. It is the super class of all classes representing an
input stream of bytes. classes that are used to read 8-bit bytes. We cannot create instance of this
class. The Input Stream class defines methods for performing input functions such as;
1) reading bytes
2) closing streams
3) Marking positions in streams
4) skipping ahead in a stream
5)Finding the number of bytes in a stream.

Commonly used methods:


1) read()-reads a byte from the input stream.
2)read(byte b[ ])-reads an array of bytes into b.
3) reset()-goes back to the beginning of the stream.
4)close()-closes the input stream.
5)skip(n)-skips over n bytes from the input stream.

OutputStreamclasses:
OutputStream class is an abstract class.It is the super class of all classes representing an
output stream of bytes. we cannot instantiate it.The methods that are designed to perform tasks
are; 1)writing bytes.
2)closing streams.
3)flushing streams.
Commonly used methods of OutputStream class:
1) write()-writes a byte to the output stream.
2) write(byte b[ ])-write all bytes in the array b to output stream.
3)close()-closes the output stream.
4)flush()-flushes the output stream.

Character stream classes:


Character stream is also defined by using two abstract class at the top of hierarchy .They
are used to Reade and Write 16-bit unicode characters.
character stream classes

reader stream classes writer stream classes

Reader Stream Classes:


Reader stream classes are designed to read character from the files. Reader class is the
base class for all other class. It contains methods that are identical to those available in the Input
stream class except reader is designed to handle characters. The reader classes can perform all
the functions implemented by the input stream classes.

Writer Stream Classes:


The Writer stream classes are designed to perform all output operations on files. The
writer stream classes are designed to write characters. This class is an abstract class which acts
as a base class for all other writer stream classes.
Some important I/O stream classes.

Stream class Description


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

3)Explain the keywords that are used to manage the exception in java?(apr-16)
An exception is an abnormal condition, which occurs during the execution of a program
Exceptions are error events like division by zero, opening of a file that does not exist. Java
provides specific keywords for exception handling purposes they are,
1)Try-Catch
2)Multiple Catch Statements.
3)Finally
4)Throwing Our Own Exceptions.
1.Try-Catch – The try block contains a block of program statements within which an exception
might occur. The corresponding catch block executes if an exception of a particular type
occurs within the try block. try is the start of the block and catch is at the end of try block to
handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be
nested also. catch block requires a parameter that should be of type Exception.
Syntax: try
{
//statements that may cause an exception
}
catch (exception-type e)‫‏‬
{
//error handling code
}

2.Finally – finally block is optional and can be used only with try-catch block. Since exception
halts the process of execution, we might have some resources open that will not get closed, so we
can use finally block. finally block gets executed always, whether exception occurred or not.
Syntax: try
{
//statements that may cause an exception
}
catch(Exception e)
{
//statements
}
finally
{
//statements to be executed
}

3.Multiple Catch Statements: When an exception in a try block is generated,java treats the
multiple catch statements like switch case statement.The first satements whose parameter
matches with exception object will be executed and the remaning statementswill be skipped.
syntax: try
{
statement;
}
catch(Exception-Type-1 e)
{
statement;
}
.
.
catch(Exception-Type-N e)
{
statement;
}
4)Throwing Our Own Exceptions.
There may be times to throw our own exception.This can be done by the keyword called
throw.It is used inside method body to invoke an exception.
syntax: throw new Throwabl'e subclass;
Throws – Throws are used to throws an exception in a method and not for handling it. this
throws keyword is used.It is specifed after the method declaration
Example:
import java.lang.Excception;
class myException extends Exception
{
MyException(String message)
{
super(messgae);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=2,y=100;
try
{
float z= (float) x/(float)y;
if(z<0.01)
{
throw new MyException("number is small");
}
}
catch(MyException e)
{
system.out.println("caught");
system.out.println(e.getMessage());
}
finally
{
system.out.println("i am");
}
}
}
output: caught
number is small
i am
4) Explain any five methods in the Graphics class?(nov-15,nov-14)
The Graphics class is the abstract super class for all graphics contexts which allow an
application to draw onto components that can be realized on various devices. some of the
methods are,
1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.

5)What are the different types of errors? Explain.(apr-15)


An error may produce an incorrect output or may terminate the execution of the program
abrupt. Error is not meant catching anything, if you catch it then also you can't recover it. There
are two types of errors ,they are;
1)Compile-Time Errors.
2)Run-Time Errors.
1)Compile-Time Errors.
All syntax errors will be detected and displayed by the java compiler and therefore these
errors are know as compile-time errors. The compiler displays an errror,it will not create the
.class file. The most common problems are,
 Misspelled identifiers and keywords
 Missing semicolons
 Improperly matches parentheses, square brackets, and curly braces
 Incorrect format in selection and loop statements
 use of undeclared variables
2)Run-Time Errors:
A program may compile successfully creating the .class file but may not run properly.
such errors may produce wrong results due to wrong logic or may terminate due to errors such as
stack overflow. some of the errors are ;
 Trying to divide by a variable that contains a value of zero
 Trying to open a file that doesn't exist
 Converting invalid string to a number
 Attempting to use a negative size of an array
 Trying to illegally change the state of a thread

Example:
class exam
{
public static void main(string args[])
{
int a=10,b=0,c;
c=a/b; //divide by zero(run time error)
system.out.println("the value of c:"+c) //semi-colon missing(compile time error)
}
6)Give a brief account on character stream classes?(apr-16)
Character stream is also defined by using two abstract class at the top of hierarchy .They
are used to Reade and Write 16-bit unicode characters.

character stream classes

reader stream classes writer stream classes

Reader Stream Classes:


Reader stream classes are designed to read character from the files. Reader class is the
base class for all other class.It contains methods that are identical to those available in the Input
stream class except reader is designed to handle characters.The reader classes can perform all the
functions implemented by the input stream classes.

Hierarchy of reader stream classes


Writer Stream Classes:
The Writer stream classes are designed to perform all output operations on files. The
writer stream classes are designed to write characters. This class is an abstract class which acts
as a base class for all other writer stream classes.

Hierarchyof reader stream classes


Some important Charcter stream classes:

Stream class Description


BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output

7)How exceptions are handled in java? Explain. (apr-14)


Refer question no:3 in 5 marls

8)Explain Keywords that are used to manage the exceptions in java?(apr-16)


Refer question no:3 in 5 marls
10marks:

1)List and explain any five methods in the Graphics class?(apr-12)


The Graphics class is the abstract super class for all graphics contexts which allow an
application to draw onto components that can be realized on various devices. A Graphics object
encapsulates all state information required for the basic rendering operations that Java supports.
State information includes the following properties.
 The Component object on which to draw.
 A translation origin for rendering and clipping coordinates.
 The current clip.
 The current color.
 The current font.
 The current logical pixel operation function.
some of the methods are,
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
8. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
Example:
import java.applet.*;
import java.awt.*;
/* <applet code="GraphicsDemo" width="300" height="300">
</applet>*/
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
2)What is an exception? How exceptions are handled in java? Explain.(apr-13,nov-15)
An exception is an abnormal condition, which occurs during the execution of a program
Exceptions are error events like division by zero, opening of a file that does not exist.There are
two types of exceptions;
1)checked exceptions
2)un checked exceptions

1)checked exceptions: These exceptions are explicity handled in the code itself with the help of
try-catch blocks. checked exceptions are extented from the java.lang.Exception class.

some common checked exceptions are,


Exception Description
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or
interface.
InterruptedException One thread has been interrupted by another thread.

2)unchecked exceptions:These exceptions are not essentially handled in the program


code;instead the JVM handles such excceptions.uncheccked eceptions are extended from the
java.lang.RuntimeException

some common unchecked exceptions are,


Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.

Java provides specific keywords for exception handling purposes they are,
1)Try-Catch
2)Multiple Catch Statements.
3)Finally
4)Throwing Our Own Exceptions.
try Block
Statement that causes
an exception Exception object creator

Throws
exception
object

catch Block Exception handler


Statement that handles
the exception

Exception handling mechanism

1.Try-Catch – The try block contains a block of program statements within which an exception
might occur. The corresponding catch block executes if an exception of a particular type
occurs within the try block. try is the start of the block and catch is at the end of try block to
handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be
nested also. catch block requires a parameter that should be of type Exception.
Syntax: try
{
//statements that may cause an exception
}
catch‫(‏‬exception-type‫‏‏‬e)‫‏‬
{
//error handling code
}

2.Finally – finally block is optional and can be used only with try-catch block. Since exception
halts the process of execution, we might have some resources open that will not get closed, so we
can use finally block. finally block gets executed always, whether exception occurred or not.
Syntax: try
{
//statements that may cause an exception
}
catch(Exception e)
{
//statements
}
finally
{
//statements to be executed
}
3.Multiple Catch Statements: When an exception in a try block is generated,java treats the
multiple catch statements like switch case statement.The first satements whose parameter
matches with exception object will be executed and the remaning statementswill be skipped.
syntax: try
{
statement;
}
catch(Exception-Type-1 e)
{
statement;
}
.
.
.
catch(Exception-Type-N e)
{
statement;
}

4)Throwing Our Own Exceptions.


There may be times to throw our own exception.This can be done by the keyword called
throw. It is used inside method body to invoke an exception.
syntax: throw new Throwabl'e subclass;
Example:
import java.lang.Excception;
class myException extends Exception
{
MyException(String message)
{
super(messgae);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=2,y=100;
try
{
float z= (float) x/(float)y;
if(z<0.01)
{
throw new MyException("number is small");
}
}
catch(MyException e)
{
system.out.println("caught");
system.out.println(e.getMessage());
}
finally
{
system.out.println("i am");
}
}
}
output: caught
number is small
i am

Throws – Throws are used to throws an exception in a method and not for handling it. this
throws keyword is used.It is specifed after the method declaration

Example:
Class xthrows
{
static void m( ) throws ArithmeticException
{
int x=2,y=0,z;
z=x/y;
}
public static void main(string args[])
{
try
{
m( );
}
catch(ArithmeticException e)
{
system.out.prinntln("caught exception"+e);
}
}
}
output: caught exception java.lang. ArithmeticException:/by zero.

3) Explain the life cycle of an applet program?(nov-13,apr-16,apr-14)


Every applet inherits a set of default behaviours from Applet class. When applet is
loaded, it undergoes a series of changes in its state. The applet 4 states are,
1)Born on initialization state.
2)Running state.
3)Idle state.
4)Dead or destroyed state.
Initial State:
When a new applet is born or created, it is activated by calling init() method. At this
stage, new objects to the applet are created, initial values are set, images are loaded and the
colors of the images are set. An applet is initialized only once in its lifetime. It's general form is:
public void init( )
{
//Action to be performed
}
Running State:
An applet achieves the running state when the system calls the start() method. This
occurs as soon as the applet is initialized. An applet may also start when it is in idle state. At that
time, the start() method is overridden. It's general form is:
public void start( )
{
//Action to be performed
}
Idle State:
An applet comes in idle state when its execution has been stopped either implicitly or
explicitly. An applet isimplicitly stopped when we leave the page containing the currently
running applet. An applet is explicitly stopped when we call stop() method to stop its execution.
It's general form is:
public void stop
{
//Action to be performed
}
Dead State:
An applet is in dead state when it has been removed from the memory. This can be done
by using destroy()method. It's general form is:
public void destroy( )
{
//Action to be performed
}
Example:
/*<applet code="life" height="200" width="200">
</applet>*/
import java.applet.*;
import java.awt.*;
public class life extends Applet
{
public void init()
{
setBackground(Color.yellow);
setFont(new Font("",Font.BOLD,30));
Label lab1=new Label("lifecycle Applet");
add(lab1);
System.out.println("Init called");
}
public void start()
{
System.out.println("start called");
}
public void paint(Graphics g)
{
System.out.println("paint called");
}
public void stop()
{
System.out.println("stop called");
}
public void destroy()
{
System.out.println("destroy called");
}
}
output:
applet viewer opens.once it is closed it will dispaly the statement present in all states.
Init called
start called
paint called
stop called
destory called
4)Briefly explain the fundamentals of exception handling(apr-15)
Answer:Refer 10 mark question no:2

5)Discuss the keywords that are used to manage Exceptions in java?(nov-12,nov-14)


Answer:Refer 10 mark question no:2

You might also like