Sie sind auf Seite 1von 128

A M JAIN COLLEGE SHIFT – II

DEPARTMENT OF COMPUTER APPLICATIONS


PROGRAMMING IN JAVA – SAZ4A
PREVIOUS UNIVERSITY QUESTIONS AND ANSWERS

2 MARKS

1. List down the data types in Java. (Apr-13) (Apr-14) (Apr-16)


The data types of Java are:
• Integer type
• Floating Point type
• Character type
• Boolean type

2. What are input and output streams? (Apr-12) (Apr-14) (Nov-13)


Input stream are used to read (8bit) bytes, include a super class known as
InputStream and a number of subclasses for supporting various input related
functions.
Output stream classes are used to write bytes, derived from the base class
OutputStream and a number of subclasses for performing output operations

3. Define: Thread. (Apr-12) (Apr-15) (Nov-13)


Thread is similar to a program that has a single flow of control. It has a
beginning, a body, and an end and executes commands sequentially. In fact all
main programs are examples for single threaded programs.
Threads are implemented is the form of objects that contains a method called
run ( ). The run() method is the heart and soul of any thread.

4. How to create objects? Give an example. (Apr-13) (Apr-16) (Nov-15)


To create an object we can use new keyword. This is the most common way
to create object.
Example: classname myobject=new classname();

5. What are applets? (Apr-14) (Apr-16) (Nov-12)


Applets are small Java programs that are primarily used in Internet computing.
They can be transported over the Internet from one computer to another and ran
using the Applet Viewer. It can perform arithmetic operations, display
graphics, play sounds, accept user input, create animation, and play interactive
games.

6. Define: Exception. (Apr-16) (Nov-12) (Nov-15)


An exception is a condition that is caused by a run-time error in the program.
When the java interpreter encounters an error such as dividing an integer by
zero, it creates an exception object and throws it (i.e.informs us that an error
has occurred).
7. What are constructors? (Apr-15) (Nov-12) (Nov-14)
Constructor in java is a special type of method that is used to initialize the
object. Constructors have the same name as the class name. Secondly, they do
not specify a return type, not even void. This is because they return the instance
of the class itself

8. Define objects. (Apr-12) (Apr-15)


Objects are the basic runtime entities in an object-oriented system. Objects are
the instance of a class.

9. What is an Interface? (Apr-12) (Apr-15)


An interface is a basically a kind of a class. Like classes, interfaces contain
methods and variables, but with a major difference. The difference is that
interfaces define only abstract methods and final fields. This means that
interfaces do not specify any code to implement these methods and data fields
contains only constants. Interfaces are used to support the concept of multiple
inheritance.

10. Define: Token in Java. (Apr-12) (Apr-15)


Smallest individual units in a program are known as tokens. Java language
includes five types of tokens. They are:
• Reserved keywords
• Identifiers
• Literals
• Operators
• Separators

11. What is type casting? (Apr-12) (Apr-15)


Type variable1 = (type) variable2;
The process of converting one data type to another is called casting.

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.

13. Define: Encapsulation. (Apr-13) (Apr-16)


The wrapping up of the data and methods into a single unit is known as
encapsulation.

14. Define: Method Overloading. (Apr-13) (Nov-14)


In Java, it is possible to create method that have the same name, but different
parameters list and different definition, this is called Method Overloading.
15. How do we set priorities for threads? (Apr-13) (Apr-14)
Java permits us to set the priority of a thread using the set priority ( ) method as
follows:
ThreadName.setPriority (int Number);

16. Write a note on: Import statement. (Apr-13) (Apr-14)


Using Import statements we can have access to classes that are part of other
named packages.
Example: import java.io.*;

17. What are Remote applets? (Apr-13) (Nov-15)


A remote applet is that which is develop by someone else and stored on a
remote computer connected to internet. It need the use of internet.

18. What is URL? (Apr-12) (Apr-15)


URL is an acronym for Uniform Resource Locator and is a reference (an
address) to a resource on the Internet.

19. How do we start a thread? (Apr-14) (Apr-16)


MyThread aThread = new MyThread( );
aThread.start( ); // invokes run() method
The first line instantiates a new object of class MyThread. Note that this
statement just creates the object. The thread that will run this object is not yet
running. The thread is in a newborn state. The second line calls the start( )
method causing the thread to move into the runnable state.

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; ]
}

21. What is meant by AWT? (Apr-15) (Nov-14)


The Abstract Window Toolkit (AWT) package in Java enables the
programmers to create GUI-based applications.

22. Write a note on: Java Character Set. (Apr-16) (Nov-14)


The smallest units of java language are the characters used to write java tokens.
These characters are defined by the Unicode character set, an emerging that
tries to create characters for a large number of scripts worldwide.

23. What are Datagrams? (Apr-16) (Nov-14)


Datagram is an independent, self-contained message sent over the network
whose arrival, arrival time, and content are not guaranteed.
24. What are packages? (Apr-16) (Nov-12)
Packages are collection of related classes and interfaces. It is just like header
files in C++ and it is stored in hierarchical manner. If we want to use a package
in a class we have to import it. There are two types of packages: (1) System
package and (2) User-defined package.

25. What is synchronization? (Nov-12) (Nov-15)


One thread may try to read a record from a file while another is still writing to
the same file. Depending on the situation, we may get strange results. Java
enables us to overcome this problem using a technique known as
synchronization. Synchronization controls the access of multiple threads to
shared resources.

26. Define: TCP. (Nov-12) (Nov-15)


TCP means Transmission control protocol. TCP is a network communication
protocol designed to send data packets over the internet. There may be any
number of computers that exists in the network between the client and the
server. Before transmitting data, TCP creates a connection between the source
and the destination node and keeps it alive until the communication is active.

27. Define: Variables. (Nov-13) (Nov-14)


A variable is an identifier that denotes a storage location used to store a data
value.
Example: float average;

