A M Jain College Shift - Ii Department of Computer Applications Programming in Java - Saz4A Previous University Questions and Answers 2 Marks
A M Jain College Shift - Ii Department of Computer Applications Programming in Java - Saz4A Previous University Questions and Answers 2 Marks
2 MARKS
12. Write the purpose of new operator? Give an example. (Apr-12) (Nov-13)
The new operator creates an object of the specified class and return a reference
to that object.
20. Give the general syntax of the basic form of a class in Java. (Apr-15) (Apr-
14)
Class classname [extends superclassname]
{
[ fields declaration; ]
[ methods declaration; ]
}
34. What is the major difference between an interface and a class? (Nov-15)
Class Interface
The members of a class can be The members of an interface are always
constant or variables. declared as constant, i.e., their values are
final.
The class definition can contain the The methods in an interface are abstract
code for each of its methods. That in nature, i.e., there is no code associated
is, the methods can be abstract or with them. It is later defined by the class
non-abstract. that implements the interface.
It can be instantiated by declaring It cannot be used to declare objects. It
objects. can only be inherited by a class.
It can use various access specifiers It can only use the public access specifier.
like public, private, or protected.
47. How does string class differ from the string buffer class?(Nov-12)
String Class: It is immutable means once created the value cannot be changed
the value of the object. The object created as a string is stored in the constant
string pool.
String Buffer Class: It is mutable means one can change the value of the object.
The object created through string buffer is stored in the heap.
It is possible to create two or more methods that have same name ,with
different parameter list is referred to as method overloading. When a method is
called, it matches up with the method name and type of arguments.
syntax:
class identifier
{
Returntype methodname()
{statement;}
Returntype methodname(parameter list)
{statement n;}
}
The java.util.Vector class can be used to create a generic dynamic array known as vector.
Vector can hold objects of any type and any number.
The advantages of vectors over arrays are
• It is convenient to use vectors to store objects.
• A vector can be used to store a list of objects that may vary in size.
• We can add and delete objects from the list as and when required.
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
}
The layout manager is associated with every Container object. Each layout
manager is an object of the class that implements the LayoutManagerinterface.The
Layout managers is set by the setLayout() method.The general format is void
setLayout (LayoutManagerobj)
The various layout managers are;
1) Border Layout Manager.
2) Flow Layout Manager.
3)Grid Layout Manager.
The main advantage of java is portability. Java applications that are compiled
to byte code can be interpreted by any system that implements the java virtual
machine. The byte code generated by the java compiler can be implemented on any
machine and the size of the primitive data types are machine independent. Java
programs can be easily moved from one computer to another anywhere anytime.
Changes and upgrades in operating systems, processors and system resources will not
force any change in java programs. This means that java applications are able to run
on most platforms. Hence java is known as platform independent language.
CLASS OBJECTS
Class is a blue print or template from Object is an instance of a class
which objects are created
Class is a group of similar objects Object is a real world entity which may
be a place, person or things
Class is declared using the keyword class Object is created through keyword new
Ex. class Student{} Ex. Student s=new Student();
Class doesn’t allocated memory when it is Objects allocated memory when it is
created created
Class is a logical entity Object is a physical entity
Class is created once Object is created many times as per
requirement
• All classes and interfaces names starts with a leading uppercase letters.(ex.
System)
• If there are multiple words in the class name then each word must also begin
with a capital letter. (ex. BufferedReader)
Catch block defined by the keyword catch “catches” the exception “thrown”
by the try block and handles it appropriately. The catch block is added immediately
after the try block.
Attribute Meaning
CODE=AppetFileName.class Specifies the name of the applet class to be
loaded. That is, the name of the already complied
.class file
CODEBASE=codebase_url Specifies the URL of the directory in which the
(Optional) applet resides. In case of local applet the
CODEBASE attribute may be omitted entirely. In
case of remote applet CODEBASE attribute must
be specified.
WIDTH=pixels Specify the width of the space on the HTML page
that will be reserved for the applet
HEIGHT=pixels Specify the height of the space on the HTML
page that will be reserved for the applet
For modulo division the sign of the result is always the sign of the first
operand.
Therefore,
14%(-3) = 2
An Array is a group of data items of similar data type that share a common
name. Arrays can contain primitive data types as well as object of a class depending
on the definition of array. In case of primitive data types, the actual values are stored
in contiguous memory locations. In case of objects of a class, the actual objects are
stored in heap segment.
FIVE MARKS QUESTIONS
2)Datagram socket:
The datagram communication protocol, known as UDP (user datagram protocol),
is a connectionless protocol, DatagramPacket is a message that can be sent or received. If
you send multiple packet, it may arrive in any order. packet delivery is not guaranteed.
Class constructors:
1) DatagramSocket() throws SocketEeption: it creates a datagram socket and binds
it with the available Port Number on the localhost machine.
2) DatagramSocket(int port) throws SocketEeption: it creates a datagram socket
and binds it with the given Port Number.
1
3) DatagramSocket(int port, InetAddress address) throws SocketEeption: it
creates a datagram socket and binds it with the specified port number and host
address.
Example :server:
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main(String args[])
{
Try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Client:
import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String args[])
{
Try
{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
2
{
System.out.println(e);
} }}
import java.io.*;
class fact
try
int n=Integer.parseInt(br.readLine());
int fact;
for(inti=1i<=n;i++)
fact=fact*i;
System.out.println(fact);
}}
3
catch(Exception e){}
}}
The Color class states colors in the default sRGB color space or colors in arbitrary
color spaces identified by a ColorSpace.
Class declaration:The declaration for java.awt.Color class:
publicclassColorextendsObject implementsPaint,Serializable
Field:The fields for java.awt.geom.Arc2D class:
1. static Color black -- The color black.
2. static Color BLACK -- The color black.
3. static Color blue -- The color blue.
4. static Color BLUE -- The color blue.
5. static Color cyan -- The color cyan.
6. static Color CYAN -- The color cyan.
Class constructors:
S.No Constructor & Description
1 Color(ColorSpacecspace, float[] components, float alpha)-Creates a color in
the specified ColorSpace with the color components specified in the float array
and the specified alpha.
2 Color(float r, float g, float b)-Creates an opaque sRGB color with the
specified red, green, and blue values in the range (0.0 - 1.0).
3 Color(float r, float g, float b, float a)-Creates an sRGB color with the
specified red, green, blue, and alpha values in the range (0.0 - 1.0).
4 Color(intrgb)-Creates an opaque sRGB color with the specified combined
RGB value consisting of the red component in bits 16-23, the green component
in bits 8-15, and the blue component in bits 0-7.
5 Color(int r, int g, int b)-Creates an opaque sRGB color with the specified red,
green, and blue values in the range (0 - 255).
6 Color(int r, int g, int b, int a)-Creates an sRGB color with the specified red,
green, blue, and alpha values in the range (0 - 255).
Methods:
1. intgetBlue()-Returns the blue component in the range 0-255 in the default sRGB
space.
2. static Color getColor(String nm)-Finds a color in the system properties.
3. intgetGreen()-Returns the green component in the range 0-255 in the default
sRGB space
4. intgetRed()-Returns the red component in the range 0-255 in the default sRGB
space.
4
5. intgetRGB()-Returns the RGB value representing the color in the default
sRGBColorModel.
Example:
importjava.awt.*;
importjava.applet.*;
/*<applet Code="color" Width=500 Height=200>
</applet>*/
public class color extends Applet
{
publicvoid paint(Graphics g)
{
FontplainFont=newFont("Serif",Font.PLAIN,24);
g.setFont(plainFont);
g.setColor(Color.red);
g.drawString("Welcome to college",50,70);
g.setColor(Color.green);
g.drawString("hai",50,120);
}
}
Output:
Welcome to college
hai
5
S1.setLength(n) Sets the length of the string S1 to n.
Example Program:
PALINDROME CHECKING
import java.io.*;
classpalind
String str=br.readLine();
StringBuffersb=new StringBuffer(str).reverse();
String strrev=sb.toString();
if(str.equalsIgnoreCase(strrev))
else
6
}
7.Write a program that counts the even and odd numbers in the list of
numbers(Apr 14)
import java.io.*;
classOddeven
{
public static void main(String args[])throws IOException
{
intecount=0,ocount=0, n;
7
2. Each vector tries to optimize storage management by maintaining acapacity and
a capacityIncrement.
3. Vector is synchronized.This class is a member of the Java Collections Framework.
Class constructor:
1. Vector()-This constructor is used to create an empty vector so that its internal data
array has size 10 and its standard capacity increment is zero.
2. Vector(intinitialCapacity)-This constructor is used to create an empty vector
with the specified initial capacity and with its capacity increment equal to zero.
Methods:
1. boolean add(E e)-This method appends the specified element to the end of this
Vector.
2. void add(int index, E element)-This method inserts the specified element at the
specified position in this Vector.
3. void clear()-This method removes all of the elements from this vector.
The Java URL class represents an URL. URL is an acronym for Uniform Resource
Locator. It points to a resource on the World Wide Web. For ex:
http://www.college.com/office
A URL contains many information;
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.school.com is the server name.
3. Port Number: It is an optional attribute. If we write
http//ww.college.com:80/office/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index1.jsp is the file name. The
java.net.URL class provides many methods. The important methods of URL class
are given below,
Method Description
public String getProtocol() it returns the protocol of the URL.
8
public String getFile() it returns the file name of the URL.
public URLConnectionopenConnection() it returns the instance of URLConnection
i.e. associated with this URL.
Example :
import java.io.*;
import java.net.*;
public class url1
{
public static void main(String args[])
{
try
{
url1 url=new url1("http://www.college.com/office");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Protocol: http
Host Name: www.college.com
Port Number: -1
File Name: /office
9
Public static InetAddressgetLocalHost() It returns the instance of
throws UnknownHostException InetAddressconatiningLocalHost name
and address.
Public String getHostName() It returns the host name of the IP
address.
Public String getHostAddress() It retturns the IP address in string
format.
Example:
import java.io.*;
import java.net.*;
public class InetDemo
{
public static void main(String args[])
{
try
{
InetAddress ip=InetAddress.getByName("www.college.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Host Name: www.college.com
IP Address: 206.51.231.148
Example method 1:
The second method is to draw polygons more conveniently using the drawPolygon()
method of Graphics class. This method takes three arguments:
Example Method 2:
11
o Defining x coordinates values as an array
o Defining y coordinates values as an array
o Defining the number of points n
o Creating a Polygon object and initializing it with x,y,n values
o Calling the method drawPolygon() or fillPolygon() with the polygon object
as arguments.
Exampe Method 3:
Constructors Description
Method
Boolean canDisplay(char c) Checks if this font has a glyph for the
specified character.
Int canDisplayUpTo(String str) Indicates whether or not this font can
display a specified string
IntcanDisplayUpTo(CharacterIteratoriter, Indicates whether or not this font can
int start, int limit) display the text specified by the
iterstartint at start and ending at limit.
Static Font createFont(intfontFormat, Returns a new font using the specified
12
InputStreamfontStream) font type and input data
A file can be created an opened for random access by giving a mode string as a
parameter to the constructor when we open the file.We can use one of the following two
mode strings
An existing file can be updated using the “rw” mode.Random access file support
a pointer known as file pointer that can be moved to arbitrary positions in the file pror to
reading or writing. The file pointer is moved using the method seek() in the
RandomAccessFile class.
Example:
import java.io.*;
class Random
RandomAccessFile file=null;
13
try
file.writeChar('X');
file.writeInt(555);
file.writeDouble(3.14123);
file.seek(0);
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2);
System.out.println(file.readInt());
file.close();
catch(IOException e)
System.out.println(e);
}}}
14
1.Default:
When a Method is set to default it will be accessible to the classes which are
defined in the same package. Any Method in any Class which is defined in the same
package can access the given Method via Inheritance or Direct access.
2.Public Access:
Public Access modifiers Specifies that data Members and Member Functions those
are declared as public will be visible in entire class in which they are defined. Public
Modifier is used when we wants to use the method any where either in the class or from
outside the class. The Variables or methods those are declared as public are accessed in
any where , Means in any Class which is outside from our main program or in the
inherited class or in the class that is outside from our own class where the method or
variables are declared.
3.Protected Access:
The Methods those are declared as Protected Access modifiers are Accessible to
Only in the Sub Classes but not in the Main Program , This is the Most important Access
Modifiers which is used for Making a Data or Member Function as he may only be
Accessible to a Class which derives it but it doesn’t allows a user to Access the data
which is declared as outside from Program Means Methods those are Declared as
Protected are Never be Accessible to Another Class The Protected will be Accessible to
Only Sub Class and but not in your Main Program.
4.Private Access:
The Methods or variables those are declared as private Access modifiers are not
would be not Accessed outside from the class or in inherited Class or the Subclass will
not be able to use the Methods those are declared as Private they are Visible only in same
class where they are declared. By default all the Data Members and Member Functions is
Private, if we never specifies any Access Modifier in front of the Member and Data
Members Functions.
15
The access level cannot be more restrictive than the overridden method's access
level. For example: If the superclass method is declared public then the
overridding method in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared
public or protected.
Constructors cannot be overridden.
Super :
When a sub class needs to refer to its immediate super class. It can done by using
a keyword called super. There are two types of super ,
Example :-
import java . io . *;
classsuper
{
int x;
super(int x)
{
this.x=x;
}
void display()
{
system.out.println("super x:"+x);
}
}
class sub extends super
{
16
int y;
sub(intx,int y)
{
super(x);
this.y=y;
}
voiddispaly()
{
system.out.println(" super x="+x);
system.out.println("sub y='+y);
}
}
class over
{
public static void main(string args[])
{
sub s1=new sub(10,20);
s1.display();
}
}
output:
super x=10
sub y=20
17
Example :-
import java.io.*;
class overload
{
intnum(int x)
{
System .out .println(“Double x=”+x);
return(x);
}
intnum(intx,int y)
{
System .out .println(“Int x and y=”+x+” “+y);
return(x+y);
}
}
classoverloadDemo
{
public static void main (String args[])
{
Overload od=new overload();
Od .num(8);
Od .num(8,8);
}}
output:
8
16
18
2.equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case
(upper or lower case doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output:true
3.length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output:8
4.replace()
replace() method replaces occurances of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output:Change Me
5.toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to
lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output:abcdef
6.trim()
This method returns a string from which any leading and trailing whitespaces has been
removed.
String str = " hello ";
System.out.println(str.trim());
Output:hello
data member
method
constructor
block
class and interface
Syntax:
class <class_name>
{
19
data member;
method;
}
we have created a Student1 class that have only one method. We are creating the object
of the Student1 class by new keyword and printing the objects value.
class Student1
{
voiddisp()
{
system.out.println("hai");
}
class stud
{
public static void main(String args[])
{
Student1 s1=new Student1();
s1.disp();
}
}
output:hai
20
4.Hierarchical Inheritance
5.Hybrid Inheritance (Through Interface)
1.Single Inheritance:
Single Inheritance is the simple inheritance of all, When a class extends another
class(Only one class) then we call it as Single inheritance. The below diagram represents
the single inheritance in java where Class B extends only one class Class A. Here Class
B will be the Sub class and Class A will be one and only Superclass.
2.Multiple Inheritance:
Multiple Inheritance is nothing but one class extending more than one class.
Multiple Inheritance is basically not supported by many Object Oriented
Programming languages such as Java, Small Talk, C# etc.. (C++ Supports Multiple
Inheritance). As the Child class has to manage the dependency of more than
one Parent class. But you can achieve multiple inheritance in Java using Interfaces.
3.Multilevel Inheritance:
In Multilevel Inheritance a derived class will be inheriting a parent class and as
well as the derived class act as the parent class to other class. As seen in the below
diagram. ClassB inherits the property of ClassA and again ClassB act as a parent
for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.
21
4.Hierarchical Inheritance:
In Hierarchical inheritance one parent class will be inherited by many sub classes.
As per the below example ClassAwill be inherited by ClassB,
ClassC and ClassD. ClassA will be acting as a parent class for ClassB,
ClassC and ClassD.
5.Hybrid Inheritance:
Hybrid Inheritance is the combination of both Single and Multiple Inheritance.
Again Hybrid inheritance is also not directly supported in Java only through interface we
can achieve this. Flow diagram of the Hybrid inheritance will look like below. As you
can ClassA will be acting as the Parent class
for ClassB&ClassC and ClassB&ClassC will be acting as Parent for ClassD.
22
Example:
import java.io.*;
classClassA
{
publicvoiddispA()
{
System.out.println("hai");
}
}
publicclassClassBextendsClassA
{
publicvoiddispB()
{
System.out.println("hello");
}
publicstaticvoid main(Stringargs[])
{
ClassB b =newClassB();
b.dispA();
b.dispB();
}
}
output:
hai
hello
23
In case of java, the keyword synchronisedhelps to solve such problems by keeping a
watch on such locations. For example, the method that will read information from a
file and the method that will update the same file may be declared as synchronized.
Example:
synchronizedvoid update( )
{
………………
………………
}
When we declare a method synchronized, java creates a “monitor” and hands it over to
the thread that calls the method first time. As long as the thread holds the monitor, no
other thread can enter the synchronized section of code. A monitor is like a key and
thread that holds the key can only open the lock.
It is also possible to mark a block of code as synchronized as shown below:
Synchronised(lock-object)
{
………………….
…………………
}
Whenever a thread has completed its work of using synchronized method (or block of
code), it will hand over the monitor to the next thread that is ready to use the same
resource.
An interesting situation may occur when two or more threads are waiting to gain
control of a resource. Due to some reasons, the condition on which the waiting threads
rely on to gain control does not happen. This result in what is known as deadlock. For
example, assume that the thread A must access Method1 before it can release
Method2, but the thread B cannot release Method1 until it gets hold of Method2.
Because these are mutually exclusive conditions, a deadlock occurs.
ThreadA
synchronizedmethod2 ( )
{
synchronized method1 ( )
{
………………….
…………………
}
}
24
Thread B
synchronized method1 ( )
{
synchronized method2 ( )
{
………………….
…………………
}
}
In Java, each thread is assigned as priority, which affects the order in which it is
scheduled for running. The threads that we have discussed so far are of the same
priority. The threads of the same priority are given equal treatment by the java
scheduler and, therefore, they share the processor on a first-come, first-serve basis.
Java permits us to set the priority of a thread using the setPriority() method as
follows:
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread’s priority is set. The Thread
class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10.
Note that the default setting is NORM_PRIORITY.
By assigning priorities to threads, we can ensure that they are given the attention (or
lack of it) they deserve. For example, we may need to answer an input as quickly as
possible. Whenever multiple threads are ready for execution, the java system chooses
25
the highest priority thread and executes it. For a thread of lower priority to gain
control, one of the following things should happen:
However, if another thread of a higher priority comes along, the currently running
thread will be pre-empted by the incoming thread thus forcing the current thread to
move to the runnable state. Remember that the highest priority thread always preempts
any lower priority threads.
Example Program:
26
System.out.println(“thread started”);
for(int k=1;k<=4;k++)
{
System.out.println(“\t From thread C: k=”+k);
}
System.out.println(“Exit from C”);
}
}
classThreadPriority
{
Public static void main(String args[])
{
A threadA= new A();
B threadB= new B();
C thread= newC();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println(“Start thread A”);
threadA.start();
System.out.println(“Start thread B”);
threadB.start();
System.out.println(“Start thread C”);
ThreadC.start();
System.out.println(“End of main thread”);
}
}
OUTPUT:
start thread A
start thread B
start thread C
threadB started
From Thread B: j=1
From Thread B: j=2
threadC started
From Thread C : k=1
27
From Thread C: k=2
From Thread C : k=3
From Thread C : k=4
Exit from C
End of main thread
From Thread B : j=3
From Thread B : j=4
Exit from B
threadA started
From Thread A :i=1
From Thread A :i=2
From Thread A :i=3
From Thread A :i=4
Exit from A
Stopping a thread:
Whenever we want to stop a thread from running further, we may do so by calling its
stop() method, like:
aThread.stop();
This statement causes the thread to move to the dead state. A thread will also move to
the dead state automatically when it reaches the end of its method. The stop() method
may be used when the premature death of a thread is desired.
Blocking a thread:
A thread can also be temporarily suspended or blocked from entering into the runnable
and subsequently running state by using either of the following thread methods:
Sleep()
Suspend()
Wait()
These methods cause the thread to go into the blocked(or not-runnable) state. The
thread will return to the runnable state when the specified time is elapsed in the case of
sleep(), the resume() method is invoked in the case of suspend(), and notify() method
is called in the case of wait().
28
25.Write about creation of files with examples. (Apr-12)
If we want to create and use a disk file, we need to decide the following about the file
and its intended purpose:
• Suitable name for the file
• Data type to be stored
• Purpose (reading, writing or updating)
• Method of creating the file
A filename is a unique string of characters that helps identify a file on the disk. The
length of a filename and the characters allowed are dependent on the OS on which the
Java program is executed. A filename may contain two parts, a primary name and an
optional period with extension. Examples:
Input.data salary
Test.doc student.txt
Inventory rand.dat
Data type is important to decide the type of file stream classes to be used for handling
the data. We should decide whether the data to be handled is in the form of characters,
bytes or primitive type.
The purpose of using a file must also be decided before using it. For example, we
should know whether the file is created for reading only or writing only, or both the
operations.
Source or Characters Bytes
Destination
Read Write Read Write
29
26.Write about Java Statements. (Apr-13)
Expression Guarding
Statement Labelled Synchronization Statement
Statement Statement
Control
Statement
while for
30
if break return
switch do
if-else continue
1. Abstract Method:
It is a method in which we have only method declaration but it will not have definition
or body. Abstract methods are declared with abstract keyword and terminated by
semicolon (;)
Syntax: abstract return_typeMethodName(parameter_list);
● In a class hierarchy when a superclass containing an abstract method. All the
subclasses of that superclass must override the base class method.
● If the child fails to override the superclass abstract method, the child class must
also be abstract.
● Hence abstract method follows the process of method overriding.
2. Abstract Classes:
A class which consists atleast one abstract method is called abstract class. The class
definition must be preceded by abstract keyword.
Syntax:
abstract class className
{
-----
abstractreturntypeMethodName(parameter_list)
{
-------
}
-------
31
}
Example:
abstract class Shape
{
abstract void callMe();
}
class sub extends Shape
{
voidcallMe()
{
System.out.println(“I am sub’s Method”)
}
}
classDemoAbstract
{
public static void main(String ar[])
{
sub s=new sub();
s.callMe();
}
}
32
10 MARKS
Wrapper class in java provides the mechanism to convert primitive into object and
object into primitive. autoboxing and unboxing feature converts primitive into object
and object into primitive automatically. The automatic conversion of primitive into object
is known and autoboxing and vice-versa unboxing. One of the eight classes
of java.lang package are known as wrapper class in java. The list of eight wrapper classes
are given below:
The wrapper classes have number of unique method for handling primitive data
types and object.
1
Str = Float .toString (f) ; -convert primitive float to string
Str = Double .toString (d) ; -convert primitive double to string
Str = Long .toString (l) ; -convert primitive long to string
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.
2
Data Input
Hierarchy of inputstreamclasses
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.
3
Data Output
3. Describe the usage of character stream class and file stream class(Apr12)
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.
4
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.
5
4. Explain the various Layout managers in java?(apr-12,apr-15)
The layout manager is associated with every Container object. Each layout
manager is an object of the class that implements the LayoutManagerinterface.The
Layout managers is set by the setLayout() method.The general format is void setLayout
(LayoutManagerobj)
The various layout managers are;
1) Border Layout Manager.
2) Flow Layout Manager.
3)Grid Layout Manager.
6
Button b2= new Button (“South”);
Button b3= new Button (“East”);
Button b4= new Button (“West”);
Button b5= new Button (“Center”);
add(b1,”North”);
add(b2,”South”);
add(b3,”East”);
add(b4,”West”);
add(b5,”Center”);
}
}
Output:
7
Methods:
1) intgetAlignment()-Gets the alignment for this layout.
2) voidaddLayoutComponent(String name, Component comp)-Adds the
specified component to the layout.
3) voidlayoutContainer(Container target)-Lays out the container.
Example:
importjava.applet.*;
importjava.awt.*;
public class flow extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,5,5));
for(inti= 1,i<6;i++)
{
add(new Button(“ ”+i);
}
}
}
Output:
8
Methods:
1) voidaddLayoutComponent(String name, Component comp)-Adds the
specified component with the specified name to the layout.
2) intgetColumns()-Gets the number of columns in this layout.
3) intgetHgap()-Gets the horizontal gap between components.
4) intgetRows()-Gets the number of rows in this layout.
Example:
importjava.applet.*;
importjava.awt.*;
public class grid extends Applet
{
Button b1,b2;
GridLayout g=new GridLayout(2,2);
public void init()
{
setLayout(g);
b1=new Button(“how”);
b2=new Button(“Are”);
b3=new Button(“You”);
b4=new Button(“hai”);
add(b1);
add(b2);
add(b3);
add(b4);
}
}
Output:
How Are
You hai
9
5. Desribe the various methods of AWT classes and write a program using
AWT?(APR-13)
2.Window:
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.
3.Panel:
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
4. Frame
The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
10
Methods:
1. public void add(Component c)- inserts a component on this component
2. public void setSize(intwidth,int height)- sets the size (width and height) of the
component.
3. public void setLayout(LayoutManager m)- defines the layout manager for the
component.
4. public void setVisible(boolean status)- changes the visibility of the component,
by default false
There are two ways to create a frame in AWT.
1. By extending Frame class.
2. By creating the object of Frame class.
The various AWT controls in java are,
1. Label
2. Button
3. Check Boxes
4. List
5. Scroll Bar
6. Choice
7. Text Area
11
Example:
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
First f=new First();
}
}
Output:
12
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.
Java provides specific keywords for exception handling purposes they are,
1)Try-Catch
2)Multiple Catch Statements.
3)Finally
4)Throwing Our Own Exceptions.
13
try Block
Statement that causes
an exception Exception object creator
Throws
exception
object
catch Block Exception handler
Statement that handles
the exception
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
{
14
//statements to be executed
}
syntax: try
{
statement;
}
catch(Exception-Type-1 e)
{
statement;
}
.
.
.
catch(Exception-Type-N e)
{
statement;
}
Example:
importjava.lang.Excception;
classmyException extends Exception
{
MyException(String message)
{
super(messgae);
}
}
classTestMyException
{
15
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( );
}
16
catch(ArithmeticException e)
{
system.out.prinntln("caught exception"+e);
}
}
}
output: caught exception java.lang. ArithmeticException:/by zero.
7.Describe in detail the methods of Graphics class with example ( Nov 14, Apr 15)
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.
17
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);
}
}
1.Label :Label is a passive control because it does not create any event when accessed by
the user. The label control is an object of Label. A label displays a single line of read-
only text.
Class declaration:
The declaration for java.awt.Label class:
public class Label extends Component implements Accessible
Field:
Following are the fields for java.awt.Component class:
18
Class constructors:
S.No Constructor & Description
1 Label()-Constructs an empty label.
2 Label(String text)-Constructs a new label with the specified string of text, left
justified.
3 Label(String text, int alignment)-Constructs a new label that presents the specified
string of text with the specified alignment.
Methods:
1)intgetAlignment()-Gets the current alignment of this label.
2)StringgetText()-Gets the text of this label
3)voidsetAlignment(int alignment)-Sets the alignment for this label to the
specified alignment.
2.Button:It is a control component that has a label and generates an event when pressed.
When a button is pressed and released, AWT sends an instance of ActionEvent to the
button, by calling processEvent on the button. The button's processEvent method receives
all events for the button; it passes an action event along by calling its own
processActionEvent method.
Class declaration:The declaration for java.awt.Button class:
public class Button extends Component implements Accessible
Class constructors:
S.No Constructor & Description
1 Button()-Constructs a button with an empty string for its label.
Methods:
1.voidaddActionListener(ActionListener l):Adds the specified action
listener to receive action events from this button.
2.StringgetActionCommand():Returns the command name of the action event
fired by this button.
3.StringgetLabel():Gets the label of this button.
4.voidsetActionCommand(String command):Sets the command name for the
action event fired by this button.
5.voidsetLabel(String label):Sets the button's label to be the specified string.
19
3.Checkbox:It is a graphical component that can be in either an on (true) or off (false)
state.
Class declaration:The declaration for java.awt.Checkbox class:
public class Checkbox extends Component implements ItemSelectable,Accessible
Class constructors:
S.No Constructor & Description
1 Checkbox()-Creates a check box with an empty string for its label.
2 Checkbox(String label)-Creates a check box with the specified label.
3 Checkbox(String label, boolean state)-Creates a check box with the specified
label and sets the specified state.
4 Checkbox(String label, boolean state, CheckboxGroup group)-constructs a
Checkbox with the specified label, set to the specified state, and in the specified
check box group.
5 Checkbox(String label, CheckboxGroup group, boolean state)-Creates a check
box with the specified label, in the specified check box group, and set to the
specified state.
Methods:
1. CheckboxGroupgetCheckboxGroup()-Determines this check box's group.
2. voidaddItemListener(ItemListener l)-Adds the specified item listener to receive
item events from this check box.
3. String getLabel()-Gets the label of this check box.
4.List:It represents a list of text items. The List component presents the user with a
scrolling list of text items.
Class declaration:The declaration for java.awt.List class:
public class List extends Component implements ItemSelectable, Accessible
Class constructors:
S.No Constructor & Description
1 List()-Creates a new scrolling list.
2 List(int rows)-Creates a new scrolling list initialized with the specified number of
visible lines.
3 List(int rows, booleanmultipleMode)-Creates a new scrolling list initialized to
display the specified number of rows.
Methods:
1. void add(String item)-Adds the specified item to the end of scrolling list.
2. void add(String item, int index)-Adds the specified item to the the scrolling list
at the position indicated by the index.
3. intgetItemCount()-Gets the number of items in the list.
5.Scrollbar: It represents a scroll bar component in order to enable user to select from
range of values.
20
Class declaration:The declaration for java.awt.Scrollbar class:
public class Scrollbar extends Component implements Adjustable, Accessible
Field:The fields for class:
1. staticint HORIZONTAL --A constant that indicates a horizontal scroll bar.
2. staticint VERTICAL --A constant that indicates a vertical scroll bar.
Class constructors:
S.No Constructor & Description
1 Scrollbar()-Constructs a new vertical scroll bar.
2 Scrollbar(int orientation)-Constructs a new scroll bar with the specified orientation.
3 Scrollbar(int orientation, int value, int visible, int minimum, int maximum)-
Constructs a new scroll bar with the specified orientation, initial value, visible
amount, and minimum and maximum values.
Methods:
1. intgetBlockIncrement()-Gets the block increment of this scroll bar.
2. intgetMaximum()-Gets the maximum value of this scroll bar.
Class constructors:
S.No Constructor & Description
1 Choice()-Creates a new choice menu.
Methods:
1. void add(String item)-Adds an item to this Choice menu.
2. String getItem(int index)-Gets the string at the specified index in this Choice
menu.
3. intgetSelectedIndex()-Returns the index of the currently selected item.
4. voidremoveAll()-Removes all items from the choice menu.
Methods:
1. void append(String str)-Appends the given text to the text area's current text.
2. void insert(String str, intpos)-Inserts the specified text at the specified position
in this text area.
3. voidreplaceRange(String str, int start, int end)-Replaces text between the
indicated start and end positions with the specified replacement text.
Example:
import java.applet.Applet;
import java.awt.Button;
import java.awt.Font;
/*<applet code="control" width=200 height=200>
</applet>*/
public class control extends Applet
{
public void init()
{
Label label1 = new Label("hai");
add(label1);
Button button1 = new Button("click");
Font myFont = new Font("Courier", Font.ITALIC,12);
button1.setFont(myFont);
add(button1);
Checkbox checkbox1 = new Checkbox("1");
checkbox1.setBackground(Color.red);
add(checkbox1);
List list = new List(2);
list.add("One");
22
list.add("Two");
add(list);
}
}
9.Discuss the steps involved in the developing and running a local applet. OR
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( )
{
23
//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");
24
}
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 display the statement present in all states.
Init called
start called
paint called
stop called
destory called
An interface is a group of constants and methods declarations that define the form of a
class. Java does not support multiple inheritance to overcome it interface has been used.
All the methods of an interface are automatically public.
25
Syntax :
Interface name
{
data type varname 1 = value 1;
...................................................;
...................................................;
data type varname n = value n;
Example :
Interface x
{
int a=7 , b=8 , n=9 ;
void a (int , int);
void a (int);
Extending interface :An interface can be interfaced from other interface using the
keyword called extends.
Syntax: interface sub class extends base class
{
Variable declarations ;
Method declaration ;
}
Implementing an interface :A class can extend only a single class, it can implement a
number of interface. The keyword implements is used to implement an interface.
Syntax: class class name extends super class implements interface
{
Body of the statement;
}
26
Combining Multiple interfaces:
interface InterfaceName
{
// "constant" declarations
// method declarations
}
// inheritance between interfaces
interface InterfaceName extends InterfaceName
{
...
}
interface InterfaceName extends ClassName
{ ... }
// extends multiple interfaces (multiple inheritance like)
interface InterfaceName extends InterfaceName1, InterfaceName2
{ ...
}
Interfaces and Classes
// implements instead of extends
class ClassName implements InterfaceName
{
...
}
// combine inheritance and interface implementation
class ClassName extends SuperClass implements InterfaceName
{
...
}// multiple inheritance like again
class ClassName extends SuperClass
implements InterfaceName1, InterfaceName2
{
...
}
27
Example:
interface area
{
final static float pi = 3.14f ;
float compute ( float x , float y ) ;
}
class Rectangle implements Area
{
public float compute ( float x , float y ) ;
{
return ( x * y) ;
}
}
class Circle implements Area
{
public float compute ( float x , float y)
{
return ( pi*x*y) ;
}
}
classInterfaceTest
{
public static void main(String args [ ]) throws IOException
{
Rectangle rect = new Rectangle ( ) ;
Circle cir = new Circle ( ) ;
Area a ;
a = rect ;
System.out.println( “ Area of Rectangle”+a.compute(10,30)) ;
a = cir ;
System.out.println( “ Area of Circle”+a.compute(20,0));
}
}
Output :
Area of Rectangle 300.0
Area of Circle 1256.0
28
11. Explain any five classes in java.util package?(apr-13)
Java.util package provides various classes that perform different utility functions.It
includes a class for working with dates ,generating random numbers. Some of the util
packages are,
1. Date class
2. Random class
3. String tokenzier class
4. Vector class
5. Calendar class
1.Date class:
The java.util.Date class represents a specific instant in time, with millisecond
precision.
Class constructor:
1. Date()-This constructor allocates a Date object and initializes it so that it
represents the time at which it was allocated, measured to the nearest millisecond.
2. Date(long date)-This constructor allocates a Date object and initializes it to
represent the specified number of milliseconds since the standard base time known
as "the epoch", namely January 1, 1970, 00:00:00 GMT.
Methods:
1. boolean after(Date when)-This method tests if this date is after the specified date.
2. boolean before(Date when)-This method tests if this date is before the specified
date.
3. boolean equals(Object obj)-This method compares two dates for equality.
2.Random class:
The java.util.Random class instance is used to generate a stream of pseudorandom
numbers.Following are the important points about Random:
The class uses a 48-bit seed, which is modified using a linear congruential formula.
The algorithms implemented by class Random use a protected utility method that on each
invocation can supply up to 32 pseudorandomly generated bits.
Class constructor:
1. Random()-This creates a new random number generator.
2. Random(long seed)-This creates a new random number generator using a single
long seed.
Methods:
1. protectedint next(int bits)-This method generates the next pseudorandom
number.
2. intnextInt()-This method returns the next pseudorandom, uniformly distributed
int value from this random number generator's sequence.
3. longnextLong()-This method returns the next pseudorandom, uniformly
distributed long value from this random number generator's sequence.
29
3.StringTokenizer :
The java.util.StringTokenizer class allows an application to break a string into
tokens.Its methods do not distinguish among identifiers, numbers, and quoted strings.This
class methods do not even recognize and skip comments.
Class constructor:
1. StringTokenizer(String str)-This constructor a string tokenizer for the specified
string.
2. StringTokenizer(String str, String delim)-This constructor constructs string
tokenizer for the specified string.
3. StringTokenizer(String str, String delim, booleanreturnDelims)-This
constructor constructs a string tokenizer for the specified string.
Methods:
1. intcountTokens()-This method calculates the number of times that this tokenizer's
nextToken method can be called before it generates an exception.
2. String nextToken()-This method returns the next token from this string tokenizer.
4.vector class:
The java.util.Vector class implements a growable array of objects. Similar to an
Array, it contains components that can be accessed using an integer index. The important
points about Vector:
1. The size of a Vector can grow or shrink as needed to accommodate adding and
removing items.
2. Each vector tries to optimize storage management by maintaining acapacity and
a capacityIncrement.
3. Vector is synchronized.This class is a member of the Java Collections Framework.
Class constructor:
1. Vector()-This constructor is used to create an empty vector so that its internal data
array has size 10 and its standard capacity increment is zero.
2. Vector(intinitialCapacity)-This constructor is used to create an empty vector
with the specified initial capacity and with its capacity increment equal to zero.
Methods:
1. boolean add(E e)-This method appends the specified element to the end of this
Vector.
2. void add(int index, E element)-This method inserts the specified element at the
specified position in this Vector.
3. void clear()-This method removes all of the elements from this vector.
30
5.calendar class:
The java.util.calendar class is an abstract class that provides methods for converting
between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as
getting the date of the next week.The important points about Calendar:
1. This class also provides additional fields and methods for implementing a concrete
calendar system outside the package.
2. Calendar defines the range of values returned by certain calendar fields.
Fields:
1. staticint DATE -- This is the field number for get and set indicating the day of the
month.
2. staticint DAY_OF_MONTH -- This is the field number for get and set indicating
the day of the month.
3. staticint DAY_OF_WEEK -- This is the field number for get and set indicating
the day of the week.
Example:
importjava.util.*;
publicclassRandomDemo
{
publicstaticvoid main(Stringargs[])
{
Randomrandomno=newRandom();
int value =randomno.nextInt();
System.out.println("Value is: "+ value);
}
}
Output:
Valueis:-187902182
31
class A extends Thread
{
public void run()
{
System.out.println(“threadA started”);
for(inti=1;i<=4;i++)
{
System.out.println(“\t from Thread A:=”+i);
}
System.out.println(“Exit from A”);
}
}
Class B extends Thread
{
public void run()
{
System.out.println(“thread started”);
for(int j=1;j<=4;j++)
{
System.Out.Println(“\t from Thread B: j=”+j);
}
System.out.println(“Exit from B”);
}
}
Class C extends Thread
{
Public void run()
{
System.out.println(“thread started”);
for(int k=1;k<=4;k++)
{
System.out.println(“\t From thread C: k=”+k);
}
System.out.println(“Exit from C”);
}
}
classThreadPriority
{
32
Public static void main(String args[])
{
A threadA= new A();
B threadB= new B();
C thread= newC();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println(“Start thread A”);
threadA.start();
System.out.println(“Start thread B”);
threadB.start();
System.out.println(“Start thread C”);
ThreadC.start();
System.out.println(“End of main thread”);
}
}
OUTPUT:
start thread A
start thread B
start thread C
threadB started
From Thread B: j=1
From Thread B: j=2
threadC started
From Thread C : k=1
From Thread C: k=2
From Thread C : k=3
From Thread C : k=4
Exit from C
End of main thread
From Thread B : j=3
From Thread B : j=4
Exit from B
threadA started
From Thread A :i=1
33
From Thread A :i=2
From Thread A :i=3
From Thread A :i=4
Exit from A
1)Panel: panel class is concrete sub class of Container. Panel does not contain title bar,
menu bar or border.
2)Frame:It’s a sub class of Window and have resizing canvas. It is a container that
contain several different components like button, title bar, textfield, label etc. In Java,
most of the AWT applications are created usingFrame window.
class constructors:
1) Frame() throws HeadlessException
2) Frame(String title) throws HeadlessException .
There are two ways to create a Frame. They are,
1) By Instantiating Frame class
2) By extending Frame class
Example:
34
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
First f=new First();
}
}
Output:
35
13. Write a program to input numbers in ascending numbers(Apr 15)
import java.io.*;
importjava.util.*;
class number
{
public static void main(String args[])throws IOException
{
BufferedReaderbr = new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter the no. of elements");
int n = br.nextInt();
intarr[]=new int[n];
System.out.println("Enter the elements");
for(inti=0;i<n;i++)
arr[i] = br.nextInt();
for(inti=0;i<n;i++)
{
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println("\nsorted array");
System.out.println("\n");
for(inti=0;i<n;i++)
System.out.println(arr[i]);
}
}
OUTPUT:
36
Enter the no. of elements
4
Enter the elements
2
1
53
22
sorted array
1
2
22
53
14)Write a java program to sort the given set of names in alphabetical order?(apr-
13,apr-14)
import java.io.*;
importjava.util.Scanner;
publicclassAlphabetical_Order
{
publicstaticvoid main(String[]args)
{
int n;
String temp;
Scanner s =newScanner(System.in);
n =s.nextInt();
Stringnames[]=newString[n];
Scanner s1 =newScanner(System.in);
System.out.println("Enter the names:");
for(inti=0;i< n;i++)
{
names[i]= s1.nextLine();
}
for(inti=0;i< n;i++)
{
for(int j =i+1; j < n;j++)
{
if(names[i].compareTo(names[j])>0)
{
temp= names[i];
names[i]= names[j];
names[j]= temp;
37
}
}
}
System.out.print("Sorted Order:");
for(inti=0;i< n -1;i++)
{
System.out.print(names[i]+",");
}
System.out.print(names[n -1]);
}
}
38
New thread New born Stop()
Start()
Suspend() Resume()
Sleep() Notify()
Wait () Stop()
Start Stop
39
2)Runnable state :
The thread is ready for execution and waits for the processor to be
available. All the threads in a execution queue have equal priority. The threads comes to
this state when the start ( ) method is called. This process of assigning time to threads is
known as time-slicing.If we want a thread to relinguish control to another thread equal
priority before its turn comes we can do so by using the yield ( ) method.
…… …….
..
Running thread Runnable thread
3)Running state :
The thread comes to this state when it start its execution. A thread enters this stage
whenever its run ( ) method is called. It has been suspended using suspend ( ) method. A
suspend thread can be reviewed by using the resume ( ) method.
Suspend
Resume
We can put a thread in a specified time period using the method sleep ( ) method where
time is in millisecond.
Sleep (t)
After (t)
It has been told to wait until some event occurs. This is done using the wait ( ) method.
The thread can be scheduled to run again using the notify ( ) method.
40
Wait
Notify
4)Blocked state :
A thread comes to this state when it is made to stop its execution. The thread
comes to this state when its stop ( ) or wait ( ) method is called.
5)Dead state :
A thread comes to this state when it completes its execution.
41
6)Source file and class file should be in a directory as specified in the class path
environment variable.
Example :
Package x;
public class hello
{
public void display ( )
{
System.out.println(“welcome”) ;
}
}
import x.*;
class pack
{
public static void main(string args[])
{
hello h1=new hello();
h1.display();
}
}
output: welcome
42
void a (int , int);
void a (int);}
Extending interface :An interface can be interfaced from other interface using the
keyword called extends.
Syntax: interface sub class extends base class
{
Variable declarations ;
Method declaration ;
}
Implementing an interface :A class can extend only a single class, it can implement a
number of interface. The keyword implements is used to implement an interface.
Syntax: class class name extends super class implements interface
{
Body of the statement;
}
43
{
...
}// multiple inheritance like again
class ClassName extends SuperClass
implements InterfaceName1, InterfaceName2
{
...
}
// multiple inheritance like
class ClassName implements InterfaceName1, InterfaceName2
{
...
}
Example:
interface area
{
final static float pi = 3.14f ;
float compute ( float x , float y ) ;
}
class Rectangle implements Area
{
public float compute ( float x , float y ) ;
{
return ( x * y) ;
}
}
class Circle implements Area
{
public float compute ( float x , float y)
{
return ( pi*x*y) ;
}
}
classInterfaceTest
{
public static void main(String args [ ]) throws IOException
{
Rectangle rect = new Rectangle ( ) ;
Circle cir = new Circle ( ) ;
Area a ;
a = rect ;
System.out.println( “ Area of Rectangle”+a.compute(10,30)) ;
a = cir ;
44
System.out.println( “ Area of Circle”+a.compute(20,0));
}
}
Output :
Area of Rectangle 300.0
Area of Circle 1256.0
Example:
classMyThread implements Runnable
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
classMyThreadDemo
{
public static void main( String args[] )
{
MyThreadmt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output :
45
concurrent thread started running..
Example:
classMyThreadDemo
{
public static void main( String args[] )
{
MyThreadmt = new MyThread();
mt.start();
}
}
Output :
concurrent thread started running..
46
19.write a program for copying characters from one file to another.(Nov 13)
import java.io.*;
classCopyCharacters
FileReaderins=null;
FileWriter outs=null;
try
ins=new FileReader(inFile);
outs=new FileWriter(outFile);
intch;
while((ch=ins.read())!=-1)
outs.write(ch);
catch(IOException e)
47
{
System.out.println(e);
System.exit(-1);
finally
try
ins.close();
outs.close();
catch(IOException e)
import java.io.*;
classquadeqn
double root1=0.0,root2=0.0,d;
48
BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
int c=Integer.parseInt(br.readLine());
d=b*b-4*a*c;
if(d>0)
root1=(-b+Math.sqrt(d))/(2*a);
root2=(-b-Math.sqrt(d))/(2*a);
else if(d==0)
root1=(-b+Math.sqrt(d))/(2*a);
else
49
}}
21.Write a program to find the no of and sum of all integers greater than 100 and
less than 200 that are divisible by 7.
import java.io.*;
class range
int count=0,ocount=0, n;
for(inti=100;i<=200;i++)
{if((i%7)==0)
count++;
ocount+=i;
50
5) Separators
1) keywords:
Keywords also referred as reserved words. Keywords have standard built-in
meanings that cannot be changed. Keywords should be written in lower case.
2)Identifiers:
Identifiers are programmer-designed tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interfaces in a program. Java identifier’s
basic rules are as follows:
They can have alphabets, digits, and the underscore and dollar sign characters.
They must not begin with a digit.
Uppercase and lowercase letters are distinct.( Sum is different from sum).
They can be of any length.,some of the examples are,
51
3) Literals:
A literal is the source code representation of a fixed value. Literals in Java are a
sequence of characters (digits, letters, and other characters) that represent constant values
to be stored in variables. Java language specifies five major types of literals. Literals can
be any number, text, or other information that represents a value. They are:
1) Integer literals
2) Floating literals
3) Character literals
4) String literals
5) Boolean literals
1) Integer Literals :
Integer literals are the primary literals used in java programming. They come in a few
different formats :
Decimal :- Decimal (base 10) literals appear as ordinary numbers with no special
notation. For example, an integer literal for the decimal number 12 is represented in java
as 12 in decimal.
Octal :-Octal (base 8) numbers appear with a leading 0 in front of the digits. For
example, an integer literal for the decimal number 12 is represented in java as 014 in
octal.
3)Character literals :
Character literals represent a single Unicode character and appear within a pair of
single quotation marks.
Example : ‘A’ ‘9’ ‘S’
Escape Meaning
\n New line
\t Tab
52
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\d Octal
\xd Hexadecimal
\ud Unicode character
4)Boolean literals :
The Boolean values true and false are represented by the integer values 1 and 0.
Java fixes this problem by providing a boolean type with two possible states : true and
false.
5)String literals :
String literals represent multiple characters and appear within a pair of double
quotation marks. String literals are implemented in java by the string class.When java
encounters a string literal, it creates an instance of the string class and sets its state to the
characters appearing within the double quotation marks.
Example :
“rollno” “Xavier” “456”
4.Operators :
Operator is a symbol that represent some operation that can be performed on data.
some of the operators are,
Arithmetic Operators(+,-,*,/,%).
Relational Operators(==,!=,>,>=,<,<=).
Logical Operators(&&,||,!)
Assignment Operators(=)
Increment and decrement Operators(++,--)
Conditional Operators
Bitwise Operators(~,<<,>>,&,^,|)
Special Operators.
(i). (Dot Operator) - To access instance variables
(ii) instanceof - Object reference Operator
5.Separators :
A symbol that is used to separate a group of code from another is called a
separators. For example, items in a list are separated by commas like list of items in a
sentence. In java language has six types of separators. They are :
S.no Meaning Symbol Description
53
1 Parentheses () Used to enclose an
argument in
method definition.
2 Braces {} Used to define a
block of code for
classes and
methods.
3 Brackets [] Used to declare an
array types.
4 Semicolon ; Used to separate
the statement.
5 Comma , Used to separate
identifiers (or)
variable
declarations.
6 Period . Used to separate
package names
from sub package.
Every variable in java has a data type. Data types specify the size and type of values
that can be stored. Java language is rich in data types. The variety of data types
available allow the programmer to select the type appropriate to the needs of the
application. Data types in java under various categories are shown below: primitive
types also called intrinsic or built-in types. Derived types also known as reference
types.
54
data types
in java
non-
primitive
primitive
non-
numeric classes interface arrays
numeric
floating
integer character boolean
point
Integer types:Integer types can hold whole numbers such as 123, -96 and 5639. The
size of the values that can be stored depends on the integer data type we choose. Java
supports four types of integers. They are byte, short, int and long. Java does not
support the concept of unsigned types and therefore all Java values are signed meaning
they can be positive or negative. The following table memory size and range of all the
four integer data types.
integter
55
Integer types can hold only whole numbers and therefore we use another type known
as floating point type to hold numbers containing fractional parts such as 27.59 and -
1.375 (known as floating point constants). There are two kinds of floating point
storage in Java.The float type values are single-precision numbers while the double
types represent double-precision numbers.
Floating point numbers are treated as double-precision quantities. To force to be in
single-precision mode, we must append f or F to the numbers. Example:
1.23f
7.56923e5F
Character type:
In order to store character constants in memory, Java provides a character data type
called char. The char type assumes a size of 2 bytes but, basically, it can hold only a
single character.
Boolean type:
Boolean type is used when we want to test a particular condition during the execution
of the program. There are only two values that a Boolean type can take: true or false.
Boolean type is denoted by the keyword Boolean and uses only one bit of storage.
All comparison operators return Boolean type values. Boolean values are often used in
selection and iteration statements. The words true and false cannot be used as
identifiers.
II. Secure: Security becomes an important issue for a language that is used for
programming on Internet. Threat of viruses and abuse of resources are everywhere.
Java systems not only verify all memory access but also ensure that no viruses are
communicated with an applet. The absence of pointers in java ensures that programs
can’t gain access to memory locations without proper authorization.
III. Portable: The most significant contribution of java over other languages is its
portability. Java programs can be easily moved from on computer to another,
anywhere and anytime. Changes and upgrades in operating systems, processors and
system resources will not force any changes in java programs. This is the reason
why java has become popular language for programming on internet which
56
interconnects different kinds of systems worldwide.
IV. Dynamic: java programs carry with them substantial amount of runtime
information that is used to access the objects at runtime. This makes java Dynamic.
V. Object-oriented: java is a true object oriented language. Almost everything in java
is an object. All program code and data reside within objects & classes. Java comes
with an extensive set of classes, arranged in packages that we can use in our
programs by inheritance. The object Model in java is simple and easy to extend.
VI. Robust: Java is a robust language. It provides many safeguards to ensure reliable
code. It has strict compile time and runtime checking for data types. It is designed
as a garbage collected language relieving the programmers virtually all memory
management problems. Java also incorporates the concept of exception handling
which captures serious errors and eliminates any risk of crash the system.
XI. Distributed: java is designed for the distributed environment of the internet
because it handle TCP/IP protocols. Java supports two computers to support
remotely through a package called Remote Method Invocation (RMI)
57
25) Describe the different types of operators in java?(apr-12,apr-13)
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups:
1)Arithmetic Operators
2)Relational Operators
3)Bitwise Operators
4)Logical Operators
5)Assignment Operators
6)Misc Operators
1)Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Example:
import java.io.*;
class point
{
public static void main(string args[])
58
{
int a=2,b=2;
system.out.println("a+b="+(a+b));
system.out.println("a-b="+(a-b));
system.out.println("a*b="+(a*b));
system.out.println("a/b="+(a/b));
system.out.println("a%b="+(a%b));
}
}
output:
a+b=4,a-b=0,a*b=4,a/b=1,a%b=0
2)Relational Operators:
The comparisons will be takes between two quantities depending upon their
relation,take certain decisions.Assume variable A holds 10 and variable B holds 20, then:
6 <= (less than or equal to)--------Checks if the value of left operand is less than
or equal to the value of right operand, if yes then condition becomes true.
example(A <= B) is true.
3)Bitwise Operators:
59
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.Bitwise operator works on bits and performs bit-by-bit
operation. Assume if a = 60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:Assume integer variable A holds 60 and
variable B holds 13 then:
60
7 >>> (zero fill right shift)------Shift right zero fill operator. The left operands
value is moved right by the number of bits specified by the right operand and
shifted values are filled up with zeros.
Example: A >>>2 will give 15 which is 0000 1111
4)Logical Operators:
It combines two or more relational expressions is referred as logical
expressions,Boolean variables A holds true and variable B holds false, then:
Sr.No Description
1 && (logical and)------Called Logical AND operator. If both the operands are non-
zero, then the condition becomes true.
Example (A && B) is false.
2 || (logical or)------Called Logical OR Operator. If any of the two operands are
non-zero, then the condition becomes true.
Example (A || B) is true.
3 ! (logical not)------Called Logical NOT Operator. Use to reverses the logical state
of its operand. If a condition is true then Logical NOT operator will make false.
Example !(A && B) is true.
5)Assignment Operators:
Assignment operators are used to assign the value of an expression to a
variable.syntax: v op=exp;
v= is a variable,exp=is an expression,op=is a java binary operator
61
5 /= Divide AND assignment operator, It divides left operand with the right
operand and assign the result to left operand
ExampleC /= A is equivalent to C = C / A
6 %= Modulus AND assignment operator, It takes modulus using two operands
and assign the result to left operand.
Example: C %= A is equivalent to C = C % A
7 <<= Left shift AND assignment operator.
ExampleC<<= 2 is same as C = C << 2
8 >>= Right shift AND assignment operator
Example C >>= 2 is same as C = C >> 2
9 &= Bitwise AND assignment operator.
Example: C &= 2 is same as C = C & 2
10 ^= bitwise exclusive OR and assignment operator.
Example: C ^= 2 is same as C = C ^ 2
11 |= bitwise inclusive OR and assignment operator.
Example: C |= 2 is same as C = C | 2
6)Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator
consists of three operands and is used to evaluate Boolean expressions. The goal of the
operator is to decide which value should be assigned to the variable. The operator is
written as:variable x =(expression)?valueiftrue: value iffalse
Example:
import java.io.*;
publicclassTest
{
publicstaticvoid main(Stringargs[]){
int a, b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}
output:
Value of b is : 30
62
Value of b is : 20
instance of Operator:
This operator is used only for object reference variables. The operator
checks whether the object is of a particular type (class type or interface type). instanceof
operator is written as:
(Object reference variable )instanceof(class/interface type)
precedence operators
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
63
Java programming language provides following types of decision making statements.
1) IF STATEMENT
2) IF ELSE STATEMENT
3) NESTED IF STATEMENT
4) IF ELSE LADDER STATEMENT
5) SWITCH STATEMENT
1) IF STATEMENT:
Syntax :
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
Flow Diagram
64
Example
if( x < 20 ) {
System.out.print("This is if statement");
}
}
}
Output
This is if statement.
2) IF ELSE STATEMENT:
Syntax
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
65
Flow Diagram
Example
Output
3) NESTED IF STATEMENT:
It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax
if(Boolean_expression 1) {
66
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
Example
publicclassTest{
publicstaticvoid main(Stringargs[]){
int x =30;
int y =10;
if( x ==30){
if( y ==10){
System.out.print("X = 30 and Y = 10");
}
}
}
}
Output
X = 30 and Y = 10
4) IF ELSE LADDER:
Syntax
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}
Example
67
public class Test {
public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
System.out.print("Value of X is 30");
}else {
System.out.print("This is else statement");
}
}
}
Output
Value of X is 30
5) SWITCH STATEMENT:
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
Flow Diagram
68
Example
Well done
Your grade is C
LOOPING STATEMENTS:
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. A loop statement allows
us to execute a statement or group of statements multiple times.
1) WHILE LOOP
2) FOR LOOP
3) DO-WHILE LOOP
1) WHILE LOOP:
Syntax
while(Boolean_expression) {
70
// Statements
}
When executing, if the boolean_expression result is true, then the actions inside the
loop will be executed. This will continue as long as the expression result is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Flow Diagram
Example
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 15 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
71
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
2) FOR LOOP:
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax
for(initialization; Boolean_expression; update) {
// Statements
}
Flow Diagram
72
Example
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
3) DO-WHILE LOOP:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.
Syntax
do {
// Statements
}while(Boolean_expression);
In do…while loop, Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.If the Boolean
expression is true, the control jumps back up to do statement, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Flow Diagram
73
Example
Output
value of x : 10
value of x : 11
value of x : 12
74
Object-oriented is a term which is interpreted differently by different person.It is
essential to have a basic knowledge of the concepts of Object oriented programming.
Some of the important object oriented features are namely:
1)Objects
2)Classes
3)Inheritance
4)Data Abstraction
5)Data Encapsulation
6)Polymorphism
7)Dynamic binding
8)Message passing
1.Objects:
Object is the basic unit of object-oriented programming. Objects are identified by
its unique name. An object represents a particular instance of a class. There can be more
than one instance of a class. Each instance of a class can hold its own relevant data.(ie)An
Object is a collection of data members and associated member functions also known as
methods.
2.Classes:
Classes are data types based on which objects are created. Objects with similar
properties and methods are grouped together to form a Class. Thus a Class represents a
set of individual objects. Characteristics of an object are represented in a class as
Properties. The actions that can be performed by objects become functions of the class
and are referred to as Methods. No memory is allocated when a class is created. Memory
is allocated only when an object is created, i.e., when an instance of a class is created.
example: Class of Cars, In this context each Car Object will have its own, Model, Year
of Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car
class and the associated actions i.e., object functions like Start, Move, and Stop form the
Methods of Car Class.
3.Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification. Inheritance
provides re usability. This means that we can add additional features to an existing class
without modifying it.
4.Data abstraction:
Data abstraction refers to, providing only needed information to the outside world
and hiding implementation details. For example, consider a class Complex with public
functions as getReal() and getImag(). We may implement the class as an array of size 2
or as two variables. The advantage of abstractions is, we can change implementation at
75
any point, users of Complex class wont’t be affected as out method interface remains
same. Had our implementation be public, we would not have been able to change it.
5.Data Encapsulation:
Wrapping up of data and functions into a single unit is known as encapsulation.
The data is not accessible to the outside world and only those functions which are
wrapping in the class can access it. This insulation of the data from direct access by the
program is called data hiding or information hiding.
6.Polymorphism:
polymorphism means ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends upon the types of
data used in the operation.polymorphism is extensively used in implementing inheritance.
7.Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is
decided at runtime.
8.Message Passing:
Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results.
Message passing involves specifying the name of the object, the name of the function and
the information to be sent.
Java permits mixing of constants and variables of different types in an expression, but
during evaluation it adheres to very strict rules of type conversion. We know that the
computer, considers one operator at a time, involving two operands. If the operands
are of different types, the ‘lower’ type is automatically converted to the ‘higher’ type
before the operation proceeds. The result is of the higher type.
If byte, short and intvariables are used in an expression, the result is always
promoted to int, to avoid overflow. If a single long is used in the expression, the
whole expression is promoted to long. Remember that all integer values are considered
to be intunless they have the 1 or L appended to them. If an expression contains a float
operand, the entire expression is promoted to float. If any operand is double, result is
double.
76
1. Float to intcauses truncation of the fractional part.
2. Double to float causes rounding of digits.
3. long to intcauses dropping of the excess higher order bits.
Casting a value:
Where type_name is one of the standard data types. The expression may be constant,
variable or an expression. Some examples of casts and their actions are shown below:
Examples Action
77
p=cost((double)x) Converts x to double before using
it as parameter.
Casting can be used to round-off a given value to an integer. Consider the following
statement:
x=(int) (y+0.5);
if y is 27.6, y+0.5 is 28.1 and on casting, the result becomes 28, the value that is
assigned to x. Of course, the expression being cast is not changed.When combining
two different types of variables in an expression, never assume the rules of automatic
conversion. It is always a good practice to explicitly force the conversion. It is more
safer. For example, when y and p aredouble and m is int, the following two
statements are equivalent. Y= p+m;
Y=p+(double)m;
Example:
class Casting
{
public static void main(String args[])
{
float sum;
int I;
sum=0.0F;
for(i=1;i<=5;i++)
{
Sum=sum+1/(float)i;
System.out.println(“i=” +i);
System.out.println(“sum=” +sum);
}
}
}
Output:
i=1 sum=1
i=2 sum=1.5
i=3 sum=1.83333
i=4 sum=2.08333
i=5 sum=2.28333
78
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.
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
79
Exception object creator
Throws
exception
object
catch Block Exception handler
Statement that handles
the exception
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
80
}
81
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.
82