28. Write the purpose of Exception Handling. (Apr-12)


An exception is a condition that is caused by a run time error in the program.
When the java interpreter encounters an error such as dividing an integer by
zero, it creates an exception object and throws it (i.e., informs us that an error
has occurred).

29. Write a note on: drawArc( ) method. (Nov-15)


drawArc ( ) - Draws a hollow arc.

30. What are controls? (Apr-12)


Controls are reusable components that allow a user to interact with your
application in various ways. The AWT supports the following types of
controls.
• Labels
• Push buttons
• Check boxes
• Choice lists
• Scroll bars
• Text areas
31. Write a note on: Push Button Control. (Nov-12)
Push buttons are objects of type button class. To create a button object, use one
to the following
Button( );
Button(string str);

32. What are literals? (Apr-13)


Literals 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. They are:
• Integer literals
• Floating point literals
• Character literals
• String literals
• Boolean literals

33. Give any two Most Common Run-time Errors. (Nov-15)


 Dividing an integer by zero.
 Converting invalid string to a number.
 Accessing an element that is out of the bounds of an array.

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.

35. When do we declare a method or class abstract? (Apr-13)


abstract class shape
{
……………….
……………….
abstract void draw( );
……………….
}
36. Write the names of any two common Java exceptions. (Apr-13)
 Arithmetic Exception
 IOException

37. Define: Random Access Files. (Apr-13)


RandomAccesFile class supported by java.io package allows us to create files
that can be used for reading and writing data with random access. That is we
can “Jump Around” in the files while using the file. Such files are known as
Random access files.

38. List the features of Java. (Apr-14)


 Simple
 Object oriented
 Compiled Interpreted
 Distributed
 Secure
 Portable
 High Performance

39. List the Thread States. (Nov-15)


• Newborn state
• Runnable state
• Running state
• Blocked state
• Dead state

40. Write a note on: Labels. (Apr-14)


A Label object is a component for placing text in a container. A label displays a
single line of read-only text. The text can be changed by the application but a
user cannot edit it directly.

41. What is File? (Apr-15)


A file is a collection of related records placed in a particular area on the disk.
A record is composed of several fields and a field is a group of characters.

42. Define: Inheritance. (Apr-16)


The mechanism of deriving a new class from an existing class is called
Inheritance.

43. What are character stream classes? (Apr-16)


Character stream can be used to read and write 16-bit Unicode Characters.
There are two kinds of character stream classes namely reader stream class and
writer stream case.
44. How to draw lines in Java? Give an example. (Apr-16) (Nov-14)
Within a Java applet that performs graphical operations you can draw simple
and complex graphics.
To draw a line within the applet window, you can use the Graphics class
drawLine() method.
drawLine(int startX, int startY, int endX, int endY).

45. What is meant by object-oriented programming? (Nov-12)


Object Oriented Programming is an approach that provides a way of
modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on
demand.

46. What are Variable Size Arrays? (Nov-12)


Java treats multidimensional arrays as array of arrays. In java we can create
arrays that are not rectangular. It is possible to create a two dimensional array
as having different lengths for each row. Such type of arrays are called variable
size arrays or unstructured arrays or N-dimensional arrays.

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.

48. Define: Multithreading. (Nov-12)


Multithreading is a programming technique in which a program (process) is
divided into two or more subprograms (processes) which can be implemented
at the same time in parallel. For example one subprogram can display an
animation on the screen while another subprogram may build next animation to
be displayed.
In multi-threading, there is better utilization of the CPU’s capability thus
reducing its idle time.

49. What are classes in Java? (Nov-13)


A class is a user-defined data type with a template that serves to define its
properties. Once the class type has been defined, we can create “variables” of
that type using declarations.

50. What are Java separators? (Nov-13)


Java separators are symbols used to indicate where groups of code are divided
and arranged. They basically define the shape and function of our code.
51. Define: Overriding. (Nov-13)
Overriding means an object to respond to the same method but have different
behaviour when that method is called. This is possible by defining a method in
the subclass that has the same name, same arguments and same return type as a
method in the super class. Then when that method is called, the method defined
in the subclass is invoked and executed instead of the one in the super class.
This is known as overriding.

52. What are Compile-Time Errors? (Nov-13)


All syntax errors will be detected and displayed by the Java compiler and
therefore these errors are known as compile-time errors.

53. Write a note on: Draw oval ( ) method. (Nov-13)


drawOval( ) - Draws a hollow oval.

54. What are Byte Stream Classes? (Nov-14)


Byte stream classes have been designed to provide functional features for
creating and manipulating streams and files for reading and writing bytes.
There are two kinds: (1) Input stream classes and (2) Output stream classes.

55. What are Java API packages? (Nov-14)


Java API packages are
• lang
• util
• io
• awt
• net
• applet.

56. Define Data Abstraction. (Nov-15)


Abstraction refers to the act of representing essential features without including
the background details. Classes use the concept of abstraction and are defined
as a list of abstract attributes such as size, weight and cost, and methods that
operate on these attributes.

57. Write the purpose of Exception Handling.(Nov-12).


The purpose of exception handling mechanism is to provide a means to detect
and report an “exceptional circumstances” so that appropriate action can be
taken.

58. What is constant?(apr-15)


Constants in java are fixed values those are not changed during the execution
of program. Types of constants supported by the Java language are
• Integer constants
• Floating point constants
• Character constants
• String constants
• Boolean constants

59. What is an Exception?(Nov 13)


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.

60. List the constants(literals) in java(Nov 12)


Constants in java are fixed values those are not changed during the execution of
program. Java allows different types of literals(constants). They are
1. Integer constants
2. Floating point constants
3. Boolean constants
4. Character constants
5. String constant

61. Write a note on the declaration of arrays.(Apr 12)


Array in java may be declared in two forms.
Form 1: type arrayname[ ];
Eg: int number[ ];
Form 2: type [ ] arrayname;
Eg: float [ ] marks;

62. What is the use of parseInt() method. Give example.(Apr 12)


The parseInt() method is a way of converting numeric sting to primitive
numbers. It converts string to integer.
Eg: int i= Integer.parseInt(str); //where str is string.
parseInt() method throws a NumberFormatException if the value of the str does not
represent an integer.

63. How to create objects. Give example(Apr 13)


Objects in java are created using the new operator. The new operator creates an
object of the specified class and returns a reference to that object. The general
format is:
Form1: Classname objectname;
objectname = new Classname( );
eg: Rectangle rect1;
rect1=new Rectangle();

Form 2: Classname objectname=new Classname( )


Eg:Rectangle rect1=new Rectangle( );
64. Define Method overloading(Apr 13)

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;}
}

65. What is an abstract method?(apr-13)


Methods that are declared without any body within an abstract class is known
as abstract method. The method body will be defined by its subclass. Abstract method
can never be final and static. Any class that extends an abstract class must implement
all the abstract methods declared by the super class.
Syntax :abstract returntype methodname ();

66. What is a vector? How is it different from an array(Nov 13)

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.

67. Write a short note on socket class.(Nov 13)


A socket is one endpoint of a two-way communication link between two
programs running on the network. A socket is bound to a port number so that the TCP
layer can identify the application that data is destined to be sent to.java provides two
types of sockets. They are
1.Stream socket.
2.Datagram socket.

68. How do we define a try block.(Apr 14)


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
}

69. What is meant by automatic type conversion(Apr 14)


Automatic type conversion:

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 int variables 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 int unless they have the l 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.
1. Float to intcauses truncation of the fractional part.
2. Double to float causes rounding of digits.
3. long to int causes dropping of the excess higher order bits.
70.Write a note on the syntax of exception handling code (Apr 13)

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
}

71. Write the purpose of layout manager(Apr 13)

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.

72. Write a note on instance of operator(Nov 15)


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)

73. Why is java known as platform independent language?

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.

74. Distinguish between classes and objects.

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

75. Write down the rules for naming classes.

• 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)

76. What is the use of catch block?

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.

77. Differentiate between local applet and remote applet.

Local applet Remote applet


We can develop our own applets and we can download an applet developed by
embed them into web pages. An applet someone else and embed them into web
developed locally and stored in a local pages. An applet developed by someone
system is called local applets. else and stored in a remote system is
called remote applets.
To use the local applet the system does To use the remote applet the system need
not need the internet connection. It simply the internet connection. The remote applet
searches the directories in the local is located using the applet’s address
system and locates and loads the specified known as URL(uniform resource locator)
applet stored on the remote computed and
downloads the specified applet.
78. Write down any four attributes of APPLET tag.

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

79. List the different situations in which an “ActionEvent” is generated.

The situations in which an ActionEvent is generated are


• When Button is pressed
• When a menu-item is selected
• When a list-item is double clicked

80. What is AWT?


AWT is Abstract Window Toolkit. AWT is a System package. It contains large
number of classes for implementing GUI (Graphical user interface). It includes classes
for windows, buttons, lists, menus. Scroll bars etc.

81. Find the value of 14%(-3)

For modulo division the sign of the result is always the sign of the first
operand.
Therefore,
14%(-3) = 2

82. Define the term “Array”.

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

1. Write short notes on socket programming.(Apr 12)


A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer
can identify the application that data is destined to be sent to.java provides two
types of sockets,they are
1.Stream socket.
2.Datagram socket.
1)Stream socket:
The stream communication protocol is known as TCP (transfer control protocol).
TCP is a connection-oriented protocol. We must establish a connection between the pair
of sockets. While one of the sockets listens for a connection request (ie)server, the other
asks for a connection (ie)client. Once two sockets have been connected, they can be used
to transmit data in both (or either one of the) directions.
Class Constructors:
1) Socket(String host, int port) throws UnknownHostException, IOException-
This method attempts to connect to the specified server at the specified port. If this
constructor does not throw an exception, the connection is successful and the
client is connected to the server.
2) Socket(InetAddress host, int port) throws IOException-This method is
identical to the previous constructor, except that the host is denoted by an
InetAddress object
Methods:
1) public InputStreamgetInputStream()-returns the InputStream attached with this
socket
2) public OutputStreamgetOutputStream()-returns the OutputStream attached
with this socket
3) public synchronized void close()-closes this socket.
4) public Socket accept()-returns the socket and establish a connection between
server and client

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);
} }}

2.Write about working with graphics with eg:( Nov 12)


Refer 10 marks Qn.No: 7

3.Write a program to find the factorial, N! (Apr 12)


FACTORIAL

import java.io.*;

class fact

public static void main(String args[])throws IOException

try

BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the number: ");

int n=Integer.parseInt(br.readLine());

int fact;

System.out.println("factorial of "+n+" : ");

for(inti=1i<=n;i++)

fact=fact*i;

System.out.println(fact);

}}

3
catch(Exception e){}

}}

4.Explain color class in java?(nov-13)

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.Write short notes on commonly used String buffer methods(Apr 13)


StringBuffer class is apeer class of String. While String creates strings of fixed
length, String buffer class creates strings of variable length that can be modified in
terms of both length and content. We can insert characters and strings in the
middle of the string or append another string at the end.
Commonly used StringBuffer Methods:
Method task

S1.setCharAt(n,’x’) Modifies the nth character to x

S1.append(S2) Append the string S2 to S1 at the end

S1.insert(n,S2) Inserts the string S2 at the position n of


the string S1

5
S1.setLength(n) Sets the length of the string S1 to n.

Example Program:

PALINDROME CHECKING

import java.io.*;

classpalind

public static void main(String args[])throws IOException

BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the sting: ");

String str=br.readLine();

StringBuffersb=new StringBuffer(str).reverse();

String strrev=sb.toString();

if(str.equalsIgnoreCase(strrev))

System.out.println("the given string "+str+" is a palindrome");

else

System.out.println("the given string "+str+" is not a palindrome");

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;

int a[ ]=new int[100];


System.out.println("Enter the number of elements");
BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
System.out.println("Enter the elements");
for(inti=1;i<=n;i++)
a[i]=Integer.parseInt(br.readLine());
for(inti=1;i<=n;i++)
if((a[i]%2)==0)
ecount++;
else
ocount++;
System.out.println("The count of even numbers:" +ecount);
System.out.println("The count of odd numbers:" +ocount);
}}

8.What are the important vector methods?Discuss briefly. (Nov 14)


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.

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.

9.What is URL? Discuss URL class usage in java(Nov 16)

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.

public String getHost() it returns the host name of the URL.


public String getPort() it returns the Port Number 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

10.Give a brief account on InetAddress class(nov-15)

Java InetAddress class represents an IP address. The java.net.InetAddress class


provides methods to get the IP of any host name for example:www.college.com,
www.google.com, www.facebook.com etc.
Commonly used methods of InetAddress class
Method
Public static It returns the instance of
InetAddressgetByName(String host throws InetAddressconatiningLocalHost IP and
UnknownHostException name.

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

11.Write short note on TCP/IP (Apr 16)

TCP stands for Transmission Control Protocol,IP stands for Internet


Protocol ,which allows for reliable communication between two applications. TCP
is typically used over the Internet Protocol, which is referred to as TCP/IP.
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.
10
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.
File Name or directory name: In this case, index1.jsp is the file name. The
java.net.URL class provides many methods.

12. Discuss the three ways of drawing polygons in Java.


Polygons are shapes with many sides. A polygon may be considered a set of lines
connected together.The end of the first line is the beginning of the second line, the end of
the second is the beginning of the third. The first method is to draw a polygon with n
sides using the drawLine() method, n times in succession.

Example method 1:

Public void paint(Graphics g)


{
g.drawstring(10,20,170,40);
g.drawstring(170,40,80,140);
g.drawstring(80,140,10,20);
}

The second method is to draw polygons more conveniently using the drawPolygon()
method of Graphics class. This method takes three arguments:

• An array of integers containing x coordinates


• An array of integers containing y coordinates
• An integer for the total number of points

Example Method 2:

Public void paint(Graphics g)


{
IntxPoint[ ]={10,170,80,10};
IntyPoint[ ]={20,40,140,20};
IntnPoint[ ]=xPoints.length;
g.drawPolygon(xPoints,yPoints,nPoints);

The third method to draw polygon is to use the polygon object.

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:

Public void paint(Graphics g)


{
IntxPoint[ ]={10,170,80,10};
IntyPoint[ ]={20,40,140,20};
Int n =x.length;
Polygon poly =new Polygon(x,y,n);
g.drawPolygon(poly);
}

13. Write short notes on Font class in Java.


The font class states the fonts, which are used to render text in a visible
way.
Constructors:

Constructors Description

Protected font() Creates a new font from the specified


type
Font(String name,int style, int size) Creates a new font of specified font
Methods:

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

14.Write Short note on Random Access File(Nov 15)


Random Access File enable us to read and write bytes,text and java data types to
any location in a file . RandomAccessFile class supported by Java.io pacakage which
allows us to create files that can be use for reading and writing data with random access.

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

• “r” for reading only


• “rw” for both for reading and writing

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

public static void main(String args[])

RandomAccessFile file=null;

13
try

file=new RandomAccessFile ("rand.dat ","rw");

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);

}}}

15. Explain different visibility controls in java?(apr-13)


Visibility Controls are used to defined where a method and Data Member of class
will be used either inside a class ,outside a class ,in inherited class or in main Method. It
tells us about the Scope of Methods where they would be used . Various types of Access
Modifiers are as follows:-
1.Default
2.Public
3.Protected
4.Private

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.

16)Describe Method Overriding in Java?(nov-14)


A method is overridden when a subclass contains a method in the same name,
return type and parameters (i.e.) the method which are declared static in the super class
cannot be overridden by the super class.
Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.

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 ,

1.Call the constructor of the super class.


2.Call the method of the subclass

1.Call the constructor of the super class :


A sub class can call a constructor method defined by its super class by using
the keyword called super. Syntax : super (parameters);

2.Call the methods of the sub class :


A class can access a hidden member variable through its super class. A
member can be either a method (or) instance of variable. Syntax :super.member ;

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.Give a brief account on Method Overloading?(apr-16,apr-14,apr-15)


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.
Rules for overloading:

1. Overloading can appear in the same class or a subclass


2. Overloaded methods MUST change its number of argument or its type.
When declaring two or more methods in same name complier differentiate them
by its arguments, so you cannot declare two methods with the same signature
3. Overloaded methods CAN have different return type.
The compiler does not consider return type when differentiating methods, so it?s
legal to change return type of overloaded method
4.Similarly overloaded method can have different access modifiers also.
The advantages of method overloading is that it provides an easy way to handle
default parameter values. Assume that a method has one required parameter and two
optional arguments. Three overloaded forms of this method can be defined. These steps
are two or three parameters.

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.Describe any five methods in the string class?(apr-12)


The java.lang.String class provides a lot of methods to work on string with the
help of these methods, we can perform operations on string such as trimming,
concatenating, converting, comparing, replacing strings.
1.charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output:u

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

19)write the general syntax of a class and describe with an example?(nov-13) OR


How to define a class and ad methods to it.(Nov 12)
A class is a group of objects that has common properties .It is a template from which
objects are created. A class in java contain;

 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. Explain various types of inheritance in java?(apr-16)


Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. It is used to manage the hierarchical order.The class
which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).
extendsKeyword:Extends is the keyword used to inherit the properties of a class.
syntax:
classSuper
{
statements;
}
classSubextendsSuper
{
statements;
}

The types of inheritance which is supported by Java.


1.Single Inheritance
2.Multiple Inheritance (Through Interface)
3.Multilevel Inheritance

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

22.Write about Synchronization in Java with example. (Apr-13)


One thread may try to read a record from a file while another is still writing to the
same file. Depending on the situation, we may try to read a record from a file while
another is still writing to the same file. Depending on the situation, we may get strange
results. Java enables us to overcome this problem using a technique known as
synchronization.

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 ( )
{
………………….
…………………
}
}

23.Discuss about Thread Priority with examples. (Apr-16) (Nov-12) (Nov-13)

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.

Most user-level processes should use NORM_PRIORITY, plus or minus 1. Back-


ground tasks such as network I/O and screen repainting should use a value very near to
the lower limit. We should be very cautious when trying to use very high priority
values. This may defeat the very purpose of using multithreads.

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:

1. It stops running at the end of run().


2. It is made to sleep using sleep().
3. It is told to wait using wait().

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:

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()
{

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

24.Discuss briefly on stopping and blocking threads. (Apr-12)

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

Memory CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream

File FileReader FileWriter FileInputStream FIleOutputStream

Pipe PipedReader PipedWriter PipedInputStream PipedOutputStream

29
26.Write about Java Statements. (Apr-13)

The statements in Java are like sentences in natural language. A statement is an


executable combination of tokens ending with a semicolon (;) mark. Statements are
usually executed in sequence in the order in which they appear. However, it is
possible to control the flow of execution, if necessary, using special statements. Java
implements several types of statements. They are considered in depth as and when
they are encountered.
Java Statements

Expression Guarding
Statement Labelled Synchronization Statement
Statement Statement

Control
Statement

Selection Iteration Jump


Statements Statements Statement

while for

30
if break return
switch do
if-else continue

27.Explain the use of abstract keyword?


Abstract Keyword:
1. To declare abstract methods
2. To declare abstract classes

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

1. Give a brief account on wrapper classes in java?(nov-14,apr-14)

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:

Data type Wrapper class


boolean Boolean
int Integer
float Float
double Double
long Long
char Character
byte Byte
short Short

The wrapper classes have number of unique method for handling primitive data
types and object.

1.Converting primitive numbers to object number using construct method :


Integer Intval = new Integer (i) ; -primitive integer to Integer object.
Float Floatval = new Float (f) ; -primitive float to Float object.
Double Doubleval = new Double (d) ; -primitive double to double object.
Long Longval = new Long (l) ;

2.Conversion of numbers string to primitive method :


Int I = Intval .intVal( ) ; -convert object to primitive Integer
Float f = Floatval .floatVal( ) ; -convert object to primitive float
Double d = Doubleval .doubleVal ( ) ; -convert object to primitive double
Long l = Longval .longVal ( ) ; -convert object to primitive long

3.Conversion number to string using string ( ) method :


Str = Integer .toString (i) ; -convert primitive integers to string

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

4.Converting string object to numeric object using static method value of ( )


Double val = Double .value of (str) ; -converts string to double object
Intval = Integer .value of (str) ;
Float val = Float .value of (str) ;
Long val = Long .value of (str) ;

5.Converting numeric string to primitive numeric using parse Int method ( ) :


Int I = Integer .parseInt(str) ; -converting string to primitive Integer
Long I = Long .parseLong(str) ; -converting string to long

2. Describe the usage of byte stream class with example(Nov 12)

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.

2
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.

3
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.

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.

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.

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.

Hierarchy of reader stream classes


Some important Character 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

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.

1) Border Layout Manager: The BorderLayout is used to arrange the components in


five regions: north, south, east, west and center. Each region (area) may contain one
component only. It is the default layout of frame or window. The BorderLayout provides
five constants for each region:
1) public static final int NORTH
2) public static final int SOUTH
3) public static final int EAST
4) public static final int WEST
5) public static final int CENTER
Class Constructors:
1) BorderLayout(): creates a border layout but with no gaps between the
components.
2) BorderLayout(inthgap, intvgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Method:
1) voidaddLayoutComponent(Component comp, Object constraints)-Adds the
specified component to the layout, using the specified constraint object.
2) voidaddLayoutComponent(String name, Component comp)-If the layout
manager uses a per-component string, adds the component comp to the layout,
associating it with the string specified by name.
3) intgetHgap()-Returns the horizontal gap between components.
4) intgetVgap()-Returns the vertical gap between components.
5)StringtoString()-Returns a string representation of the state of this border layout.
Example:
importjava.applet.*;
importjava.awt.*;
public class BorderButtons extends Applet
{
public void init()
{
setLayout(new BorderLayout(20, 10));
Button b1= new Button (“North”);

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:

2)Flow Layout Manager:TheFlowLayout is used to arrange the components in a line,


one after another.It is the default layout of applet or panel.
Fields:
1) public static final int LEFT
2) public static final int RIGHT
3) public static final int CENTER
4) public static final int LEADING
5) public static final int TRAILING
Class Constructors:
1) FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2) FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3) FlowLayout(int align, inthgap, intvgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

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:

3)Grid Layout Manager: The GridLayout is used to arrange the components in


rectangular grid. One component is displayed in each rectangle.It automatically arranges
components in a grid.
Class Constructors:
1) GridLayout(): creates a grid layout with one column per component in a row.
2) GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
3) GridLayout(int rows, int columns, inthgap, intvgap): creates a grid layout with
the given rows and columns alongwith given horizontal and vertical gaps.

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)

The hierarchy of Java AWT classes and methods are,


1.Container:
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known as
container such as Frame, Dialog and Panel.

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:

6. Explain how exception handling mechanism can be used for debugging a


program(Apr 14)

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

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.

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)uncheckedexceptions:These exceptions are not essentially handled in the


program code;instead the JVM handles such excceptions.unchecckedeceptions 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.

13
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
{

14
//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
remaningstatementswill 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 ownexception.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:
importjava.lang.Excception;
classmyException extends Exception
{
MyException(String message)
{
super(messgae);
}
}
classTestMyException
{

public static void main(String args[])


{

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.

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.*;

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);
}
}

8.Describe the various AWT controls in java?(nov-14,Apr-15)

The various AWT controls in java are,


1. Label
2. Button
3. Check Boxes
4. List
5. Scroll Bar
6. Choice
7. Text Area

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:

1. staticint CENTER -- Indicates that the label should be centered.


2. staticint LEFT -- Indicates that the label should be left justified.
3. staticint RIGHT -- Indicates that the label should be right justified.

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.

2 Button(String text)-Constructs a new button with specified 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.

6.Choicecontrol:Itis used to show pop up menu of choices. Selected choice is shown on


the top of the menu.
Class declaration:The declaration for java.awt.Choice class
public class Choice extends Component implements ItemSelectable, Accessible

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.

7.TextArea:ATextArea object is a text component that allows for the editing of a


multiple lines of text.The scroll bar is automatically appears which help us to scroll the
text up & down and right & left.
Class declaration:The declaration for java.awt.TextArea class:
public class TextArea extends TextComponent
Field:The fields for java.awt.TextArea class:
1. staticint SCROLLBARS_BOTH -- Create and display both vertical and
horizontal scrollbars.
2. staticint SCROLLBARS_HORIZONTAL_ONLY -- Create and display
horizontal scrollbar only.
21
3. staticint SCROLLBARS_NONE -- Do not create or display any scrollbars for
the text area.
4. staticint SCROLLBARS_VERTICAL_ONLY -- Create and display vertical
scrollbar only.
Class constructors:
S.No Constructor & Description
1 TextArea()-Constructs a new text area with the empty string as text.
2 TextArea(int rows, int columns)-Constructs a new text area with the specified
number of rows and columns and the empty string as text.
3 TextArea(String text)-Constructs a new text area with the specified text.
4 TextArea(String text, int rows, int columns)-Constructs a new text area with
the specified text, and with the specified number of rows and columns.
5 TextArea(String text, int rows, int columns, int scrollbars)-Constructs a new
text area with the specified text, and with the rows, columns, and scroll bar
visibility as specified.

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

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( )
{

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

10.Discuss multiple inheritance with example(Apr 16)

Multiple inheritance in java is implemented using interface.

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;

return type method name 1 (parameter list);


.......................................................................;
.......................................................................;
return type method name n (parameter list);
}

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
{
...
}

// multiple inheritance like


class ClassName 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

11.Write a program to illustrate multithreaded programming.(Apr 13)

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

12. Describe working with frames with example(Nov 16,Nov 13)

The class hierarchy for panel and frame as follows,

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]);
}
}

output:Enter the names:


orange
apple
sorted order
apple
orange

15)Explain life cycle of a thread?(apr-12,nov-15,apr-15,apr-16)


A thread moves through several states from its creation to its termination. The life
cycle of a thread consists of five shows. The following figure shorts the five states of a
thread life cycle.
1)New born state
2)Runnable state
3)Running state
4)Blocked state
5)Dead state

38
New thread New born Stop()

Start()

Active thread Running Runnable


Dead
st( stop() Yield ()

Suspend() Resume()

Sleep() Notify()

Wait () Stop()

Idle thread (not runnable) Blocked

1)New born thread :


We create a thread object a thread is born and said to be new born state. At this
stage a thread is not scheduled for running state. It can perform only one state.
(i) Scheduled it for running (i.e.) using start ( ) method
(ii) Kill it, by using stop ( ) method.
New born state when we create an object of the class thread.
New born

Start Stop

Runnable Dead state


method

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

Running Runnable Suspended

We can put a thread in a specified time period using the method sleep ( ) method where
time is in millisecond.

Sleep (t)

After (t)

Running Runnable Suspended

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

Running Runnable Suspended

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.

16)How packages are created in java? Explain?(nov-13)


Packages contain a set of classes in order to ensure that class names are unique.
Packages are containers for classes that are used to compartmentalize the class name
space.
Creating a package :
To create an user defined package it includes a package command as the first statement
in java source file. We can assign the classes and interfaces in a source file to a particular
package by using a package. Syntax : package packagename ;
Importing a package :
We can import a specific class or the whole package. We can place import statements at
the beginning of your java source file.
Syntax :import packagename . * ;
some of the java packages are;
 java.lang  — basic language functionality and fundamental types
 java.util  — collection data structure classes
 java.io  — file operations
 java.math  — multiprecisionarithmetics
Creating our own package :
1)Declare the package at the top of the java source file.
Package packagename ;
2)Declare the class as public
Package class classname ;
3)Create as directory and name the same name as the package .
4)The file should be named with the same name as their public class followed by the
extension as .Java
5)Compile the source file which creates the .class file in the directory .

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

17) What is an interface? Discuss the various forms of implementing interface in


java?(apr-13)
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.
Syntax :
Interface name
{
data type varname 1 = value 1;
...................................................;
...................................................;
data type varname n = value n;
return type method name 1 (parameter list);
.......................................................................;
.......................................................................;
return type method name n (parameter list);
}
Example :
Interface x
{
int a=7 , b=8 , n=9 ;

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;
}

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

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

18)Explain the two ways of creating threads in java?(apr-14)


Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class.

1. By implementing the Runnable interface


To create a thread is to create a class that implements the runnable interface. After
implementing runnable interface, the class needs to implement the run() method, syntax:
public void run()
1)Declare the class as implementing the Runnable interface.
2)Implement run() method.
3)Create a thread by defining an object that is instantiated from this runnable class as
the traget of the thread.
4)Call the thread start() method to run the thread.

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..

Extending Thread class:


The another way to create a thread by a new class that extends Thread class and
create an instance of that class.
Declare the class as extending the Thread class
Implement the run() method that is responsible forr executing tha sequence of code that
the thread will execute.
Create a thread object and call start() method to initiate the thread execution.

Declaring of class: class MyThread extends Thread


{
.......................................
........................................
}

Example:

classMyThread extends Thread


{
public void run()
{
System.out.println("Concurrent thread started running..");
}
}

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

public static void main(String args[])

File inFile=new File("input.dat");

File outFile=new File("output.dat");

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)

20.Write a Java program to find all possible roots of a Quadratic equation

import java.io.*;

classquadeqn

public static void main(String args[]) throws IOException

double root1=0.0,root2=0.0,d;

48
BufferedReaderbr= new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the values of a,b,c: ");

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)

System.out.println("the roots are real and unequal");

root1=(-b+Math.sqrt(d))/(2*a);

root2=(-b-Math.sqrt(d))/(2*a);

System.out.println("the first root is :"+root1);

System.out.println("the second root is :"+root2);

else if(d==0)

System.out.println("the roots are real and equal");

root1=(-b+Math.sqrt(d))/(2*a);

System.out.println("the roots are :"+root1);

else

System.out.println("the roots are imaginery");

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

public static void main(String args[])

int count=0,ocount=0, n;

for(inti=100;i<=200;i++)

{if((i%7)==0)

count++;

ocount+=i;

System.out.println("the number of elements divisible by 7 is :"+count);

System.out.println("the sum is: "+ocount);

22. Explain the various types of tokens in java?(nov-13,nov14,apr-16)


Tokens are the Smallest individual units in a java program. Java has five types of
tokens . They are ,
1) Keywords
2) Identifiers
3) Literals
4) Operators

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.

Abstract boolean break byte


Byvalue case cast catch
Char class Const continue
default do double else
extends final Float for
future generic goto if
implements import inner instanceof
Int interface long native
New null operator outer
package private protected public
Rest return short static
super switch synchronized this
throw throws transient try
Var void volatile while

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,

Valid identifiers Invalid identifiers


A2 While (this is a java keyword)
SUM .9D(uses a period operator)
Sum roll no (uses a space)
C18 94(does not begin with a letter)
balance_amount 3ABC. (begin with a numeral)

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.

Hexadecimal:-Hexadecimal numbers (base 16) appear with a leading 0x or 0X.For


example, an integer literal for the decimal number 12 is represented in java as 0xC in
hexadecimal.

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.

2)Floating point literals :


Floating point literals represented decimal numbers with fractional parts such as
3.142. They can be expressed in either standard or scientific notation, meaning that the
number 563.84 also can be expressed as 5.6384e2.

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.

23.Discuss briefly on Data Types in Java with examples. (Apr-12) (Apr-15)

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

bytes short int long


Type Size Minimum value Maximum value

byte One byte -128 127

short Two bytes -32,768 32,767

int Four bytes -2, 147, 483, 648 2,147,483, 647

long Eight bytes -9,223, 372, 036, 9, 223, 372, 036,


854,775,808 854, 775, 807

Floating point types:

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.

24.Describe the features of Java. (Apr-15) (Nov-12) (Nov-14)


I. Simple: Java was designed to be easy for professional programmers to learn, if he
already knows C &C++. Java includes syntaxes from C and object oriented
concepts from C++. The confusing concepts in both C & C++ are leftover here. So
java is easy to learn and it is simple language.

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.

VII. Multithreaded: It means handling multiple tasks simultaneously. Java supports


multithreaded programs. This means that we need not wait for the application to
finish one task before another. For eg, we can listen to an audio clip while scrolling
a page and at the same time download an applet from a distant computer. This
feature greatly improves the interactive performance of graphical applications.

VIII. Architectural Neutral: One of the problems facing by programmers was


program written today will not be run tomorrow even in the same machine or if the
OS or if the processor upgrades. So java designers made it architectural neutral by
implementing JVM (Java Virtual Machine) through java runtime environment. The
main role of java designers to make it architecture neutral write once, run anywhere,
anytime forever.

IX. Compiled & Interpreted: Usually a computer language is either compiled or


interpreted. Java combines both these approaches thus making java a two stage
system. First java compiler translates source code into what is known as byte code.
Byte codes are not machine instructions and therefore, in second stage java
interpreter generates machine code that can be directly executed by the machine that
is running the java program. So we can say that java is both compiled and
interpreted language.

X. High Performance: Java performance is impressive for an interpreted language,


mainly due to the use of intermediate byte code. Java architecture is also designed
to reduce overheads during runtime. Further, the incorporation of multithreading
enhances the overall execution speed of java programs.

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:

Sr.No Operator and Example


1 + ( Addition )-----Adds values on either side of the operator
Example: A + B will give 30
2 - ( Subtraction )----Subtracts right hand operand from left hand operand
Example: A - B will give -10
3 * ( Multiplication )-----Multiplies values on either side of the operator
Example: A * B will give 200
4 / (Division)-------Divides left hand operand by right hand operand
Example: B / A will give 2
5 % (Modulus)----Divides left hand operand by right hand operand and returns
remainder
Example: B % A will give 0
6 ++ (Increment)
Increases the value of operand by 1
Example: B++ gives 21
7 -- ( Decrement )
Decreases the value of operand by 1
Example: B-- gives 19

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:

Sr.No Operator and Description


1 == (equal to)-----Checks if the values of two operands are equal or not, if yes
then condition becomes true.
Example: (A == B) is not true.
2 != (not equal to)------Checks if the values of two operands are equal or not, if
values are not equal then condition becomes true.
Example: (A != B) is true.
3 > (greater than)--------Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes true.
Example: (A > B) is not true.
4 < (less than)--------Checks if the value of left operand is less than the value of
right operand, if yes then condition becomes true.
Example: (A < B) is true.
5 >= (greater than or equal to)------Checks if the value of left operand is greater
than or equal to the value of right operand, if yes then condition becomes true.
Example (A >= B) is not true.

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:

Sr.No Operator and Description


1 & (bitwise and)-----Binary AND Operator copies a bit to the result if it exists
in both operands.
Example: (A & B) will give 12 which is 0000 1100
2 | (bitwise or)-----Binary OR Operator copies a bit if it exists in either
operand.
Example: (A | B) will give 61 which is 0011 1101
3 ^ (bitwise XOR)-----Binary XOR Operator copies the bit if it is set in one
operand but not both.
Example: (A ^ B) will give 49 which is 0011 0001
4 ~ (bitwise compliment)-----Binary Ones Complement Operator is unary and
has the effect of 'flipping' bits.
Example: (~A ) will give -61 which is 1100 0011 in 2's complement form
due to a signed binary number.
5 << (left shift)-----Binary Left Shift Operator. The left operands value is
moved left by the number of bits specified by the right operand
Example: A << 2 will give 240 which is 1111 0000
6 >> (right shift)-----Binary Right Shift Operator. The left operands value is
moved right by the number of bits specified by the right operand.
Example: A >> 2 will give 15 which is 1111

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

Sr.No Operator and Description


1 = Simple assignment operator, Assigns values from right side operands to left
side operand.
Example: C = A + B will assign value of A + B into C
2 += Add AND assignment operator, It adds right operand to the left operand
and assign the result to left operand.
Example: C += A is equivalent to C = C + A
3 -= Subtract AND assignment operator, It subtracts right operand from the left
operand and assign the result to left operand.
Example:C -= A is equivalent to C = C - A
4 *= Multiply AND assignment operator, It multiplies right operand with the
left operand and assign the result to left operand.
Example: C *= A is equivalent to C = C * A

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.

Category Operator Associativity


Postfix () [] . (dot operator) Left toright
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >>>>><< Left to right
Relational >>= <<= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

26.Explain control statements in Java with suitable examples (Nov-13)(Apr-12)

BRANCHING STATEMENTS / DECISION MAKING STATEMENTS:

Decision making structures have one or more conditions to be evaluated or tested by


the program, along with a statement or statements that are to be executed if the
condition is determined to be true, and optionally, other statements to be executed if
the condition is determined to be false.

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:

An if statement consists of a Boolean expression followed by one or more statements.

Syntax :

if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}

Flow Diagram

64
Example

public class Test {

public static void main(String args[]) {


int x = 10;

if( x < 20 ) {
System.out.print("This is if statement");
}
}
}

Output

This is if statement.

2) IF ELSE STATEMENT:

An if statement can be followed by an optional else statement, which executes when


the Boolean expression is false.

Syntax

if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}

65
Flow Diagram

Example

public class Test {


public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}

Output

This is else statement

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:

An if statement can be followed by an optional else if...else statement, which is very


useful to test various conditions using single if...else if statement.

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

// You can have any number of case statements.


default : // Optional
// Statements
}

Flow Diagram

68
Example

public class Test {


public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
69
Output

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.

Java programming language provides following types of looping statements.

1) WHILE LOOP
2) FOR LOOP
3) DO-WHILE LOOP

1) WHILE LOOP:

A while loop statement in Java programming language repeatedly executes a target


statement as long as a given condition is true.

Syntax

while(Boolean_expression) {

70
// Statements
}

Here, statement(s) may be a single statement or a block of statements. The condition


may be any expression, and true is any non zero value.

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

public class Test {


public static void main(String args[]) {
for(int x = 10; x < 14; x = x + 1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

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

public class Test {


public static void main(String args[]) {
int x = 10;
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 13 );
}
}

Output

value of x : 10
value of x : 11
value of x : 12

27. Explain the basic concepts of OOP?(apr-14,apr-16(nov-14 -5 marks))

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.

28.Discuss briefly on Type Casting with example.(Nov-12) (Nov-13) (Nov-14)


(Nov-15)

Automatic type conversion:

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:

We have already discussed how java performs type conversion automatically.


However, there are instances when we want to force a type conversion in a way that is
different from the automatic conversion. Consider, for example, the calculation of
ration of females to males in a town.
Ratio = female_number/male_number
Since female_number and male_numberare declared as integers in the program, the
decimal part of the result of the division would be lost and ratio would not represent a
correct figure. This problem can be solved by converting locally one of the variables to
the floating oint as shown below:
Ratio = (float) female_number/male_number
The operator (float) converts the female_numberto floating point for the purpose of
evaluation of the expression. Then using the rule of automatic conversion, the division
is performed in floating point mode, thus retaining the fractional part of result.
The process of such a local conversion is known as casting a value.

The general form of a cast is: (type_name) expression

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

X=(int) 7.5 7.5 is converted to integer by


truncation

a=(int)21.3/(int)4.5 Evaluated as 21/4 and the result


would be 5

b=(double) sum/n Division is done in floating point


mode.

y=(int) (a+b) The result of a+b is converted to


integer.

z=(int) a+b A is converted to integer and then


added to b.

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

29. What is an exception? How exceptions are handled in java? Explain.(apr-13,nov-


15)OR
Write about the keywords used in exception handling.

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.

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)uncheckedexceptions:These exceptions are not essentially handled in the program


code;instead the JVM handles such excceptions.unchecckedeceptions 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
79
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

80
}

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
remaningstatementswill 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 ownexception.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:
importjava.lang.Excception;
classmyException extends Exception
{
MyException(String message)
{
super(messgae);
}
}
classTestMyException
{
public static void main(String args[])
{
int x=2,y=100;
try
{
float z= (float) x/(float)y;

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

Das könnte Ihnen auch gefallen