Você está na página 1de 177

MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION

(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 1/ 27

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the
model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try
to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give credit for any
equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the candidates answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based
on candidates understanding.
7) For programming language papers, credit may be given to any other program based on equivalent
concept.

Q.1.

a) Attempt any three of following:


a) Explain :
1) Platform independence
2) Compiled and interpreted features of Java.
( 2 M each feature)

1) Platform independent

Java programs are platform independent and portable. That is they can be easily
moved from one computer system to another. Changes in operating systems,
processors, system resources will not force any change in java programs. Java
compilers generate byte code instructions that can be implemented on any machine as
well as the size of primitive data type is machine independent. In this sense, Java
programs are platform independent.

2) Compiled & interpreted features of Java

Java is a two staged system. It combines both approaches. First java compiler
translates source code into byte code instructions. In the second stage java interpreter
generates machine code that can be directly executed by machine. Thus java is both
compiled and interpreted language.

b) Explain serialization in relation with stream class.


(4 M Explanation, example not expected)
Serialization in java is a mechanism of writing the state of an object into a byte
stream.
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 2/ 27

After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its
data can be used to recreate the object in memory.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types such as writeObject() method. This method serializes an Object and sends it to
the output stream. Similarly, the ObjectInputStream class contains method for
deserializing an object as readObject(). This method retrieves the next Object out of
the stream and deserializes it. The return value is Object, so you will need to cast it to
its appropriate data type.
For a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient.

c) Write any four mathematical functions used in Java.


(1 M each methods syntax and use)
Note: Any four methods can be considered.

1) min() :
Syntax: static int min(int a, int b)
Use: This method returns the smaller of two int values.
2) max() :
Syntax: static int max(int a, int b)
Use: This method returns the greater of two int values.
3) sqrt()
Syntax: static double sqrt(double a)
Use : This method returns the correctly rounded positive square root of a double
value.
4) pow() :
Syntax: static double pow(double a, double b)
Use : This method returns the value of the first argument raised to the power of the
second argument.
5) exp()
Syntax: static double exp(double a)
Use : This method returns Euler's number e raised to the power of a double value.
6) round() :
Syntax: static int round(float a)
Use : This method returns the closest int to the argument.
7) abs()
Syntax: static int abs(int a)
Use : This method returns the absolute value of an int value.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 3/ 27

d) Explain following methods related to threads:


1) suspend()
2) resume()
3) yield()
4) wait()
( 1 M each methods syntax and use)
1) suspend() -
syntax : public void suspend()
This method puts a thread in suspended state and can be resumed using resume()
method.
2) resume()
syntax : public void resume()
This method resumes a thread which was suspended using suspend() method.
3) yield()
syntax : public static void yield()
The yield() method causes the currently executing thread object to temporarily pause
and allow other threads to execute.
4) wait()
syntax : public final void wait()
This method causes the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object.

b) Attempt any one of following:


a) What is difference between array and vectors? Explain any 2 methods of vector
with example.

(4M- for any 4 points of differences, 1M each - for any 2 methods of Vector class)
Array Vector
Array can accommodate fixed Vectors can accommodate unknown
number of elements number of elements
Arrays can hold primitive data
Vectors can hold only objects.
type & objects
All elements of array should be of
the same data type. i.e. it can The objects in a vector need not have
contain only homogeneous to be homogeneous.
elements.
Syntax :
Syntax:
Datatype[] arraname= new
Vector objectname= new Vector();
datatype[size];
For accessing elements of an
Vector class provides different
array no special methods are
methods for accessing and managing
available as it is not a class , but
Vector elements.
derived type.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 4/ 27

Note : Any other methods of Vector class can also be considered.

Vector class methods :


1 ) void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size by one.
2) int capacity()
Returns the current capacity of this vector.
3) void clear()
Removes all of the elements from this Vector.
4) boolean contains(Object elem)
Tests if the specified object is a component in this vector.
5) void copyInto(Object[] anArray)
Copies the components of this vector into the specified array.
6) Object elementAt(int index)
Returns the component at the specified index.
7) boolean equals(Object o)
Compares the specified Object with this Vector for equality.
8) int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality using the equals
method.
9) void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified index.
10) boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
11) void removeElementAt(int index)
removeElementAt(int index)
12) int size()
Returns the number of components in this vector.

b) What is constructor? Demonstrate the use of parameterized constructor with suitable


example.
( 1M What is constructor, 2M features and example of constructor,
1M parameterized constructor ,2M example)
A constructor is a special method which initializes an object immediately upon creation.
It has the same name as class name in which it resides and it is syntactically similar to any
method.
When a constructor is not defined, java executes a default constructor which initializes all
numeric members to zero and other types to null or spaces.
Once defined, constructor is automatically called immediately after the object is created
before new operator completes.
Constructors do not have return value, but they dont require void as implicit data type as
data type of class constructor is the class type itself.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 5/ 27

Eg :
class Rect
{
int length, breadth;
Rect() //constructor
{
length=4;
breadth=5;
}
public static void main(String args[])
{
Rect r = new Rect();
System.out.println(Area : +(r.length*r.breadth));
}
}
Output :
Area : 20

Parameterized constructor :
When constructor method is defined with parameters inside it, different value sets can be
provided to different constructor with the same name.

Example
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
System.out.println(Area : +(r.length*r.breadth));
System.out.println(Area : +(r1.length*r1.breadth));
}
}
Output :
Area : 20
Area : 42
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 6/ 27

Q.2. Attempt any two of following:


a) Explain abstract class with suitable example.
( 4M- explanation, 4M example)
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Abstraction is a process of hiding the implementation details and showing only functionality
to the user. Another way, it shows only important things to the user and hides the internal
details.
A method must be always redefined in a subclass of an abstract class, as abstract class does
not contain method body. Thus abstract makes overriding compulsory.
Class containing abstract method must be declared as abstract.
You can not declare abstract constructor, and so, objects of abstract class cannot be
instantiated.
Syntax :
abstract class < classname>
{
.
.
abstract method1();
method2(.);
.
.}

Example :
abstract class A
{
abstract void disp();
void show()
{
System.out.println(show method is not abstract);
}
}

class B extends A
{
void disp()
{
System.out.println(inside class B);
}
}

class test
{
public static void main(String args[])
{
B b = new B();
b.disp();
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 7/ 27

b.show();
}
}

Output : show method is not abstract inside class B

b) What is interface? How it is different from class? With suitable program explain the use
of interface.
(2M what is interface, 3M 3 points of differences between interface and class, 3M
example)
Interface:
Java does not support multiple inheritances with only classes. Java provides an alternate
approach known as interface to support concept of multiple inheritance.
An interface is similar to class which can define only abstract methods and final variables.
Difference between Interface and class
Class Interface
A Class is a full body entity with members, An Interface is just a set of definition that you
methods along with their definition and must implement in your Class inheriting that
implementation. Interface
A Class has both definition and an Interface has only definition. That is, it
implementation of a method contains only abstract methods.
A Class can be instantiated. An Interface cannot be instantiated
A sub class can be extended from super You can create an instance of an Object of a
class with extends. class that implements the Interface with
implements

Example:
interface sports
{
int sport_wt=5;
public void disp();
}

class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 8/ 27

result (int r, String nm, int m11,int m12)


{
super (r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
{
result r= new result(101,"abc",75,75);
r.disp();
}
}

Output :
D:\>java result
Roll no : 101
Name : abc
sub1 : 75
sub2 : 75
sport_wt : 5
total : 155

c) Design an applet which displays three circle one below the other and fill them red, green
and yellow color respectively.( 3M- correct logic, 2M correct use of class, packages and
<applet> tag , 3M correct syntaxes)
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g) Output :
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);

g.setColor(Color.green);
g.fillOval(50,150,100,100);

g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}}
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 9/ 27

/*<applet code=myapplet width= 300 height=300>


</applet>*/
Q.3. Attempt any four of following:
a) Explain use of following methods:
1) indexOf()
2) charAt()
3) substring()
4) replace()
(1 mark each for each method use with parameters and return type.)
(Any one syntax of each method should be considered)

1. indexOf():
int indexOf(int ch): Returns the index within this string of the first occurrence of the
specified character.
int indexOf(int ch, int fromIndex): Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
int indexOf(String str): Returns the index within this string of the first occurrence of the
specified substring.
int indexOf(String str, int fromIndex): Returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
2. charAt():
char charAt(int index): Returns the char value at the specified index.
3. substring():
String substring(int beginIndex): Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex): Returns a new string that is a substring of
this string. The substring begins at the specified beginIndex and extends to the character
at index endIndex - 1
4. replace():
String replace(char oldChar, char newChar): Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.

b) Write a program to find sum of digits of number.


(A program in which the student has assumed the number or has accepted the number
in any other way may also be considered.)
(1 mark for syntax and 3 marks for logic.)

import java.io.*;
class SumOfDigits
{
public static void main(String args[])
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n;
try
{
System.out.println("Enter the number");
n = Integer.parseInt(b.readLine());
int sum = 0, n1;
while (n > 0)
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 10/ 27

{
n1 = n%10;
n = n/10;
sum = sum+n1;
}
System.out.println("The sum of the digits of the number is :"+sum);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Or
class SumOfDigits
{
public static void main(String args[])
{
int n = 1234; //Student may have assumed any other number
int sum = 0, n1;
while (n > 0)
{
n1 = n%10;
n = n/10;
sum = sum+n1;
}
System.out.println("The sum of the digits of the number is :"+sum);
}
}

c) What is use of stream classes? Write any two methods FileReader class.

(2 marks for use of stream class, 2 marks for any two methods of FilReader class.)

An I/O Stream represents an input source or an output destination.


A stream can represent many different kinds of sources and destinations,
including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.
Some streams simply pass on data; others manipulate and transform the data in
useful ways. Javas stream based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, Writer.
They are used to create several concrete stream subclasses, the top level classes
define the basic functionality common to all stream classes.
InputStream and OutputStream are designed for byte streams and used to work
with bytes or other binary objects.
Reader and Writer are designed for character streams and used to work with
character or string.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 11/ 27

1. public int read()throws IOException - Reads a single character.


2. public int read(char[] cbuf, int offset, int length) throws IOException - Reads characters into
a portion of an array.
3. public void close()throws IOException - Closes the stream and releases any system resources
associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or
skip() invocations will throw an IOException. Closing a previously closed stream has no
effect
4. public boolean ready()throws IOException - Tells whether this stream is ready to be read. An
InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read
from the underlying byte stream
5. public void mark(int readAheadLimit) throws IOException -Marks the present position in the
stream. Subsequent calls to reset() will attempt to reposition the stream to this point. Not all
character-input streams support the mark() operation.
6. public void reset()throws IOException - Resets the stream. If the stream has been marked,
then attempt to reposition it at the mark. If the stream has not been marked, then attempt to
reset it in some way appropriate to the particular stream, for example by repositioning it to its
starting point. Not all character-input streams support the reset() operation, and some support
reset() without supporting mark().

d) Describe applet life cycle with suitable diagram.

(1 mark for diagram 3 marks for explanation)

Applets are small applications that are accessed on an Internet server, transported over
the Internet, automatically installed, and run as part of a web document. The applet states
include:
Born or initialization state
Running state
Idle state
Dead or destroyed state

Initialization state: Applet enters the initialization state when it is first loaded. This is done
by calling the init() method of Applet class. At this stage the following can be done:
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colors
Initialization happens only once in the life time of an applet.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 12/ 27

public void init()


{
//implementation
}
Running state: applet enters the running state when the system calls the start() method of
Applet class. This occurs automatically after the applet is initialized. start() can also be called
if the applet is already in idle state. start() may be called more than once. start() method may
be overridden to create a thread to control the applet.
public void start()
{
//implementation
}
Idle or stopped state: an applet becomes idle when it is stopped from running. Stopping
occurs automatically when the user leaves the page containing the currently running applet.
stop() method may be overridden to terminate the thread used to run the applet.
public void stop()
{
//implementation
}
Dead state: an applet is dead when it is removed from memory. This occurs automatically by
invoking the destroy method when we quit the browser. Destroying stage occurs only once in
the lifetime of an applet. destroy() method may be overridden to clean up resources like
threads.
public void destroy()
{
//implementation
}
Display state: applet is in the display state when it has to perform some output operations on
the screen. This happens after the applet enters the running state. paint() method is called for
this. If anything is to be displayed the paint() method is to be overridden.
public void paint(Graphics g)
{
//implementation
}

e) What is final variable and methods? How it is different from abstract method?
(1 mark for explanation of final variable, 1 mark for explanation of final method. 2
marks for difference)
All variable and methods can be overridden by default in subclass. In order to prevent
this, the final modifier is used.
Final modifier can be used with variable, method or class.

final variable: the value of a final variable cannot be changed. final variable behaves like
class variables and they do not take any space on individual objects of the class.
Eg of declaring final variable: final int size = 100;

final method: making a method final ensures that the functionality defined in this method
will never be altered in any way, ie a final method cannot be overridden.
Eg of declaring a final method: final void findAverage() {
//implementation
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 13/ 27

abstract is a modifier used with methods and classes.


An abstract method is a method that is declared without an implementation.
The implementation is to be done in the subclass making overriding compulsory.
It is opposite of final modifier.
If a class includes abstract methods, then the class itself must be declared abstract.
When an abstract class is subclassed, the subclass usually provides implementations
for all of the abstract methods in its parent class. However, if it does not, then the
subclass must also be declared abstract.

Eg: abstract class Shape


{
int variable1, variable2;
void method1
{
//implementation
}
abstract void method2();
}

Q.4.
a) Attempt any three of following:
a. What do mean by typecasting? When it is needed?
(Explanation of type casting with types 2 marks, need 1 mark, 1 mark for
program or code snippet)
The process of converting one data type to another is called casting or type casting. If
the two types are compatible, then java will perform the conversion automatically. It
is possible to assign an int value to long variable. However if the two types of
variables are not compatible, the type conversions are not implicitly allowed, hence
the need for type casting.
Eg: int m = 50;
byte n = (byte) m;
long count = (long) m;
Type casting is of two types: narrowing, widening.
The process of assigning a smaller type to a larger one is known as widening and the
process of assigning a larger type into a smaller one is called narrowing.
Casting is necessary when a value of one type is to be assigned to a different type of
variable. It may also be needed when a method returns a type different than the one
we require. Generic type casting helps in the retrieval of elements from a collection as
each element in a collection is considered to be an object.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 14/ 27

b. Describe life cycle of thread.

(1 mark for diagram, 3 marks for explanation)

A thread can be in one of the following states


1. New born state
2. Ready to run state
3. Running state
4. Blocked state
5. Dead state
New Born state
The thread enters the new born state as soon as it is created. The thread is created
using the new operator.
From the new born state the thread can go to ready to run mode or dead state.
If start( ) method is called then the thread goes to ready to run mode. If the stop( )
method is called then the thread goes to dead state.
Ready to run mode (Runnable State)
If the thread is ready for execution but waiting for the CPU the thread is said to be in
ready to run mode.
All the events that are waiting for the processor are queued up in the ready to run
mode and are served in FIFO manner or priority scheduling.
From this state the thread can go to running state if the processor is available using the
scheduled( ) method.
From the running mode the thread can again join the queue of runnable threads.
The process of allotting time for the threads is called time slicing.
Running state
If the thread is in execution then it is said to be in running state.
The thread can finish its work and end normally.
The thread can also be forced to give up the control when one of the following
conditions arise
1. A thread can be suspended by suspend( ) method. A suspended thread can be revived
by using the resume() method.
2. A thread can be made to sleep for a particular time by using the sleep(milliseconds)
method. The sleeping method re-enters runnable state when the time elapses.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 15/ 27

3. A thread can be made to wait until a particular event occur using the wait() method,
which can be run again using the notify( ) method.
Blocked state
A thread is said to be in blocked state if it is prevented from entering into the runnable
state and so the running state.
The thread enters the blocked state when it is suspended, made to sleep or wait.
A blocked thread can enter into runnable state at any time and can resume execution.
Dead State
The running thread ends its life when it has completed executing the run() method
which is called natural dead.
The thread can also be killed at any stage by using the stop( ) method.

c. Write a program to generate Fibonacci series:1 1 2 3 5 8 13 21 34 55 89.


(Any other logic for generating the Fibonacci series may also be considered)
(Syntax 1 mark, logic 3 marks)

class FibonocciSeries
{
public static void main(String args[])
{
int num1 = 1; int num2 = 1;
System.out.println(num1);
while (num2< 100)
{
System.out.println(num2);
num2 = num1+num2;
num1 = num2-num1;
}
}

d. Write syntax and function of following methods of data class:


1. Sethme () // The method name has to be setTime()
2. getDay()

(2 marks for syntax and use of each method)


1. setTime():
void setTime(long time): the parameter time - the number of milliseconds.
Sets this Date object to represent a point in time that is time milliseconds after
January 1, 1970 00:00:00 GMT
2.getDay()
int getDay():Returns the day of the week represented by this date. The returned value
(0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6
= Saturday) represents the day of the week that contains or begins with the instant in
time represented by this Date object, as interpreted in the local time zone.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 16/ 27

b) Attempt any one of the following:


a. Write the syntax and example for each of following graphics methods:
1. drawPoly ()
2. drawReact ()
3. drawOval ()
4. fillOval()

(1 mark each for each method example with syntax, 2 marks for program.
Students may write different program for each method or may include all
methods in one program.)

(Any one syntax and use of the method may be considered)

1. void drawPolygon(int[] xPoints, int[] yPoints, int nPoints): Draws a closed


polygon defined by arrays of x and y coordinates. The number of points defined by x
and y is specified by numpoints.
2. void drawRect(int top, int left, int width, int height): Draws a rectangle with upper
left corner of the rectangle is top, left. Dimensions of the rectangle are specified by
width and height.
3. void drawOval(int top, int left, int width, int height): Draws an oval within a
bounding rectangle whose upper left corner is specified by top, left. Width and height
of the oval are specified by width and height.
4. void fillOval(int top, int left, int width, int height): Draws an oval within a
bounding rectangle whose upper left corner is specified by top, left. Width and height
of the oval are specified by width and height.

Eg.
import java.applet.*;
import java.awt.*;
/*
<applet code = DrawGraphics.class height = 500 width = 400></applet>
*/
public class DrawGraphics extends Applet
{
public void paint(Graphics g)
{
int x[] = {10, 170, 80};
int y[] = {20, 40, 140};
int n = 3;
g.drawPolygon(x, y, n);
g.drawRect(10, 150,100, 80);
g.drawOval(10, 250, 100, 80);
g.fillOval(10, 350, 100, 80);
}
}
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 17/ 27

b. What is garbage collection and finalize method in Java?


(3 marks for garbage collection, 3 marks for finalization )
Garbage collection - The objects are dynamically allocated in java by the use of the
new operator. The objects which are no longer in use are to be destroyed and the
memory should be released for later reallocation. Java, unlike C++, handles
deallocation of memory automatically. This technique is called garbage collection.
When no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed. Garbage collection occurs
sporadically during the execution of programs. It will not occur just because one or
more objects exist that are no longer used. Different run-time implementations will
take varying approaches to garbage collection.
finalize() method: -sometimes an object will need to perform some action when it is
destroyed. Eg. If an object holding some non java resources such as file handle or
window character font, then before the object is garbage collected these resources
should be freed. To handle such situations java provide a mechanism called
finalization. In finalization, specific actions that are to be done when an object is
garbage collected can be defined. To add finalizer to a class define the finalize()
method. The java run-time calls this method whenever it is about to recycle an object.
Inside the finalize() method, the actions that are to be performed before an object is to
be destroyed, can be defined. Before an object is freed, the java run-time calls the
finalize() method on the object. The general form of the finalize() method is:

protected void finalize()


{
//finalization code
}

Q.5. Attempt any Two of following:


a) Write a program to create two threads; one to print numbers in original order and
other to reverse order from 1 to 50.
( 4-marks for Logic, 4-marks for correct Syntax)
(Any other program with correct logic may also be considered)

class original extends Thread


{
public void run()
{
try
{
for(int i=1; i<=50;i++)
{
System.out.println("\t First Thread="+i);
Thread.sleep(300);
}
}
catch(Exception e)
{}
}
}
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 18/ 27

class reverse extends Thread


{
public void run()
{
try
{
for(int i=50; i>=1;i--)
{
System.out.println("\t Second Thread="+i);
Thread.sleep(300);
}
}
catch(Exception e)
{}
}
}
class orgrev
{
public static void main(String args[])
{
new original().start();
new reverse().start();
System.out.println("Exit from Main");
}
}

b) What are different types of error? What is use of throw, throws and finally Statement?
[Type of Errors & explanation 2-marks, throw, throws & finally 2-mark each]
Errors are broadly classified into two categories:-
1. Compile time errors
2. Runtime errors
Compile time errors: All syntax errors will be detected and displayed by java
compiler and therefore these errors are known as compile time errors.
The most of common problems are:
Missing semicolon
Missing (or mismatch of) bracket in classes & methods
Misspelling of identifiers & keywords
Missing double quotes in string
Use of undeclared variables.
Bad references to objects.
Runtime errors: Sometimes a program may compile successfully creating the .class
file but may not run properly. Such programs may produce wrong results due to wrong
logic or may terminate due to errors such as stack overflow. When such errors are
encountered java typically generates an error message and aborts the program.
The most common run-time errors are:
Dividing an integer by zero
Accessing an element that is out of bounds of an array
Trying to store value into an array of an incompatible class or type
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 19/ 27

Passing parameter that is not in a valid range or value for method


Trying to illegally change status of thread
Attempting to use a negative size for an array
Converting invalid string to a number
Accessing character that is out of bound of a string

throw: If your program needs to throw an exception explicitly, it can be done using throw
statement. General form of throw statement is:
throw new Throwable subclass;
throw statement is mainly used in case there is user defined exception raised. Throwable
instance must be an object of the type Throwable or a subclass of Throwable.
The flow of exception stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception. If it does find a match, control is
transferred to that statement. If not matching catch is found, then the default exception
handler halts the program and prints the built in error message.
throws: If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that exception.
You do this by including a throws clause in the methods declaration. A throws clause
lists the types of exception that a method might throw.
General form of method declaration that includes throws clause
Type method-name (parameter list) throws exception list
{
// body of method
}
Here exception list can be separated by a comma.
finally: It can be used to handle an exception which is not caught by any of the
previous catch statements.
finally block can be used to handle any statement generated by try block. It may be added
immediately after try or after last catch block.
Syntax
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 20/ 27

c) State the use of Font class. Write syntax to create an object of Font class. Describe any
3 methods of Font class with their syntax and example of each.

[Font class 3-Marks, Syntax 2-Marks & Methods 3-Marks]


Font class: A font determines look of the text when it is painted. Font is used while painting text on a
graphics context & is a property of AWT component.
The Font class defines these variables:
Variable Meaning

String name Name of the font

float pointSize Size of the font in points

int size Size of the font in point

int style Font style

Syntax to create an object of Font class: To select a new font, you must first construct a Font object
that describes that font.
Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)

fontName specifies the name of the desired font. The name can be specified using either the logical or
face name. All Java environments will support the following fonts: Dialog, DialogInput, Sans Serif,
Serif, Monospaced, and Symbol. Dialog is the font used by once systems dialog boxes. Dialog is also
the default if you dont explicitly set a font. You can also use any other fonts supported by particular
environment, but be carefulthese other fonts may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR them together. For example,
Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.

To use a font that you have created, you must select it using setFont( ), which is defined by
Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font

Methods of Font class

1. String getFamily(): Returns the family name of this Font.


2. int getStyle():Returns the style of this Font
3. int getSize() : Returns the size of this Font
4. boolean is bold(): Returns true if the font includes the bold style value. Else returns false
5. String toString(): Returns the string equivalent of the invoking font.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 21/ 27

Example Using Methods of Font class:


Program-1:
A program to make use of Font class methods. Which will display string Java Programming Is
Language if font object style is BOLD else it will display string Java Programming Is Language
with another string saying String is not bold

import java.applet.*;
import java.awt.*;
/*<applet code="FontD" width=350 height=60> </applet> */
public class FontD extends Applet {
Font f, f1;
String s="";
String msg="";
public void init()
{
f=new Font("Dialog", Font.BOLD,30);
s="Java Programming";
setFont(f);
msg="Is Language";
int a=f.getSize();
String b=f.getFontName();
int d=f.getStyle();
System.out.println("String Information: Size"+a);
System.out.println("Name:"+b);
System.out.println("Style:"+d);
}
public void paint(Graphics g) {
if(f.isBold()==true)
g.drawString(s,50,50);
else
g.drawString("String is not bold",400,400);
g.drawString(s,50,50);
g.drawString(msg,100,100);}}
Output:
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 22/ 27

Program-2:
A program to make use of Font class methods. To displays the name, family, size, and style of the
currently selected font:
import java.applet.*;
import java.awt.*;
/*<applet code="FontInfo" width=350 height=60> </applet>*/
public class FontInfo extends Applet {
public void paint(Graphics g) {
Font f = g.getFont();
String fontName = f.getName();
String fontFamily = f.getFamily();
int fontSize = f.getSize();
int fontStyle = f.getStyle();
String msg = "Family: " + fontName;
msg += ", Font: " + fontFamily;
msg += ", Size: " + fontSize + ", Style: ";
if((fontStyle & Font.BOLD) == Font.BOLD)
msg += "Bold ";
if((fontStyle & Font.ITALIC) == Font.ITALIC)
msg += "Italic ";
if((fontStyle & Font.PLAIN) == Font.PLAIN)
msg += "Plain ";
g.drawString(msg, 4, 16);}}
Output:

Q.6. Attempt any four of following:


a)

Interface: Gross Class:Employee


ta,da,gross_sal() Name,basic_sal

Class:Salary
Disp_sal(),hra

[2-marks for Logic, 2-marks for correct Syntax]


interface Gross
{
double ta=500.0;
double da=1200.0;
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 23/ 27

void gross_sal();
}
class Employee
{
String name;
float basic_sal;
Employee(String n, float b)
{
name=n;
basic_sal=b;
}
void display()
{
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+basic_sal);
}
}
class salary extends Employee implements Gross
{
float hra;
salary(String n, float b, float h)
{
super(n,b);
hra=h;
}
void disp()
{
display();
System.out.println("HRA of Employee="+hra);
}
public void gross_sal()
{
double gross_sal=basic_sal+ta+hra;
System.out.println("TA of Employee="+ta);
System.out.println("DA of Employee="+da);
System.out.println("Gross Salary of Employee="+gross_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
salary s=new salary("ABC",6000,4000);
s.disp();
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 24/ 27

s.gross_sal();
}
}

b) What is use of setclass? Write a program using setclass.


( any other suitable example may also be considered.)
[2-marks for Set class, 2-marks for Program]
Note: Assuming Set interface in place of set class. Answer is as follows:
The Set interface defines a set. It extends Collection and declares the behavior of a collection
that does not allow duplicate elements. Therefore, the add( ) method returns false if an
attempt is made to add duplicate elements to a set.
The Set interface contains only methods inherited from Collection and adds the restriction
that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations,
allowing Set instances to be compared meaningfully even if their implementation types
differ.
The methods declared by Set are summarized in the following table:
SN Methods with Description

add()
1
Adds an object to the collection

clear()
2
Removes all objects from the collection

contains()
3
Returns true if a specified object is an element within the collection

isEmpty()
4
Returns true if the collection has no elements

iterator()
5 Returns an Iterator object for the collection which may be used to retrieve
an object

remove()
6
Removes a specified object from the collection

size()
7
Returns the number of elements in the collection
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 25/ 27

There are three general-purpose Set implementations HashSet, TreeSet,


and LinkedHashSet. Which of these three to use is generally straight forward. HashSet is
much faster than TreeSet(constant-time versus log-time for most operations) but offers no
ordering guarantees. If you need to use the operations in the SortedSet interface, or if value-
ordered iteration is required, use TreeSet; otherwise, use HashSet. It's a fair bet that you'll end
up using HashSet most of the time.
LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as
a hash table with a linked list running through it, it provides insertion-ordered iteration (least
recently inserted to most recently) and runs nearly as fast as HashSet.
The LinkedHashSet implementation spares its clients from the unspecified, generally chaotic
ordering provided by HashSet without incurring the increased cost associated with TreeSet.
Set have its implementation in various classes like HashSet, TreeSet, LinkedHashSet.
Following is the example to explain Set functionality:
import java.util.*;
public class SetDemo
{
public static void main(String args[])
{
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e){}
}}
Executing the program.
[34, 22, 10, 30, 60]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 26/ 27

c) Differentiate between applet and application (any 4 points).


Ans: [4-marks for 4 Points]
Applet Application

Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries from Application are not restricted from using
other language such as C or C++ libraries from other language

d) What is package? How do we create it?

[Package: 3-marks Creating Packages 5-marks]


Package: Packages are used for grouping a variety of classes & interfaces together. This
grouping is done according to functionality. Packages acts as containers of classes. Packages
are stored in hierarchical manner & are explicitly imported into new class definitions.
Following benefits are achieved by organizing classes into packages:
1. The classes contained in the packages of other programs can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is two
classes in two different packages can have same name. They may be referred by their fully
qualified name, comprising package name & class name.
3. Packages provide way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
4. Packages also provide a way for separating design from coding. First we can design
classes & decide their relationship & then we can implement Java code needed for methods.
It is possible to change implementation of any method without affecting rest of the design.
Java packages are therefore classified into two types. First category is known as Java API
packages & second is known as User defined packages.

Creating Packages: First declare name of package using package keyword followed by
package name. This must be first statement in a java source file. Here is an example:
package firstPackage; //package declaration

public class FirstClass //class definition


{
..
.. (body of class)
..
}
Here the package name is firstPackage. The class FirstClass is now considered a part of this
package. This listing would be saved as file called FirstClass.java & located in a director
named firstPackage. When source file is complied, Java will create a .class file & store it in
same directory.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 27/ 27

.class must be located in a directory that has same name as the package, & this directory
should be a subdirectory of the directory where classes that will import package are located.
Creating package involves following steps:
1. Declare the package at beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package & declare it public
3. Create a subdirectory under directory where main source files are stored
4. Store listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory
Case is significant & therefore subdirectory name must match package name exactly. Java
supports the concept of package hierarchy. This is done by specifying multiple names in a
package statement, separated by dots. Example: package firstPackage.secondPackage;
This approach allows us to group related classes into a package & then group related
packages into larger package. To store this package in subdirectory named
firstPackage/secondPackage.
A java package file can have more than one class definition. in such cases only one of the
classes may be declared public & that class name with .java extension is the source file name.
When a source file with more than one class definition is complied, java creates independent
.class files for these classes.

e) Write a program to print reverse of a number.


[ 2-marks for Logic, 2-marks for correct Syntax]
(Any other program with correct logic may also be considered)
class Reverse1
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]); //take argument as command line
int remainder, result=0;
while(num>0)
{
remainder = num%10;
result = result * 10 + remainder;
num = num/10;
}
System.out.println("Reverse number is : "+result);
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 1/ 27

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the
model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try
to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in
the figure. The figures drawn by candidate and model answer may vary. The examiner may
give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed
constant values may vary and there may be some difference in the candidates answers and
model answer.
6) In case of some questions credit may be given by judgement on part of examiner of
relevant answer based on candidates understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.

Q.1.

A. Attempt any THREE of the following: 12

a) What is JVM? What is byte code?


(JVM- 3 M, bytecode- 1 M)
JVM is the Java Virtual Machine
The java compiler compiles produces an intermediate code known as byte
code for the java virtual machine, which exists only in the computer
memory
It is a simulated computer within the computer and does all the major
functions of a real computer

Java Program Java Compiler Virtual Machine

Byte Code
Source code
process of compilation

Virtual machine code is not machine specific


Machine specific code is generated by Java Interpreter by acting as an
intermediary between the virtual machine and the real machine.
Interpreter is written for each type of machine.

Byte Code Java Interpreter Machine Code

Virtual machine real machine

Process of converting byte code into machine code


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 2/ 27

Byte code: Bytecode is the compiled format for Java programs. Once a
Java program has been converted to bytecode, it can be transferred across a
network and executed by Java Virtual Machine (JVM). A Bytecode file
generally has a .class extension.

b) Write any two methods of file and file input stream class each.

File class Methods:


(Any 2 methods can be considered) (2 M)
1. public String getName()
Returns the name of the file or directory denoted by this abstract pathname.
2. public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if
this pathname does not name a parent directory.
3. public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if
this pathname does not name a parent directory.
4. public String getPath()
Converts this abstract pathname into a pathname string.
5. public boolean isAbsolute()
Tests whether this abstract pathname is absolute. Returns true if this
abstract pathname is absolute, false otherwise
6. public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
7. public boolean canRead()
Tests whether the application can read the file denoted by this abstract
pathname. Returns true if and only if the file specified by this abstract
pathname exists and can be read by the application; false otherwise.
8. public boolean canWrite()
Tests whether the application can modify to the file denoted by this
abstract pathname. Returns true if and only if the file system actually
contains a file denoted by this abstract pathname and the application is
allowed to write to the file; false otherwise.
9. public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists.
Returns true if and only if the file or directory denoted by this abstract
pathname exists; false otherwise
10. public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
Returns true if and only if the file denoted by this abstract pathname exists
and is a directory; false otherwise.
11. public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A
file is normal if it is not a directory and, in addition, satisfies other system-
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 3/ 27

dependent criteria. Any non-directory file created by a Java application is


guaranteed to be a normal file. Returns true if and only if the file denoted
by this abstract pathname exists and is a normal file; false otherwise.
12. public long lastModified()
Returns the time that the file denoted by this abstract pathname was last
modified. Returns a long value representing the time the file was last
modified, measured in milliseconds since the epoch (00:00:00 GMT,
January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
13. public long length()
Returns the length of the file denoted by this abstract pathname. The return
value is unspecified if this pathname denotes a directory.

FileInputStream class methods :


(Any 2 methods can be considered) (2 M)
1) int available() Returns an estimate of the number of remaining bytes that
can be read (or skipped over) from this input stream without blocking by
the next invocation of a method for this input stream.
2) void close() Closes this file input stream and releases any system resources
associated with the stream.
3) int read() Reads a byte of data from this input stream.
4) int read(byte[] b) Reads up to b.length bytes of data from this input stream
into an array of bytes.
5) read(byte[] b, int off, int len) Reads up to len bytes of data from this input
stream into an array of bytes.

c) ? what this operator is called? Explain with suitable example.


(Name of the operator 1M, Explanation and example 3 M)

1) ?: is called as conditional operator or ternary operator.


2) It can be used to check condition in one line, instead of writing
ifelse statement.
3) Its format is (condtion ? true case : false case)
4) example
int a,b;
a=10;
b=(a>5? 12 : 20);
Here b= 12 as a is 10 and condition is true. If value of a is changed to 15
then b will have value as 20.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 4/ 27

d) Define an exception. How it is handled?

(Definition 1 M, explanation with all keywords 3 M)


Exception: An exception is an event, which occurs during the execution of
a program, that stop the flow of the program's instructions and takes
appropriate actions if handled.
Java handles exceptions with 5 keywords:
1) try 2) catch 3) finally 4) Throw 5) throws
1) try: This block applies a monitor on the statements written inside it. If
there exist any exception, the control is transferred to catch or finally
block.
2) catch: This block includes the actions to be taken if a particular exception
occurs.
3) finally: finally block includes the statements which are to be executed in
any case, in case the exception is raised or not.
4) throw: This keyword is generally used in case of user defined exception, to
forcefully raise the exception and take the required action.
5) throws: throws keyword can be used along with the method definition to
name the list of exceptions which are likely to happen during the execution
of that method. In that case , try catch block is not necessary in the code.

B. Attempt any one of the following: 6

a) Define a class employee with data members empid, name and salary.
Accept data for five objects using Array of objects and print it.

(Class declaration-1 M, Accept data- 1 M, Array of object- 1 M, Display


data- 1 M) import java.io.*;
class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new
InputStreamReader(System.in));
System.out.print("Enter Emp number : ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine();
System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 5/ 27

}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(Name : " + name);
System.out.println(Salary : " + salary);
}
}

classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[5];
for(inti=0; i<5; i++)
{
e[i] = new employee();
e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<5; i++)
e[i].show();
}
}
(Note: Any relevant logic can be considered)

b) Explain with example how to achieve multiple inheritance with


interface.

(Multiple inheritance 2 M, interface 2 M, example 2M)

Multiple inheritances: It is a type of inheritance where a derived class may


have more than one parent class. It is not possible in case of java as you
cannot have two classes at the parent level
Instead there can be one class and one interface at parent level to achieve
multiple interface.
Interface is similar to classes but can contain on final variables and abstract
method. Interfaces can be implemented to a derived class.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 6/ 27

Example :
Interface: Sports Class: test

sport_wt=5 Rollno,Name, m1,m2

disp( )

Code :
interface sports
{ Class: result
int sport_wt=5;
public void disp(); disp() which displays all
} details of student along with
total including sport_wt.
class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
result(int r, String nm, int m11,int m12)
{
super(r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 7/ 27

{
result r= new result(101,"abc",75,75);
r.disp();
}
}

Q.2. Attempt any Two of the following: 16


a) Define wrapper class. Give the following wrapper class methods with
syntax and use:
1) To convert integer number to string.
2) To convert numeric string to integer number.
3) To convert object numbers to primitive numbers using typevalue()
method.

(Wrapper class 2 M, each method syntax and use 2 M each)

Wrapper Class:
Objects like vector cannot handle primitive data types like int, float, long
char and double. Wrapper classes are used to convert primitive data types
into object types. Wrapper classes are contained in the java.lang package.
The some of the wrapper classes are:
Simple type Wrapper class
boolean Boolean
int Integer
char Character
float Float

1) To convert integer number to string : Method is toString()


String str = Integer.toString(i) converts the integer i to string value.
2) To convert numeric string to integer number: Method is parseInt()
int i = Integer.parseInt(str) converts the string value of numeric string str
to int i.
3) To convert object number to primitive number using typevalue()
method
The method here is typeValue(), meaning that type can be the data
type of the number. For example : if x is an Integer object with value 10,
then it can be stored as primitive int y with the method intValue() as
Integer x = new Integer(10);
int y = x.intValue();
Similarly, it can be done with other numeric types as floatValue(),
doubleValue() etc.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 8/ 27

b) Write syntax and example of


1) drawstring ()
2) drawRect ();
3) drawOval ()
4) drawArc ()

(Each methods syntax 1 Mark, each methods example 1 Mark)

1) drawstring( )
Displaying String:
drawString() method is used to display the string in an applet window
Syntax:
voiddrawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example:
g.drawString(WELCOME, 10, 10);

2) drawRect( )
Drawing Rectangle:
The drawRect() method display an outlined rectangle. The general forms
of this method is :
void drawRect(inttop,intlept,intwidth,int height)
The upper-left corner of the Rectangle is at top and left. The dimension of
the Rectangle is specified by width and height.
Example:
g.drawRect(10,10,60,50);

3) drawOval( )
Drawing Ellipses and circles:
To draw an Ellipses or circles used drawOval() method can be used. The
general form of this method is:
Syntax:
voiddrawOval(int top, int left, int width, int height)
the ellipse is drawn within a bounding rectangle whose upper-left corner is
specified by top and left and whose width and height are specified by width
and height to draw a circle or filled circle, specify the same width and
height the following program draws several ellipses and circle.
Example:
g.drawOval(10,10,50,50);

4) drawArc( )
Drawing Arc:
It is used to draw arc
Syntax:
voiddrawArc(int x, int y, int w, int h, intstart_angle, intsweep_angle);
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 9/ 27

wherex, y starting point, w& h are width and height of arc, and
start_angle is starting angle of arc
sweep_angle is degree around the arc
Example:
g.drawArc(10, 10, 30, 40, 40, 90);

c) What is package? State any four system packages along with their use?
How to add class to a user defined packages?

(package 2 M, Four packages and their use 1 M each, how to add class
to package 2 M)

Package: Java provides a mechanism for partitioning the class namespace into
more manageable parts. This mechanism is the package. The package is both
naming and visibility controlled mechanism.

System packages with their use:(Any 4 can be considered)


1. java.lang - language support classes. These are classes that java compiler
itself uses and therefore they are automatically imported. They include classes
for primitive types, strings, math functions, threads and exceptions.
2. java.util language utility classes such as vectors, hash tables, random
numbers, date etc.
3. java.io input/output support classes. They provide facilities for the input
and output of data
4. java.awt set of classes for implementing graphical user interface. They
include classes for windows, buttons, lists, menus and so on.
5. java.net classes for networking. They include classes for communicating
with local computers as well as with internet servers.
6. java.applet classes for creating and implementing applets.

To add a class to user defined package :


1) Include a package command as the first statement in a Java source file.
2) Any classes declared within that file will belong to the specified package.
3) The package statement defines a name space in which classes are stored.
4) Example :
package MyPack;
public class Balance
{
.
.
.
}
Then class Balance in included inside a user defined package MyPack.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 10/ 27

Q.3. Attempt any FOUR: 16

a) Differentiate vector and array with any 4 points.


(4M- for any 4 points of differences)
Array Vector
Array can accommodate fixed number Vectors can accommodate unknown
of elements number of elements
Arrays can hold primitive data type &
Vectors can hold only objects.
objects
All elements of array should be of the
The objects in a vector need not have to be
same data type. i.e. it can contain only
homogeneous.
homogeneous elements.
Syntax :
Syntax:
Datatype[] arraname= new
Vector objectname= new Vector();
datatype[size];
For accessing elements of an array no Vector class provides different methods
special methods are available as it is for accessing and managing
not a class , but derived type. Vector elements.

b) Write a program to accept a number as command line argument and


print the number is even or odd.
(Any other program with correct program may also be considered)
(Logic 2-M, Syntax 2-marks)

public class oe
{
public static void main(String key[])
{
int x=Integer.parseInt(key[0]);
if (x%2 ==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 11/ 27

c) Write a program to copy contents of one file to another file using


character stream class.

(Any other program with correct logic may also be considered)


(Logic 2-M, Syntax 2-M)
import java.io.*;
class filetest
{
String n=" ";
int rollno=0;
File f1;
File f2;
FileReader in=null;
FileWriter out=null;
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
void getdata(String s)
{
String ch="y";
try
{
f1=new File(s);
out= new FileWriter(f1);
while(ch.compareTo("y")==0)
{
System.out.println("Enter name");
n=b.readLine();
System.out.println("Enter number:");
rollno=Integer.parseInt(b.readLine());
out.write(Integer.toString(rollno));
out.write(" ");
out.write(n);
System.out.println("More records :");
ch=b.readLine();
if (ch.compareTo("y")==0)
out.write('\n');
}
out.write('\n');
out.close();
}
catch (IOException e){ System.out.println(e);}
}
void wordcount(String s)
{
int r=0,count=0,c=0;
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 12/ 27

try
{
f1= new File(s);
in= new FileReader(f1);
while(r!=-1)
{
r=in.read();
if(r=='\n')
c++;
if (r==' ' || r=='\n')
{
count++;
}
System.out.println("No. of words:"+count);
System.out.println("No. of lines:"+c);
in.close();
}
catch(IOException e){System.out.println(e);}
}
void display(String s)
{
int r =0;
try
{
f1= new File(s);
in = new FileReader(f1);
while(r!=-1)
{
r=in.read();
System.out.print((char)r);
}
in.close();
}
catch(IOException e){ System.out.println(e); }
}
void filecopy(String s)
{
int r =0;
try
{
f1= new File(s);
f2=new File("output.txt");
in = new FileReader(f1);
out= new FileWriter(f2);
while(r!=-1)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 13/ 27

{
r=in.read();
out.write((char)r);
}
System.out.println("File copied to output.txt...");
in.close();
out.close();
}
catch(IOException e){System.out.println(e);}
}
public static void main(String[] args)
{
filetest f= new filetest();
String filename= args[0];
f.getdata(filename);
f.filecopy(filename);
f.display(filename);
f.wordcount(filename);
}
}

d) State the use of final keyword w. r. t. a method and the variable with
suitable example.

All variable and methods can be overridden by default in subclass. In order to


prevent this, the final modifier is used.
Final modifier can be used with variable, method or class.

final variable: the value of a final variable cannot be changed. final variable
behaves like class variables and they do not take any space on individual
objects of the class.
Eg of declaring final variable: final int size = 100;

final method: making a method final ensures that the functionality defined in
this method will never be altered in any way, ie a final method cannot be
overridden.
Eg of declaring a final method:
final void findAverage()
{
//implementation
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 14/ 27

e) Describe following states of applet life cycle:

a. Initialization state.
b. Running state.
c. Display state.

(Initialization State 1M, Running state 1M, Display state 2M)


Initialization state: Applet enters the initialization state when it is first
loaded. This is done by calling the init() method of Applet class. At this
stage the following can be done:
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colors
Initialization happens only once in the life time of an applet.

Running state: Applet enters the running state when the system calls
the start() method of Applet class. This occurs automatically after the
applet is initialized. start() can also be called if the applet is already in
idle state. start() may be called more than once. start() method may be
overridden to create a thread to control the applet.
public void start()
{
//implementation
}

Display state: Applet is in the display state when it has to perform


some output operations on the screen. This happens after the applet
enters the running state. paint() method is called for this. If anything is
to be displayed the paint() method is to be overridden.
public void paint(Graphics g)
{
//implementation
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 15/ 27

Q.4.
A. Attempt any THREE: 12

a) Compare string class and StringBuffer class with any four points.
(Any four points 1M each)
Sr. String StringBuffer
No.
1. String is a major class StringBuffer is a peer class of String
2. Length is fixed Length is flexible
3. Contents of object cannot be Contents of can be modified
modified
4. Object can be created by Objects can be created by calling
assigning String constants constructor of StringBuffer class using
enclosed in double quotes. new
5. Ex:- String s=abc; Ex:- StringBuffer s=new StringBuffer
(abc);

b) Explain thread priority and method to get and set priority values.

Threads in java are sub programs of main application program and share
the same memory space. They are known as light weight threads. A java
program requires at least one thread called as main thread. The main thread
is actually the main method module which is designed to create and start
other threads. Thread Priority: In java each thread is assigned a priority
which affects the order in which it is scheduled for running. Threads of
same priority are given equal treatment by the java scheduler.
The thread class defines several priority constants as: -

MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10

Thread priorities can take value from 1-10.


To set the priority thread class provides setPriority ()
Syntax: Thread.setPriority (priority value);

To see the priority value of a thread the method available is getPriority().


Syntax: int Thread.getPriority ();
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 16/ 27

c) Define a class having one 3 digit number, num as data member,


initialize and display reverse of that number.
(Logic 2-M, Syntax 2-M)

class reverse
{
public static void main(String args[])
{
int num = 253;
int q,r;
for (int I = 0; i<3; i++)
{
q = num / 10;
r = num % 10;
System.out.println(r);
Num = q;
}
}
}

d) Write syntax and function of following methods of Date class:


i. getTime ()
ii. getDate ()

(1 M each for syntax, 1 M each for function)


The Date class encapsulates the current date and time.
i. getTime():

Syntax:
long getTime( )
Returns the number of milliseconds that have elapsed since January 1,
1970.

ii. getDate()
Syntax:
public int getDate()
Returns the day of the month. This method assigns days with the values of
1 to 31.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 17/ 27

B. Attempt any one of the following: 6

a) Explain following methods of vector class:


i. elementAt ()
ii. addElement ()
iii. removeElement ()

(Syntax 1m each, Use 1M each)


1) Object elementAt(int index)
Returns the component at the specified index.
2) void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size
by one.
3) boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this
vector.

b) Explain <PARAM> tag of applet with suitable example.

(Syntax of PARAM tag 1M, Use of tag 1m, Any suitable example 2M)
(Any suitable example may be considered)

To pass parameters to an applet <PARAM > tag is used. Each


<PARAM> tag has a name attribute and a value attribute. Inside the
applet code, the applet can refer to that parameter by name to find its value.
The syntax of <PARAM> tag is as follows

<PARAM NAME = name1 VALUE = value1>

To set up and handle parameters, two things must be done.

1. Include appropriate <PARAM..> tags in the HTML document.

2. Provide code in the applet to parse these parameters.

Parameters are passed on an applet when it is loaded. Generally init()


method in the applet is used to get hold of the parameters defined in the
<PARAM> tag. The getParameter() method, which takes one string
argument representing the name of the parameter and returns a string
containing the value of that parameter.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 18/ 27

Example
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}

<HTML>
<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>

Q.5. Attempt any TWO of the following: 16


a) Write a program to input name and age of a person and throws an user
define exception if entered age is negative.

(Declaration of class with proper members and constructor 4 M, statement for


throwing exception and main method 4 M)
[Note: Any other relevant program can be considered]
import java.io.*;
class negative extends Exception
{
negative(String msg)
{
super(msg);
}
}

class negativedemo
{
public static void main(String ar[])
{
int age=0;
String name;
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 19/ 27

InputStreamReader isr=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(isr);
System.out.println("enter age and name of person");
try
{
age=Integer.parseInt(br.readLine());
name=br.readLine();
{
if(age<0)
{
throw new negative("age is negative");
}
else
throw new negative("age is positive");
}}
catch(negative n)
{
System.out.println(n);
}
catch(Exception e)
{
}
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 20/ 27

b) With suitable diagram explain life cycle of Thread.

(2 M for diagram, 6 M for Explanation)

Thread Life Cycle


Thread has five different states throughout its life.

1) Newborn State

2) Runnable State

3) Running State

4) Blocked State

5) Dead State

Thread should be in any one state of above and it can be move from one state
to another by different methods and ways.

1. Newborn state: When a thread object is created it is said to be in a new born state.
When the thread is in a new born state it is not scheduled running from this state it
can be scheduled for running by start() or killed by stop(). If put in a queue it moves to
runnable state.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 21/ 27

2. Runnable State: It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is waiting for
execution. If all threads have equal priority then they are given time slots for
execution in round robin fashion. The thread that relinquishes control joins the queue
at the end and again waits for its turn. A thread can relinquish the control to another
before its turn comes by yield().

3. Running State: It means that the processor has given its time to the thread for
execution. The thread runs until it relinquishes control on its own or it is pre-empted
by a higher priority thread.

4. Blocked state: A thread can be temporarily suspended or blocked from


entering into the runnable and running state by using either of the following thread
method.

suspend() : Thread can be suspended by this method. It can be rescheduled by


resume().

wait(): If a thread requires to wait until some event occurs, it can be done using wait
method and can be scheduled to run again by notify().

sleep(): We can put a thread to sleep for a specified time period using sleep(time)
where time is in ms. It reenters the runnable state as soon as period has elapsed /over.

5. Dead State: Whenever we want to stop a thread form running further we can call its
stop(). The statement causes the thread to move to a dead state. A thread will also
move to dead state automatically when it reaches to end of the method. The stop
method may be used when the premature death is required.

c) State the use of font class. Describe any three methods of font class with
their syntax and example of each.

(Use:- 2M, Any three method ( syntax and example), for each method -2M)
(Any other suitable example may also be considered)
Uses:-
The Font class states fonts, which are used to render text in a visible way.
It is used to set or retrieve the screen font.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 22/ 27

Sr methods description
no

1 static Font decode(String str) :Returns a font given its name.

2 boolean equals(Object Returns true if the invoking object contains the


FontObj) : same font as that specified by FontObj.Otherwise,
it returns false.

3 String toString( ) Returns the string equivalent of the invoking font.

4 String getFamily( ) Returns the name of the font family to which the
invoking font belongs.

5 static Font getFont(String Returns the font associated with the system
property) property specified by property. null is returned if
property does not exist.

6 static Font getFont(String Returns the font associated with the


property,Font defaultFont) systemproperty specified by property. The font
specified by defaultFont is returned if property
does not exist.

7 String getFontName() Returns the face name of the invoking font.

8 String getName( ) Returns the logical name of the invoking font.

9 int getSize( ) Returns the size, in points, of the invoking font.

10 int getStyle( ) Returns the style values of the invoking font.

11 int hashCode( ) Returns the hash code associated with the invoking
object.

12 boolean isBold( ) Returns true if the font includes the BOLD style
value. Otherwise, false is returned.

13 boolean isItalic( ) Returns true if the font includes the ITALIC style
value. Otherwise, false is returned.

14 boolean isPlain( ) Returns true if the font includes the PLAIN style
value. Otherwise, false is returned.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 23/ 27

example:-

//program using equals method


import java.awt.*;
import java.applet.*;
public class ss extends Applet

{
public void paint(Graphics g)
{
Font a = new Font ("TimesRoman", Font.PLAIN, 10);
Font b = new Font ("TimesRoman", Font.PLAIN, 10);
// displays true since the objects have equivalent settings
g.drawString(""+a.equals(b),30,60);
}
}
/*<applet code=ss height=200 width=200>
</applet>*/

// program using getFontName,getFamily(),getSize(),getStyle(),.getName()


import java.awt.*;
import java.applet.*;
public class font1 extends Applet
{
Font f,f1;
String s,msg;
String fname;
String ffamily;
int size;
int style;
public void init()
{
f= new Font("times new roman",Font.ITALIC,20);
setFont(f);
msg="is interesting";
s="java programming";
fname=f.getFontName();
ffamily=f.getFamily();
size=f.getSize();
style=f.getStyle();
String f1=f.getName();

}
public void paint(Graphics g)
{
g.drawString("font name"+fname,60,44);
g.drawString("font family"+ffamily,60,77);
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 24/ 27

g.drawString("font size "+size,60,99);


g.drawString("fontstyle "+style,60,150);
g.drawString("fontname "+f1,60,190);
}
}
/*<applet code=font1.class height=300 width=300></applet>*/

Q.6. Attempt any FOUR of the following: 16

a) Differentiate applet and application with any four points.


(Any four points 1 M each)
Applet Application

Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries from Application are not restricted from using
other language such as C or C++ libraries from other language

b) Define JDK. List the tools available in JDK explain any one in detail.
(Definition 1 M, list any four tools -2M, explanation of any
component -1 M)

Definition: A Java Development Kit (JDK) is a collection of tools which are


used for developing, designing, debugging, executing and running java
programs.
Tools of JDK.
java
javap
javah
javadoc
jdb
appletviewer
javac

1. Java Compiler it is used to transl ate j ava source code to byt e


code fil es that the i nterpret er can underst and.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 25/ 27

c) Write a program to implement following inheritance:

Class: Person,
name , age

Class: employee,
emp_designation,
emp_salary

(Class and method declaration superclass1-1/2 M, class and method declaration of subclass

1-1/2 M, main method 1M)

(Any other program with correct logic may also be considered)

class person
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("name--->"+name);
System.out.println("age--->"+age);
}
}
class employee extends person
{
String emp_designation;
float emp_salary;
void accept_emp(String d,float s)
{
emp_designation=d;
emp_salary=s;
}
void emp_dis()
{
System.out.println("emp_designation-->"+emp_designation);
System.out.println("emp_salary-->"+emp_salary);
}
}
class single_demo
{
public static void main(String ar[])
{
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 26/ 27

employee e=new employee();


e.accept("ramesh",35);
e.display();
e.accept_emp("lecturer",35000.78f);
e.emp_dis();
}
}

d) Write the effect of access specifiers public, private and protected in package.
(Each specifier 2 marks)
Visibility restriction must be considered while using packages and inheritance in program
visibility restrictions are imposed by various access protection modifiers. packages acts as
container for classes and other package and classes acts as container for data and methods.

Data members and methods can be declared with the access protection modifiers such as
private, protected and public. Following table shows the access protections

Access modifier public protected Friendly Private private


protected
(default)

Access location

Same class yes yes yes yes yes

Subclass in same yes yes yes yes no


package

Other classes in yes yes yes no no


same package

Subclass in other yes yes no yes no


packages

Non-subclasses in yes no no no no
other packages

e) What are stream classes? List any two input stream classes from character stream.
(Definition and types- 2 M, any two input classes -2 M)

Definition: The java. Io package contain a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into two groups
based on the data type on which they operate.

1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 27/ 27

Character Stream Class can be used to read and write 16-bit Unicode characters. There are
two kinds of character stream classes, namely, reader stream classes and writer stream classes

Reader stream classes:--it is used to read characters from files. These classes are
functionally similar to the input stream classes, except input streams use bytes as their
fundamental unit of information while reader streams use characters

Input Stream Classes


1. BufferedReader
2. CharArrayReader
3. InputStreamReader
4. FileReader
5. PushbackReader
6. FilterReader
7. PipeReader
8. StringReader
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the candidates answers and model answer.
6) In case of some questions credit may be given by judgment on part of examiner of relevant
answer based on candidates understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.

Marks

1. (A) Attempt any THREE of the following: 34 = 12

(a) Explain any four features of Java.


(Any four features - 1 Mark each)

Ans:
1. Compile & Interpreted: Java is a two staged system. It combines both approaches.
First java compiler translates source code into byte code instruction. Byte codes are
not machine instructions. In the second stage java interpreter generates machine code
that can be directly executed by machine. Thus java is both compile and interpreted
language.

2. Platform independent and portable: Java programs are portable i.e. it can be easily
moved from one computer system to another. Changes in OS, Processor, system
resources wont force any change in java programs. Java compiler generates byte
code instructions that can be implemented on any machine as well as the size of
primitive data type is machine independent.

Page 1 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

3. Object Oriented: Almost everything in java is in the form of object. All program
codes and data reside within objects and classes. Similar to other OOP languages java
also has basic OOP properties such as encapsulation, polymorphism, data abstraction,
inheritance etc. Java comes with an extensive set of classes (default) in packages.

4. Robust & Secure: Java is a robust in the sense that it provides many safeguards to
ensure reliable codes. Java incorporates concept of exception handling which captures
errors and eliminates any risk of crashing the system. Java system not only verify all
memory access but also ensure that no viruses are communicated with an applet. It
does not use pointers by which you can gain access to memory locations without
proper authorization.

5. Distributed: It is designed as a distributed language for creating applications on


network. It has ability to share both data and program. Java application can open and
access remote object on internet as easily as they can do in local system.

6. Multithreaded: It can handle multiple tasks simultaneously. Java makes this possible
with the feature of multithreading. This means that we need not wait for the
application to finish one task before beginning other.

7. Dynamic and Extensible: Java is capable of dynamically linking new class librarys
method and object. Java program supports function written in other languages such as
C, C++ which are called as native methods. Native methods are linked dynamically at
run time.

(b) What is exception? How it is handled? Explain with suitable example.


(Definition 1 Mark, Listing of keywords 1 Mark, Example 2 Marks)

Ans:

Exception: An exception is an event, which occurs during the execution of a program,


that stop the flow of the program's instructions and takes appropriate actions if
handled. .i.e. It is erroneous situation encounter during course of execution of program.
Exception handling in java is done by 5 keywords as:
1) try 2) catch 3) finally 4) throw 5) throws
Example:
class DemoException
{

Page 2 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


public static void main(String args[])
{
try
{
int b=8;
int c=b/0;
System.out.println(answer=+c);
}
catch(ArithmeticException e)
{
System.out.println(Division by Zero);
}
}
}

(c) Describe break and continue statement with example.


(Each explanation - 1 Mark, Example - 1 Mark)
[**Note: any other relevant example can be considered]
Ans:
Break:
The break keyword is used to stop the entire loop. The break keyword must be used
inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the
next line of code after the block.
Example:
public class TestBreak
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
System.out.println( value of x-+x );

Page 3 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

}
}
}

continue:
The continue statement skips the current iteration of a for, while , or do-while loop. The
unlabeled form skips to the end of the innermost loop's body and evaluates the boolean
expression that controls the loop.
A labeled continue statement skips the current iteration of an outer loop marked with the
given label.
Example:
public class TestContinue
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

(d) What are streams? Write any two methods of character stream classes.
(Definition of Streamclass - 2 Marks, two methods of character stream class - 2 Marks)

Ans:
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information (i.e it takes the input or gives the output). A stream is
linked to a physical device by the Java I/O system. All streams behave in the same
manner, even if the actual physical devices to which they are linked differ. Thus, the
same I/O classes and methods can be applied to any type of device.

Page 4 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


Java 2 defines two types of streams: byte and character. Byte streams provide a
convenient means for handling input and output of bytes. Byte streams are used, for
example, when reading or writing binary data. Character streams provide a convenient
means for handling input and output of characters. They use Unicode and, therefore, can
be internationalized. Also, in some cases, character streams are more efficient than byte
streams.
The Character Stream Classes

Character streams are defined by using two class hierarchies. At the top are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character streams.
Java has several concrete subclasses of each of these.

Methods of Reader Class

1) void mark(int numChars) : Places a mark at the current point in the input stream
that will remain valid until numChars characters are read.

2) boolean markSupported( ) : Returns true if mark( ) / reset( ) are supported on this


stream.
3) int read( ) :Returns an integer representation of the next available character from the
invoking input stream. 1 is returned when the end of the file is encountered.

4) int read(char buffer[ ]) : Attempts to read up to buffer. Length characters into


buffer and returns the actual number of characters that were successfully read. 1 is
returned when the end of the file is encountered.

5) abstract int read(char buffer[ ],int offset,int numChars): Attempts to read up to


numChars characters into buffer starting at buffer[offset], returning the number of
characters successfully read.1 is returned when the end of the file is encountered.

6) boolean ready( ): Returns true if the next input request will not wait. Otherwise, it
returns false.

7) void reset( ): Resets the input pointer to the previously set mark.

8) long skip(long numChars) :- Skips over numChars characters of input, returning the
number of characters actually skipped.

9) abstract void close( ) :- Closes the input source. Further read attempts will generate
an IOException

Page 5 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

[**Note: any two methods from above list to be considered]

Writer Class
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of error

Methods of Writer class are listed below: -

1) abstract void close( ) : Closes the output stream. Further write attempts will generate
an IOException.

2) abstract void flush( ) : Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers.

3) void write(intch): Writes a single character to the invoking output stream. Note that
the parameter is an int, which allows you to call write with expressions without having to
cast them back to char.

4) void write(char buffer[ ]): Writes a complete array of characters to the invoking
output stream

5) abstract void write(char buffer[ ],int offset, int numChars) :- Writes a subrange of
numChars characters from the array buffer, beginning at buffer[offset] to the invoking
output stream.

6) void write(String str): Writes str to the invoking output stream.

7) void write(String str, int offset,int numChars): Writes a sub range of numChars
characters from the array str, beginning at the specified offset.

[**Note: any two methods from above list to be considered]

(B) Attempt any ONE of following: 16 = 6

(a) What is package? How to create package? Explain with suitable example.
(Definition of package - 1 Mark, Package creation - 2 Marks, Example - 3 Marks)

[**Note: Any relevant example can be considered]

Page 6 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

Ans:
Java provides a mechanism for partitioning the class namespace into more manageable
parts called package (i.e package are container for a classes). The package is both naming
and visibility controlled mechanism. Package can be created by including package as the
first statement in java source code. Any classes declared within that file will belong to the
specified package.
The syntax for creating package is:
package pkg;
Here, pkg is the name of the package
eg : package mypack;
Packages are mirrored by directories. Java uses file system directories to store packages.
The class files of any classes which are declared in a package must be stored in a
directory which has same name as package name. The directory must match with the
package name exactly. A hierarchy can be created by separating package name and sub
package name by a period(.) as pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3.
The classes and methods of a package must be public.
Syntax:
To access package In a Java source file, import statements occur immediately
following the package statement (if it exists) and before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}
Source file:

Page 7 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}

(b) State the use of super and final keyword w.r.t inheritance with example.
(super with example - 3 Marks , final with example - 3 Marks)
[**Note any relevant example can be considered]

Ans:
when you will want to create a superclass that keeps the details of its implementation to
itself (that is, that keeps its data members private). In this case, there would be no way for
a subclass to directly access or initialize these variables on its own. Whenever a subclass
needs to refer to its immediate super class, it can do so by use of the keyword super. As
constructer can not be inherited, but derived class can called base class constructer using
super ()
super has two general forms.
The first calls the super class constructor. (super() method)
The second is used to access a member of the super class that has been hidden by a
member of a subclass.
Using super () to Call Super class Constructors

A subclass can call a constructor method defined by its super class by use of the
following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the super
class. super( ) must always be the first statement executed inside a subclass constructor.
A Second Use for super
The second form of super acts somewhat like this, except that it always refers to the
super class of the subclass in which it is used. This usage has the following general form:
super.member

Page 8 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


Here, member can be either a method or an instance variable. This second form of super
is most applicable to situations in which member names of a subclass hide members by
the same name in the super class.
Example:
// Using super to overcome name hiding.
class A
{
int i;
}
// Create a subclass by extending class A.
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}

Final keywords
The keyword final has three uses. First, it can be used to create the equivalent of a named
constant.( in interface or class we use final as shared constant or constant.)
other two uses of final apply to inheritance

Using final to Prevent Overriding

While method overriding is one of Javas most powerful features, there will be times

Page 9 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


When you will want to prevent it from occurring. To disallow a method from being
overridden, specify final as a modifier at the start of its declaration. Methods declared
as final cannot be overridden. The following fragment illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}

As base class declared method as a final , derived class can not override the definition of
base class methods.

2. Attempt any TWO of the following : 28 = 16

(a) Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10, 20).
Remove element at 3rd and 4th position. Insert new element at 3rd position. Display
the original and current size of vector.
(Vector creation with elements 2 Marks, Remove elements 1 Mark, Insert new
element 1 Mark, Show original size 1 Mark, show current size 1 Mark )
Ans:
import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(new Integer(10));

Page 10 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


v.addElement(new Integer(20));
v.addElement(new Integer(30));
v.addElement(new Integer(40));
v.addElement(new Integer(10));
v.addElement(new Integer(20));
System.out println(v.size());// display original size
v.removeElementAt(2); // remove 3rd element
v.removeElementAt(3); // remove 4th element
v.insertElementAt(11,2) // new element inserted at 3rd position
System.out.println("Size of vector after insert delete operations: " +
v.size());
}
}

(b) What is meant by an interface? State its need and write syntax and features of an
interface. Give one example.
(Definition - 1 Mark syntax - 1 Mark, Any two features - 2 Marks, Any two needs - 2
Marks, Example - 2 Marks)
Ans:
Defining an Interface:
Interface is also known as kind of a class. So interface also contains methods and
variables but with major difference the interface consist of only abstract method
(i.e.methods are not defined,these are declared only ) and final fields(shared constants).
This means that interface do not specify any code to implement those methods and data
fields contains only constants. Therefore, it is the responsibility of the class that
implements an interface to define the code for implementation of these methods. An
interface is defined much like class.

Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
.
return_type method_nameN(parameter list);
type final-variable 1 = value1;
.

Page 11 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


type final-variable N = value2;
}

Features:
1. Variable of an interface are explicitly declared final and static (as constant) meaning
that the implementing the class cannot change them they must be initialize with a
constant value all the variable are implicitly public of the interface, itself, is declared
as a public
2. Method declaration contains only a list of methods without anybody statement and
ends with a semicolon the method are, essentially, abstract methods there can be
default implementation of any method specified within an interface each class that
include an interface must implement all of the method
Need:
1. To achieve multiple Inheritance.
2. We can implement more than one Interface in the one class.
3. Methods can be implemented by one or more class.
Example:
interface sports
{
int sport_wt=5;
public void disp();
}
class Test
{
int roll_no;
String name;
int m1,m2;
Test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class Result extends Test implements sports
{
Result (int r, String nm, int m11,int m12)
{
super (r,nm,m11,m12);

Page 12 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
{
Result r= new Result(101,"abc",75,75);
r.disp();
}
}

(c) Write syntax and example of following Graphics class methods:


(i) drawOval( )
(ii) drawPolygon( )
(iii)drawArc( )
(iv) drawRect( )
(Each method syntax 1 Mark, Example 1 Mark)
[**Note: common program using above all methods can be considered]
Ans:
(i) drawOval( )
Drawing Ellipses and circles:
To draw an Ellipses or circles used drawOval() method can be used.
Syntax: void drawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by
top and left and whose width and height are specified by width and height to draw a
circle or filled circle, specify the same width and height the following program draws
several ellipses and circle.
Example:
g.drawOval(10,10,50,50);

(ii) drawPolygon
drawPolygon() method is used to draw arbitrarily shaped figures.

Page 13 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

Syntax: void drawPolygon(int x[], int y[], int numPoints)


The polygons end points are specified by the co-ordinates pairs contained within the x
and y arrays. The number of points define by x and y is specified by numPoints.
Example:
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);

(iii)drawArc( )
It is used to draw arc .
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle is starting
angle of arc sweep_angle is degree around the arc
Example:
g.drawArc(10, 10, 30, 40, 40, 90);

(iv) drawRect()
The drawRect() method display an outlined rectangle.
Syntax: void drawRect(int top,int left,int width,int height)
The upper-left corner of the Rectangle is at top and left. The dimension of the Rectangle
is specified by width and height.
Example:
g.drawRect(10,10,60,50);

3. Attempt any FOUR of the following: 44 = 16

(a) What is constructor? Describe the use of parameterized constructor with suitable
example.
(Constructor 1 Mark, use of parameterized constructor 1 Mark, example of
parameterized constructor 2 Marks)
[**Note: any relevant example can be considered]

Ans:

Page 14 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

Constructor:
A constructor is a special method which initializes an object immediately upon
creation.
It has the same name as class name in which it resides and it is syntactically similar to
any method.
When a constructor is not defined, java executes a default constructor which
initializes all numeric members to zero and other types to null or spaces.
Once defined, constructor is automatically called immediately after the object is
created before new operator completes.
Constructors do not have return value, but they dont require void as implicit data
type as data type of class constructor is the class type itself.

Parameterized constructor:
It is used to pass the values while creating the objects
Example:
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
System.out.println(Area : +(r.length*r.breadth));
System.out.println(Area : +(r1.length*r1.breadth));
}
}

Page 15 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

(b) Describe?,: (Ternary operator) in Java with suitable example.


(Explanation of Ternary operator 2 Marks & Example 2 Marks)
[**Note: any relevant example can be considered]

Ans:

The ternary operator?: is an operator that takes three arguments. The first argument is a
comparison argument, the second is the result upon a true comparison, and the third is the
result upon a false comparison. If it helps you can think of the operator as shortened way
of writing an if-else statement. It is often used as a way to assign variables based on the
result of an comparison. When used correctly it can help increase the readability and
reduce the amount of lines in your code
Syntax:
expression1? expression2: expression3
Expression1 can be any expression that evaluates to a Boolean value.
If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the? Operation is that of the expression evaluated.
Both expression2 and expression3 are required to return the same type, which can't
be void.
Example:
class Ternary
{
public static void main(String args[])
{
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}

Page 16 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

(c) What is difference between array and vector? Explain elementAt( ) and
addElement( ) method.
(Any 2 Points - 2 Marks, Each Method - 1 Mark)

Ans:

Array Vector
Array can accommodate fixed number of Vectors can accommodate unknown number of
elements elements
Arrays can hold primitive data type & objects Vectors can hold only objects.
All elements of array should be of the same The objects in a vector need not have to be
data type. i.e. it can contain only homogeneous homogeneous.
elements.
Syntax : Datatype[] arrayname= new Syntax: Vector objectname= new Vector();
datatype[size];
For accessing elements of an array no special Vector class provides different methods for
methods are available as it is not a class , but accessing and managing Vector elements.
derived type.

1) elementAt( ): Returns the element at the location specified by index.


Syntax: Object elementAt(int index)
Example:
Vector v = new Vector();
v.elementAt(2); //return 2nd element from vector

2) addElement ( ): Adds the specified component to the end of this vector, increasing
its size by one.
Syntax: void addElement(Object element)
Example:
Vector v = new Vector();
v.addElement(new Integer(1)); //add integer object 1 to vector

Page 17 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

(d) Write any two methods of File and FileInputStream class each.
(An y two methods of each class - 1 Mark)

Ans:
File Class Methods

1. String getName( ) - returns the name of the file.


2. String getParent( ) - returns the name of the parent directory.
3. boolean exists( ) - returns true if the file exists, false if it does not.
4. void deleteOnExit( ) -Removes the file associated with the invoking object when the
Java Virtual Machine terminates.
5. boolean isHidden( )-Returns true if the invoking file is hidden. Returns false
otherwise.

FileInputStream Class Methods:

1. int available( )- Returns the number of bytes of input currently available for reading.
2. void close( )- Closes the input source. Further read attempts will generate an
IOException.
3. void mark(int numBytes) -Places a mark at the current point in the inputstream that
will remain valid until numBytes bytes are read.
4. boolean markSupported( ) -Returns true if mark( )/reset( ) are supported by the
invoking stream.
5. int read( )- Returns an integer representation of the next available byte of input. 1 is
returned when the end of the file is encountered.
6. int read(byte buffer[ ])- Attempts to read up to buffer.length bytes into buffer and
returns the actual number of bytes that were successfully read. 1 is returned when
the end of the file is encountered.

(e) Write a program to design an applet to display three circles filled with three
different colors on screen.
(Correct logic 2 Marks, Applet tag 1 Mark, Package imported 1 Mark)
[**Note: any other relevant logic can be considered, output not necessary]

Ans:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet

Page 18 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
/*<applet code= MyApplet width= 300 height=300></applet>*/
Output:

4. (A) Attempt any THREE of the following: 34 = 12

(a) Write a program to check whether the entered number is prime or not.
(Accept No. from user - 1 Mark, Prime No. logic - 3 Marks)
Ans: import java.io.*;
class PrimeNo
{
public static void main(String args[]) throws IOException
{
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number: ");
int num=Integer.parseInt(bin.readLine());

Page 19 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

int flag=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}

(b) Explain the following clause w.r.t. exception handling:


(i) try
(ii) catch
(iii) throw
(iv) finally
(Each keywords syntax with explanation - 1 Mark)
Ans:
i. try- Program statements that you want to monitor for exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown.
Syntax:
try
{
// block of code to monitor for errors
}
ii. catch- Your code can catch this exception (using catch) and handle it in some
rational manner. System-generated exceptions are automatically thrown by the Java
runtime system. A catch block immediately follows the try block. The catch block too
can have one or more statements that are necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)

Page 20 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


{
// exception handler for ExceptionType1
}
iii. throw:It is possible for a program to throw an exception explicitly, using the throw
statement.
The general form of throw is :

throw new ThrowableInstance;


or
throw Throwableinstance;
throw statement explicitly throws an built-in /user- defined exception. When throw
statement is executed, the flow of execution stops immediately after throw statement,
and any subsequent statements are not executed.

iv. finally: It can be used to handle an exception which is not caught by any of the
previous catch statements. finally block can be used to handle any statement
generated by try block. It may be added immediately after try or after last catch block.

Syntax:
finally
{
// block of code to be executed before try block ends
}

(c) Explain any two bit-wise operators with example.


(Any 2 (Each Bitwise operator explanation - 1 Mark, Example - 1 Mark))

Ans:
1) Bitwise NOT (~): called bitwise complement, the unary NOT operator, inverts all of
the bits of its operand.
e.g~ 0111 (decimal 7) = 1000 (decimal 8)

2) Bitwise AND ( & ):


the AND operator, &, produce a 1 bit if both operands are also 1, A zero is produced in
all the cases.

Page 21 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


e.g0101 (decimal 5) &0011 (decimal 3) = 0001 (decimal 1)

3) Bitwise OR ( | ) :
the OR operator, | , combines bits such that if either of the bits in the operand is a 1, then
the resultant bit is a 1

e.g0101 (decimal 5) |0011 (decimal 3) = 0111 (decimal 7)

4) Bitwise XOR ( ^ ): the XOR operator, ^, combines bits such that if exactly one
operand is 1, then the result is 1. Otherwise result is zero.
e.g0101 (decimal 5) ^ 0011 (decimal 3) = 0110 (decimal 6)

5) The Left Shift (<<): the left shift operator, <<, shifts all of the bits in a value to the
left a specified number of times specified by num
General form: value <<num

e.g. x << 2 (x=12)

0000 1100 << 2 = 0011 0000 (decimal 48)

6) The Right Shift (>>): the right shift operator, >>, shifts all of the bits in a value to
the right a specified number of times specified by num
General form: value >>num.

e.g. x>> 2 (x=32)

0010 0000 >> 2 = 0000 1000 (decimal 8)

7) Unsigned Right Shift (>>>) : >>> always shifts zeros into high order bit.
e.g. int a= -1

a=a>>>24

11111111 11111111 11111111 11111111 (-1 in binary as int) >>> 24

00000000 00000000 00000000 11111111(255 in binary as an int)

Page 22 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


8) Bitwise Operators Compound Assignments: All of the above binary bitwise
operators have a compound form similar to that of the algebraic operators, which
combines the assignment with the bitwise operation. These two statements are equivalent.
e.g.a = a >>4 ;

a >> = 4;

(d) Explain all attributes available in <applet>tag.


(Any 4 attributes - 1 Mark each)

Ans:

APPLET Tag: The APPLET tag is used to start an applet from both an HTML
document and from an appletviewer will execute each APPLET tag that it finds in a
separate window, while web browser will allow many applets on a single page the syntax
for the standard APPLET tag is:

<APPLET
[CODEBASE=codebaseURL]
CODE =appletfileName
[ALT=alternateText]
[NAME=applet_instance_name]
WIDTH=pixels HEIGHT=pixels
[ALIGN=aligment]
[VSPACE=pixels] [HSPACE=pixels]
>
[<PARAM NAME=attributeName1 VALUE=attributeValue>]
[<PARAM NAME=attributeName2 VALUE=attributeValue>]
</APPLET>
CODEBASE: is an optional attribute that specifies the base URL of the applet code or
the directory that will be searched for the applets executable class file.

CODE: is a required attribute that give the name of the file containing your applets
compiled class file which will be run by web browser or appletviewer.

ALT: Alternate Text The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.

Page 23 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


NAME: is an optional attribute used to specify a name for the applet instance.

WIDTH AND HEIGHT: are required attributes that give the size(in pixels) of the applet
display area. ALIGN is an optional attribute that specifies the alignment of the applet.
The possible value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE,
TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

VSPACE AND HSPACE: attributes are optional, VSPACE specifies the space, in
pixels, about and below the applet. HSPACE VSPACE specifies the space, in pixels, on
each side of the applet

PARAM NAME AND VALUE: The PARAM tag allows you to specifies applet-
specific arguments in an HTML page applets access there attributes with the
getParameter() method.

(B) Attempt any ONE of the following: 16 = 6

(a) Differentiate between applet and application and also write a simple applet which
display message Welcome to Java.
(Any 3 Points - 3 Marks, Correct Program - 3 Marks)
Ans:
Applet Application
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files Application can read from or write to files in
in local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries Application are not restricted from using
from other language such as C or C++ libraries from other language

Page 24 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

Program:
/*<applet code= WelcomeJava width= 300 height=300></applet>*/

import java. applet.*;


import java.awt.*;
public class WelcomeJava extends Applet
{
public void paint( Graphics g)
{
g.drawString(Welcome to java,25,50);
}
}

(b) Describe the following string class methods with examples :


(i) length()
(ii) charAt()
(iii) CompareTo()
(Each Method syntax or explanation - 1 Mark, Example - 1 Mark)
Ans:
1. length():
Syntax: int length()
It is used to return length of given string in integer.
Eg. String str=INDIA
System.out.println(str);
System.out.println(str.length()); // Returns 5

2. charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .
Eg. String s=INDIA
System.out.println(s.charAt(2) ); // returns D

3. compareTo():
Syntax: int compareTo(Object o)
or

Page 25 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

int compareTo(String anotherString)


There are two variants of this method. First method compares this String to another
Object and second method compares two strings lexicographically.
Eg. String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";

int result = str1.compareTo( str2 );


System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);

5. Attempt any TWO of the following: 28 = 16

(a) Write a program to accept password from user and throw Authentication failure
exception if password is incorrect.
(Correct logic - 5 Marks, for syntax - 3 Marks)

Ans:
import java.io.*;
class PasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
class PassCheck
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("EXAMW15"))
{

Page 26 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


System.out.println("Authenticated ");
}
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

(b) Explain life cycle of thread with neat diagram.


(Diagram - 3 Marks, Explanation - 5 Marks)

Ans:
Thread Life Cycle
Thread has five different states throughout its life.
1) Newborn State
2) Runnable State
3) Running State
4) Blocked State
5) Dead State
Thread should be in any one state of above and it can be move from one state to another
by different methods and ways.

Page 27 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

1. Newborn state: When a thread object is created it is said to be in a new born state.
When the thread is in a new born state it is not scheduled running from this state it can be
scheduled for running by start() or killed by stop(). If put in a queue it moves to runnable
state.

2. Runnable State: It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is waiting for
execution. If all threads have equal priority then they are given time slots for execution in
round robin fashion. The thread that relinquishes control joins the queue at the end and
again waits for its turn. A thread can relinquish the control to another before its turn
comes by yield().

3. Running State: It means that the processor has given its time to the thread for
execution. The thread runs until it relinquishes control on its own or it is pre-empted by a
higher priority thread.

4. Blocked state: A thread can be temporarily suspended or blocked from entering into
the runnable and running state by using either of the following thread method.
suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
wait(): If a thread requires to wait until some event occurs, it can be done using wait
method andcan be scheduled to run again by notify().

Page 28 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


Sleep(): We can put a thread to sleep for a specified time period using sleep(time) where
time is in ms. It reenters the runnable state as soon as period has elapsed /over

5. Dead State: Whenever we want to stop a thread form running further we can call its
stop(). The statement causes the thread to move to a dead state. A thread will also move
to dead state automatically when it reaches to end of the method. The stop method may
be used when the premature death is required

(c) How can parameter be passed to an applet? Write an applet to accept user name in
the form of parameter and print Hello<username>.
(Explanation for parameter passing - 3Marks, any suitable example 5 Marks)
(Any suitable example may be considered)

Ans:
Passing Parameters to Applet
User defined parameters can be supplied to an applet using <PARAM..> tags.
PARAM tag names a parameter the Java applet needs to run, and provides a value
for that parameter.
PARAM tag can be used to allow the page designer to specify different colors, fonts,
URLs or other data to be used by the applet.

To set up and handle parameters, two things must be done.


1. Include appropriate <PARAM..>tags in the HTML document.
The Applet tag in HTML document allows passing the arguments using param tag.
The syntax of <PARAM> tag
<Applet code=AppletDemo height=300 width=300>
<PARAM NAME = name1 VALUE = value1>
</Applet>
NAME:attribute name
VALUE: value of attribute named by corresponding PARAM NAME.
2. Provide code in the applet to parse these parameters.
The Applet access their attributes using the getParameter method. The syntax is :
String getParameter(String name);

import
java.awt.*;
import
java.applet.*;
public class HelloUser extends Applet

Page 29 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


{
String str;
public void init()
{
str = getParameter("username"); // Receiving parameter value
str = "Hello "+ str; //Using the value
}
public void paint(Graphics g)
{
g.drawString(str,10,100);

}
}
<HTML>
<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
OR
import java.awt.*;
import java.applet.*;
/*<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>*/
public class HelloUser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}

Page 30 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

6. Attempt any FOUR of the following : 44 = 16

(a) Explain method overloading with example.


(Method overloading - 1 Mark, Any relevant Example - 3 Marks)

Ans:
Method Overloading means to define different methods with the same name but different
parameters lists and different definitions. It is used when objects are required to perform
similar task but using different input parameters that may vary either in number or type of
arguments. Overloaded methods may have different return types. It is a way of achieving
polymorphism in java.
int add( int a, int b) // prototype 1
int add( int a , int b , int c) // prototype 2
double add( double a, double b) // prototype 3
Example :
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();

System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2.2));

Page 31 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming


}
}

(b) State any four system packages along with their use.
(Any 4 four, for each listing and use - 1 Mark)

Ans:
1. java.lang - language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. They include classes for primitive
types, strings, math functions, threads and exceptions.
2. java.util language utility classes such as vectors, hash tables, random numbers, date
etc.
3. java.io input/output support classes. They provide facilities for the input and
output of data
4. java.awt set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
5. java.net classes for networking. They include classes for communicating with
local computers as well as with internet servers.
6. java.applet classes for creating and implementing applets.

(c) What is use of ArrayList Class ?State any three methods with their use from
ArrayList.
(Any one Use - 1 Mark, Any 3 methods - 1 Mark each)

Ans:
Use of ArrayList class:
1. ArrayList supports dynamic arrays that can grow as needed.
2. ArrayList is a variable-length array of object references. That is, an ArrayListcan
dynamically increase or decrease in size. Array lists are created with an initial size.
When this size is exceeded, the collection is automatically enlarged. When objects are
removed, the array may be shrunk.

Methods of ArrayList class :


1. void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >size()).

Page 32 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

2. boolean add(Object o)
Appends the specified element to the end of this list.
3. boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator. Throws
NullPointerException if the specified collection is null.
4. boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the
specified position. Throws NullPointerException if the specified collection is null.
5. void clear()
Removes all of the elements from this list.
6. Object clone()
Returns a shallow copy of this ArrayList.
7. boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if
and only if this list contains at least one element e such that (o==null ? e==null :
o.equals(e)).
8. void ensureCapacity(intminCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can
hold at least the number of elements specified by the minimum capacity argument.
9. Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >= size()).
10. int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if
the List does not contain this element.
11. int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if
the list does not contain this element.
12. Object remove(int index)
Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13. protected void removeRange(intfromIndex, inttoIndex)
Removes from this List all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.
14. Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element.
Throws IndexOutOfBoundsException if the specified index is is out of range (index <
0 || index >= size()).

Page 33 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

15. int size()


Returns the number of elements in this list.
16. Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
17. Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the
runtime type of the returned array is that of the specified array.
18. void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.

(d) Explain Serialization in relation with stream classes.


(Correct Explanation - 4 Marks)

Ans:
Serialization in java is a mechanism of writing the state of an object into a
byte stream.
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object
and its data can be used to recreate the object in memory.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types such as writeObject() method. This method serializes an Object and sends it to
the output stream. Similarly, the ObjectInputStream class contains method for
deserializing an object as readObject(). This method retrieves the next Object out of
the stream and deserializes it. The return value is Object, so you will need to cast it to
its appropriate data type.
For a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient.

Page 34 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper

Subject Code: 17515 Subject Name: Java Programming

(e) What is byte code? Explain any two tools available in JDK.
(Bytecode - 2 Marks, Any 2 Tools - 1 Mark each)

Ans:
Byte code: Bytecode in Java is an intermediate code generated by the compiler such as
Suns javac, that is executed by JVM. Bytecode is compiled format of Java programs it
has a .class extension.

Tools Brief Description

javac The compiler for the Java programming language.

The launcher for Java applications. In this release, a single launcher


java is used both for development and deployment.
The old deployment launcher, jre, is no longer provided.

javadoc API documentation generator.


appletviewer Run and debug applets without a web browser.
jar Manage Java Archive (JAR) files.

jdb The Java Debugger.


javah C header and stub generator. Used to write native methods.
javap Class file disassemble

Page 35 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given int he model answer
scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not
applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the Figure. The
figures drawn by candidate and model answer may vary. The examiner may give Credit for any equivalent
figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed Constant values
may vary and there may be some difference in the candidates answers and model answer.
6) In case of some questions credit may be given by judgment on part of examiner of relevant answer based
on candidates understanding.
7) For programming language papers, credit may be given to any other program based on Equivalent
concept.
Marks

1. a) Attempt any three of the following: ( 3 4 =12)

a) Describe any two relational and any two logical operators in java with simple example.
(Relational operators & example - 1 mark each; Logical operators & example - 1 mark each)
[**Note - Any relevant example can be considered**]
Ans:
Relational Operators: When comparison of two quantities is performed depending on their
relation, certain decisions are made. Java supports six relational operators as shown in table.

Operators Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal
to
== Equal to
!= Not equal to

Page 1 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

Program demonstrating Relational Operators


class relational
{
public static void main(String args[])
{
int i=37;
int j=42;
System.out.println(i>j+(i>j)): //false
System.out.println(I<j+(i<j)); //true
System.out.println(i>=j+(i>=j)); //false
System.out.println(i<=j+(I<=j)); // true
System.out.println(i==j+(i==j)); // false
System.out.println(i!=j+(i!=j)); //true
}
}

Logical Operators: Logical operators are used when we want to form compound conditions by
combining two or more relations. Java has three logical operators as shown in table:

Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Program demonstrating logical Operators


class Log
{
public static void main(String args[])
{
boolean A=true;
boolean B=false;
System.out.println(A\B+(a|B)); //true
System.out.println(A&B+(A&B)); // false

System.out.println(!A+(!A)); // false
System.out.println(A^B+(A^B)); // true
System.out.println((A|B)&A+((A|B)&A)); // true
}
}

Page 2 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

b) What are stream classes? List any two input stream classes from character stream.
(Definition and types - 2 marks; any two input stream classes - 2 marks)

Ans:
Definition: The java. Io package contain a large number of stream classes that provide capabilities
for processing all types of data. These classes may be categorized into two groups based on the data
type on which they operate. 1. Byte stream classes that provide support for handling I/O operations
on bytes. 2. Character stream classes that provide support for managing I/O operations on
characters.
Character Stream Class can be used to read and write 16-bit Unicode characters. There are two
kinds of character stream classes, namely, reader stream classes and writer stream classes
Reader stream classes:-it is used to read characters from files. These classes are functionally
similar to the input stream classes, except input streams use bytes as their fundamental unit of
information while reader streams use characters
Input Stream Classes
1. BufferedReader
2. CharArrayReader
3. InputStreamReader
4. FileReader
5. PushbackReader
6. FilterReader
7. PipeReader
8. StringReader

c) Write general syntax of any two decision making statements and also give its examples.
(Any two decision making statement & example - 2 marks each)
[**Note: Any relevant example can be considered**]
Ans:
Decision Making with if statement: The if statement is powerful decision making statement & is
used to control flow of execution of statements. The if statement is the simplest one in decision
statement. The if keyword is followed by test expression in parentheses.
It is basically a two way decision statement & is used in conjunction with an expression. It has
following syntax: if(test expression)
It allows computer to evaluate expression first & then depending on value of expression
(relation or condition) is true or false, it transfers control to a particular statement. The
program has two parts to follow one for if condition is true & the other for if condition is
false

Page 3 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

The if statement can be implemented in different forms listed below:


1. Simple if statement: General form of an statement is
if (test condition)
{
statement block;
}
statement n;
Statement in block may be single statement or multiple statement. If condition is true then
statement block will be executed otherwise block is skipped & statement n is executed.
2. The ifelse statement: General form is
if (test condition)
{
True-statement block;
}
else
{
False-statement block;
}
If test expression is true, then true block statement (s) following the if statement are
executed otherwise, false-block statement(s) are executed. In both cases statement n will
always executed.
Program to demonstrate ifelse & find maximum of two numbers.
class maxof
{
public static void main(String args[])
{
int i=78;
int j=67;
if(i>j)
System.out.println (i+ is greater than +j);
else
System.out.println(j+ is greater than +i);
}

Page 4 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

3. Nested if .. else Statement: When series of decision are involved , more than one if else
statements are used in nested. General form is
if (test condition 1)
{
if (test condition2)
{
statement block 1;
}
else
{
statement block 2;
}
else
{
statement block 3;
}
statement n;

If condition-1 is false, statement block-3 will be executed; otherwise it continues to perform


second test. If condition-2 true, the statement block-1 will be evaluated; otherwise statement
block-2 will be evaluated & then control is transferred to statement n. In nesting care should
be taken for every if with else.

4. The else if ladder: When multipath decision are involved either nested if or else if
ladder can be used. A multipath decision is chain of its in which statement associated with
each else is an if. General form is:
if (condition 1)
statement 1;
else if (test condition2)
statement 2;
else if (test condition3)
statement 3;
.
.
else if (test conditionn)
statement n;
else
default statement;

statement x;

Page 5 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

This construction is known as elseif ladder. The conditions are evaluated from top (of the
ladder) to downwards. As soon as true conditions are found, statement associated with it is executed
& control is transferred to statement-n (skipping the rest of the ladder). When all the n conditions
becomes false, then final else containing default statement will be executed.

Switch Statement:
Java has built-in multi way decision statement known as switch. it can be used instead of if or
nested if..else.
General form:
switch(expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
.
.
.
default:
default block;
break;
}
statement n;
The expression is an integer expression or character. value1, value2. Value n are constants
or constant expressions which must be evaluated to integral constants are known as case
labels. Each of these values should be unique within switch statement. Block1, block 2 are
statement lists & may contain zero or more statements. There is no need to put braces around
these blocks but case labels must end with colon ( : ).
When switch is executed, value of expression is successively compared against values value-
1, value-2. If case is found whose value matches with value of expression, then block
statements that follows case are executed.
The break statement at end of each block signals end of particular case & causes exit from
switch statement & transferring control to statement following switch.
The default is optional case. When present it will be executed if value of expression does not
match with any of cases values. If not present, no action takes place when all matches fail &
control goes to statement x.

The?: Operator:
Java language has an ternary operator, useful for making two-way decisions. This operator
is combination of ? &:, Takes three operand so it is called as ternary operator. This operator

Page 6 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

is popularly known as conditional operator. General form of use of conditional operator is:
conditional expression? expression 1 : expression 2
The conditional expression is evaluated first. If result is true, expression 1 is evaluated & is
returned as value of conditional expression. Otherwise, expression 2 is evaluated & its value
is returned. For example,
if (a<0)
flag = 0;
else
flag = 1;
can written as flag = (a<0) ? 0 : 1
When conditional operators is used, code becomes more concise & perhaps , more efficient.
However readability is poor. It is better to use if statements when more than single nesting
of conditional operator is required.

d) Describe life cycle of thread.


(Diagram - 2 marks; Explanation - 2 marks)

Ans:
Thread Life Cycle Thread has five different states throughout its life.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State

Thread should be in any one state of above and it can be move from one state to another by
different methods and ways.

Page 7 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

1. Newborn state: When a thread object is created it is said to be in a new born state. When the
thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to runnable state.
2. Runnable State: It means that thread is ready for execution and is waiting for the availability
of the processor i.e. the thread has joined the queue and is waiting for execution. If all threads
have equal priority then they are given time slots for execution in round robin fashion. The
thread that relinquishes control joins the queue at the end and again waits for its turn. A thread
can relinquish the control to another before its turn comes by yield().
3. Running State: It means that the processor has given its time to the thread for execution. The
thread runs until it relinquishes control on its own or it is pre-empted by a higher priority
thread.
4. Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
wait(): If a thread requires to wait until some event occurs, it can be done using wait method
andcan be scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time
is in ms. It reenters the runnable state as soon as period has elapsed /over
5. Dead State: Whenever we want to stop a thread form running further we can call its stop().
The statement causes the thread to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop method may be used when the
premature death is required

b) Attempt any one of following. (16=6)

a) Explain following methods of string class with their syntax and suitable example.
i) substring () ii) replace ()
(Each method syntax & example - 3 marks)
[**Note - Any relevant example can be considered**]

Ans:
i) substring()
Syntax:
String substring(intstartindex)
Startindex specifies the index at which the substring will begin. It will returns a copy of the
substring that begins at startindex and runs to the end of the invoking string

String substring(intstartindex,intendindex)
Here startindex specifies the beginning index,andendindex specifies the stopping point. The
string returned all the characters from the beginning index, upto, but not including ,the ending
index.
String Str = new String("Welcome");

Page 8 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

System.out.println(Str.substring(3)); //come
System.out.println(Str.substring(3,5));//co

ii) replace()
This method returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.

Syntax: String replace(char original,char replacement)

S2=S1.replace(x,y); - Replaces all appearance of x with y.


Example:
String Str = new String("Welcome);
System.out.println(Str.replace('o', 'T')); // WelcTme

b) Write syntax of defining interface .Write any major two differences between interface and a class.
(Syntax - 2 marks; Difference - 2 marks [Any two relevant points])

Ans:
Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
return_type method_name2(parameter list);
type final-variable 1 = value1;
type final-variable 2 = value2;
CLASS INTERFACE
It has instance variable. It has final variable.
It has non abstract method. It has by default abstract method.

We can create object of class. We cant create object of interface.

Class has the access specifiers like public, Interface has only public access specifier
private, and protected.
Classes are always extended. Interfaces are always implemented.

The memory is allocated for the classes. We are not allocating the memory for the
interfaces.
Multiple inheritance is not possible with Interface was introduced for the concept of
classes multiple inheritance
class Example { interface Example
void method1() {

Page 9 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

{ int x =5;
body void method1();
} void method2();
void method2() }
{
body
}
}

2. Attempt any two of the following. ( 2 8 =16)

a) Write a program to implement a vector class and its method for adding and removing
elements. After remove display remaining list.
(Logic - 4 marks; Syntax - 4 marks)
[**Note - Any relevant program can be considered**]

Ans:
import java.io.*;
import java.lang.*;
import java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Character s5=new Character('a');
Character s6=new Character('b');
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s5);
v.addElement(s6);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);

Page 10 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}

b) Describe with example how to achieve multiple inheritance with suitable program.
(Multiple inheritance - 2 marks; example - 6 marks)
[**Note - Any relevant example can be considered**]

Ans:
Multiple inheritances: It is a type of inheritance where a derived class may have more than one
parent class. It is not possible in case of java as you cannot have two classes at the parent level
Instead there can be one class and one interface at parent level to achieve multiple interface.
Interface is similar to classes but can contain on final variables and abstract method. Interfaces can
be implemented to a derived class.
Example:

Code :
interface Gross
{
double TA=800.0;
double DA=3500;
void gross_sal();
}
class Employee
{
String name;
double basic_sal;
Employee(String n, double b)
{
name=n;
basic_sal=b;

Page 11 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

}
void display()
{
System.out.println("Name of Employee :"+name);
System.out.println("Basic Salary of Employee :"+basic_sal);
}
}
class Salary extends Employee implements Gross
{ double HRA;
Salary(String n, double b, double h)
{
super(n,b);
HRA=h;
}
void disp_sal()
{ display();
System.out.println("HRA of Employee :"+hra);
}
public void gross_sal()
{
double gross_sal=basic_sal + TA + DA + HRA;
System.out.println("Gross salary of Employee :"+gross_sal);
}
}
class EmpDetails
{ public static void main(String args[])
{ Salary s=new Salary("Sachin",8000,3000);
s.disp_sal();
s.gross_sal();
}
}

c) Write a simple applet program which display tree concentric circle.


(Logic - 4 marks; Syntax-3marks, applet tag - 1 mark)
[**Note - Any relevant program can be considered**]
Ans:
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint (Graphics g)
{

Page 12 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

g.drawString(Concentric Circle,120,20);
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
/*<applet code=Shapes.class height=300 width=200>
</applet>*/
(OR)

HTML Source:
<html>
<applet code=Shapes.class height=300 width=200>
</applet>
</html>

3. Attempt any four of the following: ( 4 4=16)

a) Define constructor. Explain parameterized constructor with example.


(Definition - 1 mark; parameterized constructor - 1 mark; Example - 2 marks)
Ans:
CONSTRUCTOR
A constructor is a special member which initializes an object immediately upon creation.
It has the same name as class name in which it resides and it is syntactically similar to any
method.
When a constructor is not defined, java executes a default constructor which initializes all
numeric members to zero and other types to null or spaces.
Once defined, constructor is automatically called immediately after the object is created
before new operator completes.
Parameterized constructor: When constructor method is defined with parameters inside it,
different value sets can be provided to different constructor with the same name.
Example
ClassRect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{

Page 13 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

Rect r = new Rect(4,5); // constructor with parameters


Rect r1 = new Rect(6,7);
System.out.println(Area : +(r.length*r.breadth)); // o/p Area : 20
System.out.println(Area : +(r1.length*r1.breadth)); // o/p Area : 42
}
}

b) Write a program to check whether an entered number is prime or not.


(Accept No. from user using command line argument or iopackage - 1 mark; Prime No. logic - 2
marks; Correct Syntax - 1 mark)
[**Note: program using IO package such as BufferedReader or DataInputStream to be
considered for allowing the user to enter the input. **]

Ans:
class PrimeNo
{
public static void main(String args[])
{
intnum=Integer.parseInt(args[0]);
int flag=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}

c) Explain serialization with stream classes.


(Explanation - 3 marks; Example or program - 1 mark)
Ans:

Serialization is the process of writing the state of an object to a byte stream. This is useful when you
want to save the state of your program to a persistent storage area, such as a file. At a later time,
you may restore these objects by using the process of deserialization.

Page 14 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a Java
object on one machine to invoke a method of a Java object on a different machine. An object may
be supplied as an argument to that remote method. The sending machine serializes the object and
transmits it. The receiving machine deserializes it.
Example:
Assume that an object to be serialized has references to other objects, which, inturn, have references
to still more objects. This set of objects and the relationships among them form a directed graph.
There may also be circular references within this object graph. That is, object X may contain a
reference to object Y, and object Y may contain a reference back to object X. Objects may also
contain references to themselves.
The object serialization and deserialization facilities have been designed to work correctly in these
scenarios. If you attempt to serialize an object at the top of an object graph, all of the other
referenced objects are recursively located and serialized. Similarly, during the process of
deserialization, all of these objects and their references are correctly restored.

d) State syntax and explain it with parameters for :


a) drawRect() ii) drawOral()
(Each with syntax and argument - 2 marks)
Ans:

drawRect()
The drawRect() method display an outlined rectangle
Syntax:
voiddrawRect(inttop,intleft,intwidth,int height)
This method takes four arguments, the first two represents the x and y co-ordinates of the top left
corner of the rectangle and the remaining two represent the width and height of rectangle.

Example:
g.drawRect(10,10,60,50);

drawOval()
To draw an Ellipses or circles used drawOval()method.
Syntax:
voiddrawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top and
left and whose width and height are specified by width and height to draw a circle or filled circle,
specify the same width and height the following program draws several ellipses and circle.
Example:
g.drawOval(10,10,50,50);//this is circle
g.drawOval(10,10,120,50);//this is oval

Page 15 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

e) Describe use of super and this with respect to inheritance.


(Inheritance definition - 1 mark; super - 1 mark; this - 1 mark; example - 1 mark)
[**Note: any appropriate example to be considered. **]

Ans:

Using inheritance, you can create a general class that defines traits common to a set of related items.
This class can then be inherited by other, more specific classes, each adding those things that are
unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that
does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a
superclass.
. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword
super.
Superhas two general forms. The first calls the super class constructor. The second is used to
access a member of the superclass that has been hidden by a member of a subclass.
super() is used to call base class constructer in derived class.
Super is used to call overridden method of base class or overridden data or evoked the overridden
data in derived class.
e.g use of super()
class BoxWeightextends Box
{
BowWeight(int a ,intb,int c ,int d)
{
super(a,b,c) // will call base class constructer Box(int a, int b, int c)
weight=d // will assign value to derived class member weight.
}
e.g. use of super.
Class Box
{
Box()
{
}
void show()
{
//definition of show
}
} //end of Box class

Class BoxWeight extends Box


{
BoxWeight()

Page 16 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

{
}
void show() // method is overridden in derived
{
Super.show() // will call base class method
}
}
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked. You can use this anywhere a
reference to an object of the current class type is permitted. To better understand what this refers
to, consider the following version of Box( ): // A redundant use of this. Box(double w, double h,
double d) { this.width = w; this.height = h; this.depth = d; }

Instance Variable Hiding


when a local variable has the same name as an instance variable, the local variable hides the
instance variable. This is why width, height, and depth were not used as the names of the
parameters to the Box( ) constructor inside the Box class. If they had been, then width would have
referred to the formal parameter, hiding the instance variable width.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}

4. A) Attempt any three of the following: 34=12

a) Explain break and continue statement with example.


(Each statement with example - 2 marks)
Ans:
Break:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.
Example:
public class Test
{

Page 17 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

public static void main(String args[])


{
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

Continue:
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled
form skips to the end of the innermost loop's body and evaluates the boolean expression that
controls the loop.
A labeled continue statement skips the current iteration of an outer loop marked with the given
label.
Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

b) Describe use of throws with suitable example.


(Explanation - 2 marks; example - 2 marks)
Ans:

Page 18 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

Throws clause
If a method is capable of causing an exception that it does not handle, it must specify this behavior
so that callers of the method can guard themselves against that exception. You do this by including
a throws clause in the methods declaration. A throws clause lists the types of exception that a
method might throw. General form of method declaration that includes throws clause
Type method-name (parameter list) throws exception list {// body of method} Here exception list
can be separated by a comma.
Eg.
class XYZ
{
XYZ();
{
// Constructer definition
}
void show() throws Exception
{
throw new Exception()
}
}

c) State syntax and describe working of for each version of for loop with one example.
(Explanation with syntax - 2 marks; example - 2 marks.)

Ans:
The For-Each Alternative to Iterators
If you wont be modifying the contents of a collection or obtaining elements in reverse order, then
the for-each version of the for loop is often a more convenient alternative to cycling through a
collection than is using an iterator. Recall that the for can cycle through any collection of objects
that implement the Iterable interface. Because all of the collection classes implement this interface,
they can all be operated upon by the for.
// Use the for-each for loop to cycle through a collection.
// Use a for-each style for loop.

Syntax:

for(data_type variable : array | collection)


{}

Example
ClassForEach
{

Page 19 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

public static void main(String args[])


{
intnums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0; // use for-each style for to display and sum the values
for(int x : nums)
{
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}

d) State syntax and describe any two methods of map class.


(Explanation - 2 marks; syntax - 2 marks)

Ans:
The Map Classes Several classes provide implementations of the map interfaces.
A map is an object that stores associations between keys and values, or key/value pairs. Given a
key, you can find its value. Both keys and values are objects. The keys must be unique, but the
values may be duplicated. Some maps can accept a null key and null values, others cannot.
Methods:
void clear // removes all of the mapping from map
booleancontainsKey(Object key) //Returns true if this map contains a mapping for the specified
key.
Boolean conainsValue(Object value)// Returns true if this map maps one or more keys to the
specified value
Boolean equals(Object o) //Compares the specified object with this map for equality.

b) Attempt any one of the following (16=6 )

a) Write method to set font of a text and describe its parameters.


(Font class - 2 marks; setFont() with parameter - 2 marks example - 2 marks)

Ans:
The AWT supports multiple type fonts emerged from the domain of traditional type setting to
become an important part of computer-generated documents and displays. The AWT provides
flexibility by abstracting font-manipulation operations and allowing for dynamic selection of fonts.

Page 20 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

Fonts have a family name, a logical font name, and a face name. The family name is the general
name of the font, such as Courier. The logical name specifies a category of font, such as
Monospaced. The face name specifies a specific font, such as Courier Italic
To select a new font, you must first construct a Font object that describes that font. One Font
constructor has this general form:
Font(String fontName, intfontStyle, intpointSize)
To use a font that you have created, you must select it using setFont( ), which is defined by
Component.
It has this general form:
VoidsetFont(Font fontObj)

Example
importjava.applet.*;
importjava.awt.*;
importjava.awt.event.*;
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
public void init()
{
f = new Font("Dialog", Font.PLAIN, 12);
msg = "Dialog";
setFont(f);
public void paint(Graphics g)
{
g.drawString(msg, 4, 20);
}
}

b) Describe final method and final variable with respect to inheritance.


(Final method - 3 marks; final variable - 3 marks)

Ans:
final method: making a method final ensures that the functionality defined in this method will
never be altered in any way, ie a final method cannot be overridden.
E.g.of declaring a final method:
final void findAverage() {
//implementation
}
EXAMPLE

Page 21 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

class A

{ final void show()

{
System.out.println(in show of A);
}
}

class B extends A
{

void show() // can not override because it is declared with final


{
System.out.println(in show of B);
}
}

final variable: the value of a final variable cannot be changed. final variable behaves like class
variables and they do not take any space on individual objects of the class.
E.g.of declaring final variable:
final int size = 100;

5. Attempt any two of the following. (28=16)

a) What is thread priority? How thread priority are set and changed? Explain with example.
(Thread Priority - 2 marks; each method - 2 marks; Any Relevant Example - 2 marks)

Ans:
Thread Priority: Threads in java are sub programs of main application program and share the
same memory space. They are known as light weight threads. A java program requires at least one
thread called as main thread. The main thread is actually the main method module which is
designed to create and start other threads in java each thread is assigned a priority which affects the
order in which it is scheduled for running. Thread priority is used to decide when to switch from
one running thread to another. Threads of same priority are given equal treatment by the java
scheduler. Thread priorities can take value from 1-10. Thread class defines default priority constant
values as
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10
1. setPriority:
Syntax:public void setPriority(int number);

Page 22 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

This method is used to assign new priority to the thread.


2. getPriority:
Syntax:public intgetPriority();
It obtain the priority of the thread and returns integer value.
Example:
class clicker implements Runnable
{
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p)
{
t = new Thread(this);
t.setPriority(p);
}
public void run()
{
while (running)
{
click++;
}
}
public void stop()
{
running = false;
}
public void start()
{
t.start();
}
}
class HiLoPri
{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
}

Page 23 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try
{
hi.t.join();
lo.t.join();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}

b) Write a program to input name and age of person and throws user defined exception, if
entered age is negative.
(Declaration of class with proper members and constructor - 4 marks; statement for throwing
exception and main method - 4 marks)
[**Note: Any other relevant program can be considered**]

Ans:
import java.io.*;
class Negative extends Exception
{
Negative(String msg)
{
super(msg);
}
}
class Negativedemo
{
public static void main(String ar[])
{
int age=0;
String name;
BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in));

Page 24 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

System.out.println("enter age and name of person");


try
{
age=Integer.parseInt(br.readLine());
name=br.readLine();
{
if(age<0)
throw new Negative("age is negative");
else
throw new Negative("age is positive");
}
}
catch(Negative n)
{
System.out.println(n);
}
catch(Exception e)
{
}

c) Explain <applet> tag with major attributes only. State purpose of get Available Font Family
Name () method of graphics environment class.
(Syntax - 2 marks; any 4 attributes of Applet tag - 4 marks; purpose -2 marks)

Ans:
The HTML APPLET Tag and attributes
The APPLET tag is used to start an applet from both an HTML document and from an applet
viewer.
The syntax for the standard APPLET tag:
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]>
[< PARAM NAME = AttributeNameVALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
1. CODEBASE is an optional attribute that specifies the base URL of the applet code or the
directory that will be searched for the applets executable class file.

Page 25 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

2. CODE is a required attribute that give the name of the file containing your applets
compiled class file which will be run by web browser or appletviewer.
3. ALT: Alternate Text. The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.
4. NAME is an optional attribute used to specifies a name for the applet instance.
5. WIDTH AND HEIGHT are required attributes that give the size(in pixels) of the applet
display area.
6. ALIGN is an optional attribute that specifies the alignment of the applet.
The possible value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE, and ABSBOTTOM.
7. VSPACE AND HSPACE attributes are optional, VSPACE specifies the space, in pixels,
about and below the applet. HSPACE VSPACE specifies the space, in pixels, on each side
of the applet
8. PARAM NAME AND VALUE:
The PARAM tag allows you to specifies applet- specific arguments in an HTML page
applets access there attributes with the get Parameter()method.THE

Purpose of getAvailableFontFamilyName() method:


It returns an array of String containing the names of all font families in this Graphics Environment
localized for the specified locale
Syntax:

public abstract String[] getAvailableFontFamilyNames(Locale l)

Parameters:
l - a Localeobject that represents a particular geographical, political, or cultural region. Specifying
null is equivalent to specifying Locale.getDefault().

Or
String[] getAvailableFontFamilyNames()
It will return an array of strings that contains the names of the available font families

Page 26 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

6. Attempt any four of the following: (44 =16)

a) Define a class item having data member code and price. Accept data for one object and
display it.
(Correct Program - 4 marks)
[**Note: Input without BufferedReader or any IOStream to be considered or argument to be
considered. **]
Ans:
import java.io.*;
class Item_details
{
int code;
float price;
Item_details()
{
code=0;
price=0;
}
Item_details(int e,float p)
{
code=e;
price=p;
}
void putdata()
{
System.out.println("Code of item :"+code);
System.out.println("Price of item:"+price);
}
public static void main(String args[]) throws IOException
{
intco;floatpr;
BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter code and price of item");
co=Integer.parseInt(br.readLine());
pr=Float.parseFloat(br.readLine());
Item_detailsobj=new Item_details(co,pr);
obj.putdata();
}
}

Page 27 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

b) What is use of Array list class? State any two methods with their use from ArrayList.
(Use - 2 marks; any 2 methods - 1 mark each)

Ans:
Use of ArrayList class:
1. ArrayListsupports dynamic arrays that can grow as needed.
2. ArrayListis a variable-length array of object references. That is, an ArrayListcan
dynamically increase or decrease in size. Array lists are created with an initial size. When
this size is exceeded, the collection is automatically enlarged. When objects are removed,
the array may be shrunk.

Methods of ArrayList class :


1. void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index
>size()).
2. boolean add(Object o)
Appends the specified element to the end of this list.
3. booleanaddAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that
they are returned by the specified collection's iterator. Throws NullPointerException if the
specified collection is null.
4. booleanaddAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the specified
position. Throws NullPointerException if the specified collection is null.
5. void clear()
Removes all of the elements from this list.
6. Object clone()
Returns a shallow copy of this ArrayList.
7. boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and
only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8. void ensureCapacity(intminCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at
least the number of elements specified by the minimum capacity argument.
9. Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >=
size()).
10. intindexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if the List
does not contain this element.

Page 28 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

11. intlastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list
does not contain this element.
12. Object remove(int index)
Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13. protected void removeRange(intfromIndex, inttoIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.
14. Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >=
size()).
15. int size()
Returns the number of elements in this list.
16. Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
17. Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime
type of the returned array is that of the specified array.
18. void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.

c) Design an Applet program which displays a rectangle filled with red color and message as
Hello Third year Students in blue color.
(Correct Program - 4 marks)

Ans:
import java.awt.*;
import java.applet.*;
public class DrawRectangle extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(10,60,40,30);
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}

Page 29 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

/*
<applet code="DrawRectangle.class" width="350" height="300">
</applet> */

d) Design a package containing a class which defines a method to find area of rectangle. Import
it in java application to calculate area of a rectangle.
(Package declaration - 2 marks; Usage of package - 2 marks)

Ans:
package Area;
public class Rectangle
{
doublelength,bredth;
public doublerect(float l,float b)
{
length=l;
bredth=b;
return(length*bredth);
}
}
import Area.Rectangle;
class RectArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle( );
double area=r.rect(10,5);
System.out.println(Area of rectangle= +area);
}
}

Page 30 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer

Subject Code: 17515 Subject Name: Java Programming

e) Define a class having one 3-digit number as a data member. Initialize and display reverse of
that number.
(Logic - 2 marks; Syntax - 2 marks)
[**Note: Any other relevant logic can be considered**]

Ans:
class reverse
{
public static void main(String args[])
{
intnum = 253;
intremainder, result=0;
while(num>0)
{
remainder = num%10;
result = result * 10 + remainder;
num = num/10;
}
System.out.println("Reverse number is : "+result);
}
}

Page 31 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the candidates answers and model
answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant
answer based on candidates understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.

Q.N Sub Answer Marking


o. Q.N. Scheme
1. (A) Attempt any THREE of the following: 12
(a) How java is different than other programming language? 4M
Ans. Java is different from the other programming languages with respect
to the following features:
i. Java has a very rich API which provides a huge number of Any 4
features. points-
ii. Java is an object oriented language:- It follows all the principles 1M
of object oriented programming namely inheritance, each
polymorphism and abstraction. Multiple inheritance is possible
with the concept of interface.
iii. Java is both compiled and interpreted:- Most of the programming
languages either uses a compiler or an interpreter. Java programs
are to be compiled to get an intermediate byte code (a.class file)
and then interpreted making it more secure and platform
independent.
iv. Java is secure:
Java does not use pointer
Java programs run inside a virtual machine
Classloader adds security by separating the package for the
classes of the local file system from those that are imported
from network sources.

Page No. 1/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

Bytecode Verifier checks the code fragments for illegal code


that can violate access right to objects.
Security Manager determines what resources a class can access
such as reading and writing to the local disk

V. Robust: Java uses strong memory management. The lack of


pointers avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking
mechanism in java.

vi. Architecture-neutral: There is no implementation dependent


features e.g. size of primitive types is fixed.

Vii. Portable: We may carry the java bytecode to any platform.

Viii Distributed
We can create distributed applications in java. RMI and EJB are used fo
applications. We may access files by calling the methods from any mac

ix. Multi-threaded: A thread is like a separate program, executing


concurrently. We can write Java programs that deal with many tasks
at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web
applications etc.
(b) What is scope of variable? Give example of class variable, 4M
instance variable and local variable.
Ans. The scope of a variable defines the section of the code in which the
variable is visible. The variables can be class variable which is Definitio
associated with the class and is shared with all the instances of the n of
class or an instance variable which is declared in a class and each scope
instance has a separate copy or a local variable which is defined in a 1M
block or a method. As a general rule, variables that are defined within
a block are not accessible outside that block. The lifetime of a
variable refers to how long the variable exists before it is destroyed.
Eg: A
class VariableTypes program
{ or
static int a = 0; //class variable suitable
int b = 0; // instance variable example
VariableTypes() should

Page No. 2/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

{ be
a++; consider
b++; ed - 3M
int c = 0; //local variable
c++;
System.out.println("In constructor printing a: "+a);//will be accessed (class,
System.out.println("In constructor printing b: "+b);//will be accessed instance
System.out.println("In constructor printing c: "+c);//will be accessed and
} local
public static void main(String ar[]) variable
{ s should
VariableTypes s = new VariableTypes(); be
VariableTypes s1 = new VariableTypes(); declared
VariableTypes s2 = new VariableTypes(); and
System.out.println("in main printing a: "+VariableTypes.a);//will be marked
accessed clearly
System.out.println("in main printing b: "+s.b);//will be accessed each
System.out.println("in main printing c "+s.c);//will not be accessed 1M)
because this is a local variable declared in constructor
}
}
(c) What is an exception? How it is handled? Give suitable example. 4M
(Note: Any suitable example should be considered)
Ans. An exception is an event, which occurs during the execution of a Definitio
program, that disrupts the normal flow of the program execution. n of
exceptio
An exception handler will handle the exception using the keywords n 1M
i. try
ii. catch Keyword
iii. throw s 1M
iv. throws
v. finally
Eg:
import java.io.*;
class ExceptionHandling
{
int num1, num2, answer;
void acceptValues()
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try

Page No. 3/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

{
System.out.println("Enter two numbers");
num1 = Integer.parseInt(bin.readLine());
num2 = Integer.parseInt(bin.readLine()); Example
} catch(IOExceptionie)
2M
{
System.out.println("Caught IOException"+ie);
} catch(Exception e)
{
System.out.println("Caught the exception "+e);
}
}
void doArithmetic()
{
acceptValues();
try
{
answer = num1/num2;
System.out.println("Answer is: "+answer);
}
catch(ArithmeticException ae)
{
System.out.println("Divide by zero"+ae);
}
}
public static void main(String a[])
{
ExceptionHandling e = new ExceptionHandling();
e.doArithmetic();
}
}
(d) Explain methods of map class and set class in jdk frame work. 4M
Ans. The methods declared in the interface Map are:
void clear()-Removes all of the mappings from this map (optional
operation).
Any 2
boolean containsKey(Object key)-Returns true if this map contains a methods
mapping for the specified key. of map
and any
boolean containsValue(Object value)-Returns true if this map maps
2
one or more keys to the specified value.
methods
Set<Map.Entry<K,V>> entrySet() - Returns a Set view of the of set
mappings contained in this map. 2M
each

Page No. 4/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

boolean equals(Object o) - Compares the specified object with this


map for equality.
get(Object key) - Returns the value to which the specified key is
mapped, or null if this map contains no mapping for the key.
int hashCode()-Returns the hash code value for this map.
boolean isEmpty() - Returns true if this map contains no key-value
mappings.
Set<K>keySet() -Returns a Set view of the keys contained in this
map
remove(Object key) -Removes the mapping for a key from this map
if it is present (optional operation).
Int size() - Returns the number of key-value mappings in this map.
Collection<V>values() - Returns a Collection view of the values
contained in this map.

The methods declared in the Set interface are:


boolean add(E e)-Adds the specified element to this set if it is not
already present
boolean addAll(Collection<? extends E> c) Adds all of the elements
in the specified collection to this set if they're not already present
(optional operation).
void clear()-Removes all of the elements from this set (optional
operation).
boolean contains(Object o)-Returns true if this set contains the
specified element.
boolean containsAll(Collection<?> c)-Returns true if this set
contains all of the elements of the specified collection.
boolean equals(Object o)-Compares the specified object with this set
for equality.
int hashCode()-Returns the hash code value for this set.
boolean isEmpty()-Returns true if this set contains no elements.
Iterator<E>iterator()-Returns an iterator over the elements in this
set.
boolean remove(Object o)-Removes the specified element from this
set if it is present (optional operation).
boolean removeAll(Collection<?> c)-Removes from this set all of its

Page No. 5/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

elements that are contained in the specified collection (optional


operation).
boolean retainAll(Collection<?> c)-Retains only the elements in this
set that are contained in the specified collection (optional operation).
int size()-Returns the number of elements in this set (its cardinality).
Object[] toArray()-Returns an array containing all of the elements in
this set.
1. (B) Attempt any ONE of the following: 1 X 6 =6
(a) Create a class Rectangle that contains length and width as 6M
data members. From this class drive class box which has
additional data member depth. Class Rectangle consists of a
constructor and an area ( ) function. The derived Box class have
a constructor and override function named area ( ) which returns
surface area of Box and a volume ( ) function. Write a java
program calling all the member function.
(Note: Any logic may be considered)
Ans. import java.io.*;
class Rectangle
{
int length, width; Correct
Rectangle(int length, int width) logic
{ 3M,
this.length = length; Correct
this.width = width; Syntax
} 3M
int area()
{
return length*width;
}
}
class Box extends Rectangle
{
int depth;
Box(int length, int width, int depth)
{
super(length, width);
this.depth = depth;
}
int area()
{
return 2*(length*width+width*depth+depth*length);

Page No. 6/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

}
int volume(int l, int w, int d)
{
return l*w*d;
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter the length, width and depth");
int l = Integer.parseInt(bin.readLine());
int w = Integer.parseInt(bin.readLine());
int h = Integer.parseInt(bin.readLine());
Box b = new Box(l,w,h);
Rectangle r = new Rectangle(l,w);
System.out.println("Area of the Rectangle is :"+r.area());
System.out.println("Area of the Box is :"+b.area());
System.out.println("volume of the Rectangle is
:"+b.volume(l,w,h));
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
(b) Write a java program. 6M

Ans. import java.io.*;


class Student
{
String name;

Page No. 7/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

int roll_no;
double m1, m2; Correct
Student(String name, int roll_no, double m1, double m2) Syntax
{ 3M,
this.name = name; Correct
this.roll_no = roll_no; logic 3M
this.m1 = m1;
this.m2 = m2;
}
}
interface exam {
public void per_cal();
}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)
{
super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of
the student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());

Page No. 8/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
2. Attempt any TWO of the following: 16
(a) Write a program to create a class Account having variable accno, 8M
accname and balance. Define deposite ( ) and withdraw( )
methods. Create one object of class and perform the operation.
Ans. import java.io.*;
class Account
{
int accno;
String accname;
double balance, new_bal; Correct
Account(int accno, String accname, double balance) logic
{ 5M,
this.accno = accno; Correct
this.accname = accname; syntax
this.balance = balance; 3M
}
void deposite(double deposit_amount)
{
balance = balance+deposit_amount;
System.out.println("Your new available balance is"+balance);
}
void withdraw(double amount)
{
if(balance > amount)
{
balance = balance-amount;
System.out.println("Your current balance"+balance);
}
else if( balance == amount)
{
System.out.println("Your current balance is "+balance+". Your

Page No. 9/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

minimum balance should be 1000. Hence cannot withdraw.");


}
else
{
System.out.println("Insufficient balance");
}
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
Account a;
double amount, bal;
try
{
System.out.println("Enter the account name account number and
balance");
String a_name = bin.readLine();
int a_no = Integer.parseInt(bin.readLine());
bal = Double.parseDouble(bin.readLine());
a = new Account(a_no, a_name, bal);
System.out.println("Enter\n 1 for depositing \n 2 for withdrawal");
int option = Integer.parseInt(bin.readLine());
switch(option)
{
case 1:
System.out.println("Enter the amount to deposite");
amount = Double.parseDouble(bin.readLine());
a.deposite(amount);
break;
case 2:
System.out.println("Enter the amount to withdraw");
amount = Double.parseDouble(bin.readLine());
a.withdraw(amount);
break;
default:
System.out.println("Enter a valid option");
break;
}
} catch(Exception e)
{

Page No. 10/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

System.out.println("Exception caught"+e);
}
}
}
(b) How multiple inheritance is achieved in java? Explain with 8M
proper program.
(Note: Any proper program should be considered)
Inheritance is a mechanism in which one object acquires all the
Ans. properties and behaviors of parent object. The idea behind inheritance
in java is that new classes can be created that are built upon existing Explana
classes. tion 3M
Multiple inheritance happens when a class is derived from two or
more parent classes. Java classes cannot extend more than one parent
classes, instead it uses the concept of interface to implement the
multiple inheritance.
It contains final variables and the methods in an interface are abstract.
A sub class implements the interface. When such implementation
happens, the class which implements the interface must define all the
methods of the interface. A class can implement any number of
interfaces.
Eg:
import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2; Example
Student(String name, introll_no, double m1, double m2) 5M
{ (Correct
this.name = name;
syntax
this.roll_no = roll_no;
this.m1 = m1;
2M,
this.m2 = m2; logic
} 3M)
}
interface exam
{
public void per_cal();
}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)

Page No. 11/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

{
super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of the student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());
double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
}
catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
(c) Write an applet program that accepts two input, strings using 8M
<Param> tag and concatenate the strings and display it in status
window.
Ans. import java.applet.*;
importjava.awt.*; Correct
/*<applet code = AppletProgram.class height = 400 width = 400> logic
<param name = "string1" value = "Hello"> 5M,
<param name = "string2" value = "Applet">
Correct
</applet>*/
public class AppletProgram extends Applet
Syntax
{ 3M

Page No. 12/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

String str1;
public void init()
{
str1 = getParameter("string1").concat(getParameter("string2"));
}
public void paint(Graphics g)
{
showStatus(str1);
}
}
3. Attempt any FOUR of following: 16
(a) How garbage collection is done in Java? Which methods are used 4M
for it?
Ans. Garbage collection is a process in which the memory allocated to Garbage
objects, which are no longer in use can be freed for further use. Collectio
Garbage collector runs either synchronously when system is out of n
memory or asynchronously when system is idle. Explana
In Java it is performed automatically. So it provides better memory tion:2M
management.

Method used for Garbage Collection:


The java.lang.Object.finalize() is called by garbage collector on an
object when garbage collection determines that there are no more Method
reference to the object. :2M
A subclass override the finalize method to dispose of system
resources or to perform other cleanup.
General Form :
protected void finalize()
{ // finalization code here
}
(b) What is the difference between vector and array? Give suitable 4M
example.
Ans. Sr. Vector Array
No
1 Vector can grow and Array cant grow and shrink Any 3
shrink dynamically. dynamically. Differen
2 Vector can hold dynamic Array is a static list of primitive ce points
list of objects or data types. : 1M
primitive data types. each ,
3 Vector class is found in Array class is found in java.lang Example
java.util package (default) package. :1M

Page No. 13/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

4 Vector can store Array can store elements of


elements of different data same data type.
types.
5 Vector class provides For accessing element of an
different methods for array no special methods are
accessing and managing available as it is not a class, but
vector elements. a derived type.
6 Syntax : Syntax :
Vector objectname=new datatype[] arrayname=new
Vector(); datatype[size];
Exa Vector v1=new Vector(); int[] myArray={22,12,9,44};
mpl
e
(c) Write a program to compute the sum of the digits of a given 4M
integer numbers.
(Note: Direct Input or User Defined Input shall be considered &
Any Other Logic shall be considered)
Ans. class Sumdigit
{
public static void main(String args[]) Logic :
{ 2M,
int num = Integer.parseInt(args[0]); //takes argument Syntax :
as commandline 2M
int remainder, result=0;
while(num>0)
{
remainder = num%10;
result = result + remainder;
num = num/10;
}
System.out.println("Sum of digit of number is : "+result);
}
}
(d) Explain following methods: 4M
(i) drawrect ( )
(ii) getfont ( )
Ans.
(i) drawrect ( ):
Syntax: void drawRect(int x, int y, int width, int height) drawRec
Used to draw a rectangle with upper left corner at (x,y) and with t
specified width and height. method:

Page No. 14/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

Syntax
(ii) getFont ( ): 1M,
public static Font getFont(String nm) Use- 1M
Returns a font from the system properties list.
Parameters: getFont
nm - the property name. method
:Syntax
public static Font getFont(String nm, Font font) - 1M,
Returns the specified font from the system properties list. Use - 1,
Parameters:
nm - the property name. Any one
font - a default font to return if property 'nm' is not defined. method
(e) Write a program that will count no. of characters in a file. 4M
(Note: Any Other Logic shall be considered)
Ans. import java.io.*;
class CountChars Logic :
{ 2M,
public static void main(String args[]) Syntax :
{ 2M
try
{
FileReader fr=new FileReader("a.txt");
int ch; int c=0;
while((ch=fr.read())!=-1)
{
c++; //increase character count
}
fr.close();
System.out.println(c);
}
catch(Exception e) {}
}
}
4. (A) Attempt any THREE of following: 12
(a) In what ways does a switch statement differ from an if 4M
statements?
Ans. Sr. Switch If
No.
1 The switch statement is The if statement is used to
used to select among select among two alternatives.
multiple alternatives

Page No. 15/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

2 It uses all primitive It uses a Boolean expression


datatypes except boolean to decide which alternative
expression to determine should be executed. Any 4
which alternative should be Differen
executed. ce points
3 Switch can not evaluate In if statement you can : 1M
complex expressions. evaluate complex expressions each
4 Switch provides multiway Multiway execution is not
execution available
5 General form: i)Simple if statementGeneral
switch(expression) form is
{ if (test condition)
case value1: {
block 1; statement block;
break; }
case value2: statement n;
block 2; ii)The ifelse statement:
break; General form is
. if (test condition)
. {
. True-statement block;
default: }
default block; else
break; {
} False-statement block;
statement n; }

(b) Write a program to find the no. and sum of all integers greater 4M
than 100 and less than 200 that are divisible by 7.
(Note: Any other Logic shall be considered)
Ans.
class SumInt
{ Logic :
public static void main(String args[]) 2M,
{ Syntax :
double sum=0; 2M
int numcnt=0;
for(int i=101;i<200;i++)
{
if(i%7==0)
{

Page No. 16/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

sum=sum+i;
numcnt++;
}
}
System.out.println(" No of elements : "+numcnt);
System.out.println(" Sum of elements : "+sum);
}
}
(c) What is synchronization? When do we use it? Explain 4M
synchronization of two threads.
(Note: Any other program shall be considered)
Ans. Synchronization :-
When two or more threads need access to a shared resource, they Synchro
need some way to ensure that the resource will be used by only one nization:
thread at a time. The process by which this is achieved is called 1M
synchronization.

Synchronization used when we want to -


1) prevent data corruption. Any one
2) prevent thread interference. Use:1M
3) Maintain consistency If multiple threads require an access to
an object

Program based on synchronization:


class Callme {
void call(String msg)
{ Program
System.out.print("[" +msg); :2M
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
System.out.print("]");
}
}
class Caller implements Runnable
{

Page No. 17/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

String msg;
Callme target;
Thread t;
public Caller(Callmetarg,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{
Callme target=new Callme();
Caller ob1=new Caller(target,"Hello");
Caller ob2=new Caller(target,"Synchronized");
try
{
ob1.t.join();
ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}
(d) Draw the hierarchy of Writer stream classes, and hierarchy of 4M
Reader stream classes.
Ans.

Page No. 18/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

Correct
Hierarc
hy of
each
Class :
2M

Page No. 19/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

4. (B) Attempt any ONE of following: 6


(a) What are the access control parameters? Explain the concept 6M
with suitable example.
Ans. Java provides a number of access modifiers to set access levels for Any 4
classes, variables, methods and constructors. paramet
1) Default Access Modifier - No keyword: ers
A variable or method declared without any access control modifier is explanat
available to any other class in the same package. Visible to all class in ion: 1M
its package. each,
E.g: Example
Variables and methods can be declared without any modifiers, as in : 1/2M
the following Examples: each
String version = "1.5.1";
boolean processOrder()
{
return true;
}
2) Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can
only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.
Using the private modifier is the main way that an object
encapsulates itself and hide data from the outside world.
Examples:
private String format;
private void get() { }

3) Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be
accessed from any other class. Therefore fields, methods, blocks
declared inside a public class can be accessed from any class
belonging to the Java Universe.
However if the public class we are trying to access is in a different
package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a
class are inherited by its subclasses.
Examples:
public double pi = 3.14;
public static void main(String[] arguments)
{

Page No. 20/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

// ...
}

4) Protected Access Modifier - protected:


Variables, methods and constructors which are declared protected in a
super class can be accessed only by the subclasses in other package or
any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however
methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method
or variable, while preventing a nonrelated class from trying to use it.
E.g
The following parent class uses protected access control, to allow its
child class override
protected void show( )
{ }

5) private protected: Variables, methods which are declared


protected in a super class can be accessed only by the subclasses in
same package. It means visible to class and its subclasses.
Example:
private protected void show( )
{ }
(b) Describe following methods of applet: 6M
(i) suspend ( ) (ii) resume ( ) .
(iii) sleep ( ) (iv) notify ( )
(v) stop ( ) (vi) wait ( )
(Note: consider these Methods as Thread Methods)
Ans. i) suspend( ): Each
syntax : public void suspend() method
This method puts a thread in suspended state and can be resumed use :1M
using resume()method.

ii) resume():
syntax : public void resume()
This method resumes a thread which was suspended using suspend()
method.

iii)sleep():
syntax: public static void sleep(long millis) throws

Page No. 21/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

InterruptedException
We can put a thread to sleep for a specified time period using
sleep(time) where time is in ms. It reenters the runnable state as soon
as period has elapsed /over.

iv)notify():
syntax: public final void notify()
Notify() method wakes up the first thread that called wait() on the
same object.

v) stop():
syntax: void stop()
Used to kill the thread. It stops thread.

vi) wait():
syntax : public final void wait()
This method causes the current thread to wait until another thread
invokes the notify() method or the notifyAll() method for this object.
5. Attempt any TWO of following: 16
(a) Write a thread program for implementing the Runnable 8M
interface.
Ans. //program to print even numbers from 1 to 20 using Runnable Class
Interface class mythread implements Runnable impleme
{ nting
public void run() Runnabl
{ e 2M
System.out.println("Even numbers from 1 to 20 : ");
for(int i= 1 ; i<=20; i++) Correct
{ run()
if(i%2==0) method
System.out.print(i+ " "); 2M
}
} Proper
} use of
class test Thread
{ class 2M
public static void main(String args[])
{
mythreadmt = new mythread(); Correct
Thread t1 = new Thread(mt); Logic
t1.start(); and

Page No. 22/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

} Syntax
} 2M
(b) Define an exception called No match Exception that is thrown 8M
when a string is not equal to MSBTE. Write program.
Ans. //program to create user defined Exception No Match Exception
import java.io.*;
class NoMatchException extends Exception For
{ subclass
NoMatchException(String s) of
{ Exceptio
super(s); n:2M
}
}
class test1 Correct
{ use of
public static void main(String args[]) throws IOException try and
{ catch:
BufferedReader br= new BufferedReader(new 2M
InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine(); Correct
try Logic:
{ 2M
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else Correct
System.out.println("Strings are equal"); syntax :
} 2M
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}
(c) Write a program to display a string concentric circles using 8M
font Arial size as 12 and style as bold + italic and display three
concentric circles with different colors on the applet.
Ans. //program to display three concentric circles filled in three colors.
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet

Page No. 23/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

{
String str=""; Use of
public void init() proper
{ methods
Font f= new Font("Arial",Font.BOLD|Font.ITALIC,12); for
setFont(f); displayi
} ng
public void paint(Graphics g) message
{ and
g.drawString("cocentric circles",130,100); circles:
3M
// for drawing three concentric circles filled with three colors.
g.setColor(Color.red); correct
g.fillOval(150,150,100,100); Logic:
2M
g.setColor(Color.yellow);
g.fillOval(160,160,80,80); Correct
Syntax :
g.setColor(Color.green); 2M
g.fillOval(170,170,60,60);
}
}
//Applet tag Applet
/*<Applet code=myapplet width=200 height=200> tag:1M
</Applet>
*/
6. Attempt any FOUR of the following: 16
(a) What is the use of new operator? Is it necessary to be used 4M
whenever object of the class is created? Why?
Ans.
1) Use :
new operator is used to dynamically allocate memory to the object of Use 2M
the class. It is the operator which is used to create usable instance of
the class.
It is generally used along with the constructor of the class so as to get
memory allocated to the object.
2) It is necessary to use new operator whenever an object requires Necessit
memory allocation after creation. Otherwise object in the form of y : 2M
reference is created which will point to Null, i.e. with no allocated
space in memory.

Page No. 24/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

(b) Perform following string/ string buffer operations, write java 4M


program.
(i) Accept a password from user
(ii) Check if password is correct then display Good, else
display Wrong
(iii) Display the password in reverse order.
(iv) Append password with welcome
Ans. import java.io.*;
class passwordtest
{
public static void main(String args[]) Correct
{ logic
int i; and
BufferedReaderbr = new BufferedReader(new correct
InputStreamReader(System.in)); syntax
String pass1="abc123"; used for
String passwd=""; each
option:
//Accepting password from user 1M
try
{
System.out.println("enter password :");
passwd=br.readLine();
}
catch(Exception e)
{}

// compare two passwords


int n= passwd.compareTo(pass1);
if(n==0)
System.out.println("Good");
else
System.out.println("Wrong");

//Reversing password
StringBuffer s1= new StringBuffer(passwd);
System.out.println("Reverse of entered password :");
System.out.println(s1.reverse());

//Append welcome to password


System.out.println("Welcome appended to password :

Page No. 25/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

"+s1.append("Welcome"));
}
}
(c) What is : 4M
(i) AddElement() &
(ii) ElementAt() command in vector
Ans.
(i) addElement() : Each
It is a method from Vector Class. method
It is used to add an object at the end of the Vector. :2M
Syntax :
addElement(Object);
Example :
If v is the Vector object ,
v.addElement(new Integer(10));
It will add Integer object with value 10 at the end of the Vector object
v.

(ii) elementAt() command in vector:


It is a Vector class method.
It is used to access element or object from a specified position in a
vector.
Syntax :
elementAt(index);
Example :
If v is the Vector object ,
v.elementAt(3);
It will return element at position 3 from Vector object v.
(d) What is interface? How to add interfaces to packages. 4M
Ans. Interface:
1) It is similar to class but mainly used to define abstraction in Java
2) It contains all abstract methods and final variables inside it. Interfac
3) Interfaces have to be implemented by a class. e : 1M
4) It is mainly used to achieve multiple inheritance in Java.

To add interface to packages:


1) Begin the program with package < package name>;
2) Declare public interface Steps to
3) Declare final variables and abstract methods required. add
4) Save and compile the file. interface
5) Create a folder with exactly same name as package name. to

Page No. 26/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

6) Copy class of package inside this folder. package


7) Create java source code which requires interface from package OR an
8) Import the created package inside it and use. example
may be
OR consider
ed : 3M
A) Creation of package containing interface
package mypack;
public interface test
{
public int x=5;
public abstract void display();
}
B) Importing package inside another java code
import mypack.test;
class test1 implements test
{
public void display()
{
System.out.println("x from interface :"+x);
}
public static void main(String args[])
{
test1 t1 = new test1();
t1.display();
}
}
(e) Write java program to display triangle filled with red colour. 4M
Ans. //program to display triangle filled with red color.
import java.awt.*; Proper
import java.applet.*; use of
public class myapplet extends Applet method
{ for
public void paint(Graphics g) triangle:
{ 2M
int x[]={100,150,120,100};
int y[]={100, 130, 150,100}; correct
g.setColor(Color.red); logic 1M
g.fillPolygon(x,y,3);
} Correct
} syntax

Page No. 27/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

WINTER 2016 EXAMINATION


Model Answer Subject Code: 17515

/*<Applet code=myapplet width=200 height=200> 1M


</Applet>
*/
(f) Write a java program to copy contents of one file to another file. 4M
Ans. import java.io.*;
class filecopy
{
public static void main(String args[]) throws IOException
{ Correct
FileInputStream in= new FileInputStream("input.txt"); //FileReader Logic
class can be used 2M
FileOutputStream out= new FileOutputStream("output.txt");
//FileWriter class can be used
int c=0;
try
{ Correct
while(c!=-1) syntax
{ 2M
c=in.read();
out.write(c);
}
System.out.println("File copied to output.txt....");
}
finally
{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
}
}

Page No. 28/28


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in
the figure. The figures drawn by candidate and model answer may vary. The examiner may
give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed
constant values may vary and there may be some difference in the candidates answers and
model answer.
6) In case of some questions credit may be given by judgement on part of examiner of
relevant answer based on candidates understanding.
7) For programming language papers, credit may be given to any other program based
one quivalent concept.

Q.N Sub Answer Marking


o. Q.N. Scheme
1. (A) Attempt any THREE of the following: 3 x 4= 12
(a) State and explain any four features of Java. 4M
(Note: Any four may be considered)
Ans. i. Java is an object oriented language:- It follows all the principles
of object oriented programming namely inheritance, polymorphism 1M for
and abstraction. Multiple inheritance is possible with the concept of each
interface feature
ii. Java is both compiled and interpreted:- Most of the programming
languages either uses a compiler or an interpreter. Java programs
are to be compiled to get an intermediate byte code (a .class file)
and then interpreted making it more secure and platform
independent.
iii.Java is secure:
Java does not use pointer.
Java programs run inside a virtual machine
Classloader adds security by separating the package for the
classes of the local file system from those that are imported
from network sources
Bytecode Verifier checks the code fragments for illegal code

Page 1 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

that can violate access right to objects


Security Manager determines what resources a class can
access such as reading and writing to the local disk

iv. Robust: Java uses strong memory management. The lack of


pointers avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking
mechanism in java
v. Architecture-neutral: There is no implementation dependent
features e.g. size of primitive types is fixed
vi. Platform independent and Portable: java byte code can be carried
to any platform
vii. Distributed: Distributed applications can be created in java.
RMI and EJB are used for creating distributed applications. We
may access files by calling the methods from any machine on the
internet
viii. Multithreaded: A thread is like a separate program, executing
concurrently. We can write Java programs that deal with many
tasks at once by defining multiple threads. The main advantage
of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important
for multi-media, Web applications etc.
(b) Write any four methods of file class with their use. 4M
(Note: Any four methods may be considered)
Ans. public String getName()
Returns the name of the file or directory denoted by this abstract
pathname.

public String getParent()


Returns the pathname string of this abstract pathname's parent,
1M each
or null if this pathname does not name a parent directory.
for method
and use
public String getPath()
Converts this abstract pathname into a pathname string.

public boolean isAbsolute()


Tests whether this abstract pathname is absolute.

public String getAbsolutePath()


Returns the absolute pathname string of this abstract pathname.

Page 2 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

public boolean canRead()


Tests whether the application can read the file denoted by this
abstract pathname.

public boolean canWrite()


Tests whether the application can modify the file denoted by this
abstract pathname.

public boolean exists()


Tests whether the file or directory denoted by this abstract
pathname exists.

public boolean isDirectory()


Tests whether the file denoted by this abstract pathname is a
directory.

public boolean isFile()


Tests whether the file denoted by this abstract pathname is a
normal file.

public boolean isHidden()


Tests whether the file named by this abstract pathname is a hidden
file

public long lastModified()


Returns the time that the file denoted by this abstract pathname
was last modified.

public long length()


Returns the length of the file denoted by this abstract pathname

public boolean createNewFile() throws IOException


Atomically creates a new, empty file named by this abstract
pathname if and only if a file with this name does not yet exist

public boolean delete()


Deletes the file or directory denoted by this abstract pathname

public String[] list()


Returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname.
public boolean mkdir()
Creates the directory named by this abstract pathname.

Page 3 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

public boolean renameTo(File dest)


Renames the file denoted by this abstract pathname.

public boolean setLastModified(long time)


Sets the last-modified time of the file or directory named by this
abstract pathname.

public boolean setReadOnly()


Marks the file or directory named by this abstract pathname so
that only read operations are allowed

public boolean setWritable(boolean writable, boolean ownerOnly)


Sets the owner's or everybody's write permission for this abstract
pathname.

public boolean equals(Object obj)


Tests this abstract pathname for equality with the given object

public String toString()


Returns the pathname string of this abstract pathname.
(c) Explain any two relational operators in Java with example. 4M
Ans. The relational operators in java are:
< - This operator is used to check the inequality of two expressions. It
returns true if the first expression is less than the second expression else 1M each
returns false. for listing
if(Exp1< exp2) {
and
do this
} else {
explainin
do this g any two
} relational
operators
>-This operator is also used to check the inequality of two expressions. It
returns true 1M each
if the first expression is greater than the second one else returns false. for
if(Exp1> exp2) { program
do this
} else {
do this
}

<=- This operator returns true if the first expression is less than or equal
to the second expression else returns false.

Page 4 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

if(Exp1< =exp2) {
do this
} else {
do this
}

>=-This operator returns true if the first expression is greater than or


(2M for
equal to the second expression else returns false. one
if(Exp1>= exp2) { program
do this with both
} else { the
do this operators)
}

= =-This operator returns true if the values of both the expressions are
equal else returns false.
if(Exp1= = exp2) {
do this
} else {
do this
}

!= - This operator returns true if the values of both the expressions are
not equal else returns false.
if(Exp1!= exp2) {
do this
} else {
do this
}

Example:
class RelationalOps {
public static void main(String args[]) {
int a = 10;
int b = 20;
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("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Page 5 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

(d) What is thread? Draw thread life cycle diagram in Java. 4M


(Note: Explanation of the life cycle is not needed).
Ans. A thread is a single sequential flow of control within a program.
They are lightweight processes that exist within a process. They
share the processs resource, including memory and are more 2M for
efficient. JVM allows an application to have multiple threads of defining a
execution running concurrently. Thread has a priority. Threads with thread
higher priority are executed in preference to threads with lower
priority.

2M for
diagram

1. (B) Attempt any ONE of the following: 1 x 6 =6


(a) What is single level inheritance? Explain with suitable example. 6M
(Note: Any appropriate program may be written).
Ans.
Single level inheritance enables a derived class to inherit properties
and behaviour from a single parent class. It allows a derived class to Explanati
inherit the properties and behaviour of a base class, thus enabling on with
code reusability as well as adding new features to the existing code. suitable
This makesthe code much more elegant and less repetitive. Single diagram
level inheritance can be represented by the following 2M

Page 6 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Example:
class SingleLevelInheritanceParent {
int l;
SingleLevelInheritanceParent(int l) { 4M for
this.l = l;
correct
}
void area() {
program
int a = l*l;
System.out.println("Area of square :"+a);
}

class SingleLevelInheritanceChild extends SingleLevelInheritanceParent


{
SingleLevelInheritanceChild(int l) {
super(l);
}
void volume() {
int v;
v= l*l*l;
System.out.println("Volume of the cube is "+v);
}
void area() {
int a;
a = 6*l*l;
System.out.println("Total surface area of a cube is "+a);
}
}

class SingleLevelInheritance {

Page 7 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

public static void main(String ar[]) {


SingleLevelInheritanceChild cube = new
SingleLevelInheritanceChild(2);
cube.volume();
cube.area();
}
}
(b) What is package? State how to create and access user defined 6M
package in Java.
(Note: Code snippet can be used for describing)
Ans. Package is a name space that organizes a set of related classes and 2M for
interfaces. Conceptually, it is similar to the different folders in a definition
computer. It also provides access protection and removes name of
collision. package
Packages can be categorized into two:- built-in and user defined.
Creation of user defined package:
To create a package a physical folder by the name should be created
in the computer.
Example: we have to create a package myPack, so we create a
folder d:\myPack 2M each
The java program is to be written and saved in the folder myPack. for
To add a program to the package, the first line in the java program explanati
should be package <name>; followed by imports and the program on of
logic. creation
package myPack; and
import java.util; access of
public class Myclass { user
//code defined
} package
Access user defined package:
To access a user defined package, we need to import the package in
our program. Once we have done the import we can create the
object of the class from the package and thus through the object we
can access the instance methods.
import mypack.*;
public class MyClassExample{
public static void main(String a[]) {
Myclass c= new Myclass();
}
}

Page 8 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

2. Attempt any TWO of the following: 2 x 8=16


(a) Write a program to add 2 integer, 2 string and 2 float objects to 8M
a vector. Remove element specified by user and display the list.
Ans. importjava.util.*;
import java.io.*;

class Vect { 4M for


public static void main(String a[]) {
correct
Vector<Object> v = new Vector<Object>();
v.addElement(new Integer(5));
syntax
v.addElement(new Integer(10));
v.addElement(new String("String 1"));
v.addElement(new String("String 2")); 4M for
v.addElement(new Float(5.0)); correct
v.addElement(new Float(6.7)); logic
int n=0;
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Following are the elements in the vector");
for(int i = 0; i <v.size();i++) {
System.out.println("Element at "+i+ "is "+v.elementAt(i));
}
System.out.println("Enter the position of the element to be removed");
try {
n = Integer.parseInt(b.readLine());
} catch(Exception e) {
System.out.println("Exception caught!"+e);
}
System.out.println("The element at "+n +"is "+v.elementAt(n)+"
will be removed");
v.removeElementAt(n);

System.out.println("The following are the elements in the


vector");

for(int i = 0; i<v.size();i++) {
System.out.println(v.elementAt(i));
}
}
}
(b) What is meant by interface? State its need and write syntax and 8M
features of interface.

Page 9 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Ans. Interface is the mechanism by which multiple inheritance is Definition


possible in java. It is a reference type in Java. An interface has all 2M
the methods undefined. For a java class to inherit the properties of
an interface, the interface should be implemented by the child class
using the keyword implements. All the methods of the interface
should be defined in the child class.
Example: program
interface MyInterface{ optional
int strength=60;
void method1();
void method2();
}
public class MyClass implements MyInterface {
int total;
MyClass(int t) {
total = t;
}
public void method1() {
int avg = total/strength;
System.out.println("Avg is "+avg);
}
public void method2() {

}
public static void main(String a[]) {
MyClass c = new MyClass(3600);
c.method1();
}
}

Need:
A java class can only have one super class. Therefore for achieving Need 2M
multiple inheritance, that is in order for a java class to get the
properties of two parents, interface is used. Interface defines a set
of common behaviours. The classes implement the interface, agree
to these behaviours and provide their own implementation to the
behaviours.

Page 10 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Syntax:
interface InterfaceName { Syntax
int var1 = value; 2M
int var2 = value;
public return_type methodname1(parameter_list) ;
public return_type methodname2(parameter_list) ;

Features:
Interface is defined using the keyword interface. Interface is Features
implicitly abstract. All the variables in the interface are by default 2M
final and static. All the methods of the interface are implicitly
public and are undefined (or implicitly abstract). It is compulsory
for the subclass to define all the methods of an interface. If all the
methods are not defined then the subclass should be declared as an
abstract class.
(c) Explain applet life cycle with suitable diagram. 8M
Ans.

3M for
diagram

Applets are small applications that are accessed on an Internet


server, transported over the Internet, automatically installed, and 5M for
run as part of a web document. The applet states include: explanati
Born or initialization state on
Running state
Idle state

Page 11 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Dead or destroyed state

Initialization state: applet enters the initialization state when it is


first loaded. This is done by calling the init() method of Applet
class. At this stage the following can be done:
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colours
Initialization happens only once in the life time of an applet.
public void init() {
//implementation
}
Running state: applet enters the running state when the system
calls the start() method of Applet class. This occurs automatically
after the applet is initialized. start() can also be called if the applet is
already in idle state. start() may be called more than once. start()
method may be overridden to create a thread to control the applet.
public void start() {
//implementation
}
Idle or stopped state: an applet becomes idle when it is stopped
from running. Stopping occurs automatically when the user leaves
the page containing the currently running applet. stop() method may
be overridden to terminate the thread used to run the applet.
public void stop() {
//implementation
}
Dead state: an applet is dead when it is removed from memory.
This occurs automatically by invoking the destroy method when we
quit the browser. Destroying stage occurs only once in the lifetime
of an applet. destroy() method may be overridden to clean up
resources like threads.
public void destroy() {
//implementation
}

Display state: applet is in the display state when it has to perform


some output operations on the screen. This happens after the applet

Page 12 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

enters the running state. paint() method is called for this. If anything
is to be displayed the paint() method is to be overridden.
public void paint(Graphics g) {
//implementation
}
3. Attempt any FOUR of the following: 4 x 4 =16
(a) Explain the following methods of string class with syntax and 4M
example:
(i) substring()
(ii) replace()
(Note: Any other example can be considered)
Ans. (i) substring():
Syntax:
String substring(intstartindex)
startindex specifies the index at which the substring will begin.It Each
will returns a copy of the substring that begins at startindex and method
runs to the end of the invoking string syntax
(OR) 1M
String substring(intstartindex,intendindex) and
Here startindex specifies the beginning index,andendindex specifies example
the stopping point. The string returned all the characters from the 1M
beginning index, upto, but not including,the ending index.
Example :
System.out.println(("Welcome.substring(3)); //come
System.out.println(("Welcome.substring(3,5));//co

(ii) replace():
This method returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

Syntax: String replace(char oldChar, char newChar)


Example:
String Str = new String("Welcome);
System.out.println(Str.replace('o', 'T')); // WelcTme
(b) Write a program to find sum of digit of number entered by 4M
user.
(Note: Direct Input or User Defined Input is also allowed & Any
Other Logic also allowed)
Ans. class Sum1

Page 13 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

{
public static void main(String args[]){
intnum = Integer.parseInt(args[0]); //takes argument as
command line Logic
int remainder, result=0; 2M
while(num>0)
{
remainder = num%10; Syntax
result = result + remainder; 2M
num = num/10;
}
System.out.println("sum of digit of number is : "+result);
}
}
OR
import java.io.*;
class Sum11{
public static void main(String args[])throws IOException{
BufferedReaderobj = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter number: ");
int num=Integer.parseInt(obj.readLine());
int remainder, result=0;
while(num>0)
{
remainder = num%10;
result = result + remainder;
num = num/10;
}
System.out.println("sum of digit of number is : "+result);
}
}
(c) What is Iterator class? Give syntax and use of any two methods 4M
of Iterator class.
Ans. Iterator enables you to cycle through a collection, obtaining or
removing elements.
Each of the collection classes provides an iterator( ) method that Definition
returns an iterator to the start of the collection. By using this iterator 1M
object, you can access each element in the collection, one element

Page 14 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

at a time
Syntax :
Iterator iterator_variable = collection_object.iterator(); Syntax
1M
Methods:
1. Boolean hasNext( ):Returns true if there are more elements. Any 2
Otherwise, returns false. methods
2. Object next( ): Returns the next element. Throws 1M each
NoSuchElementException if there is not a next element.

3.void remove( ):Removes the current element. Throws


IllegalStateException if an attempt is made to call remove( )
that is not preceded by a call to next( ).

(d) Describe the following attributes of applet. 4M


(i) Codebase
(ii) Alt
(iii) Width
(iv) Code
Ans. (i) Codebase: Codebaseis an optional attribute that specifies the
base URL of the applet code or the directory that will be Each
searched for the applets executable class file. attribute
(ii) Alt: Alternate Text. The ALT tag is an optional attribute used to descriptio
specify a short text message that should be displayed if the n 1M
browser cannot run java applets.
(iii) Width: Widthis required attributes that give the width (in
pixels) of the applet display area.
(iv) Code:Codeis a required attribute that give the name of the file
containing your applets compiled class file which will be run
by web browser or appletviewer
(e) State three uses of final keyword. 4M
Ans. Uses of final keyword:
1. Prevent overriding of method:
To disallow a method to be overridden final can be used as a
modifier at the start of declaration. Methods written as final Prevent
cannot be overridden. overridin
e.g. g :1M
class test
{

Page 15 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

final void disp() //prevents overidding


{
System.out.println(In superclass);
}
}
class test1 extends test {
voiddisp(){ // ERROR! Can't override
System.out.println("Illegal!");
}
}
2. Prevent inheritance:
Final can be used to even disallow the inheritance, to do this a class
can be defined with final modifier, declaring a class as final Prevent
declares all its method as final inheritan
e.g. ce :1M
final class test
{
void disp()
{
System.out.println(In superclass);
}
}Class test1 extends test // error as class test is final
{

}
3. Declaring final variable: Declaring
Variable declared final, it is constant which will not and can not final: 1M
change.
final int FILE_NEW = 1;
4. (A) Attempt any THREE of the following: 3 x 4 =12
(a) Write all primitive data types available in Java with their 4M
storage sizes in bytes.
Ans.
Sr. Type Keyword Width
No. (bytes) Storage
1 long integer long 8 Size of
Short integer short 2 any 4:1M
Integer int 4 each
Byte byte 1

Page 16 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

2 Double double 8
Float float 4
3 Character char 2
4 Boolean Boolean 1 bit
(b) What is thread priority? Write default priority values and 4M
methods to change them.
Ans. Thread Priority: In java each thread is assigned a priority which Thread
affects the order in which it is scheduled for running. Thread Priority
priority is used to decide when to switch from one running thread to explanati
another. Threads of same priority are given equal treatment by the on 1M
java scheduler.
Default Priority Values:Thread priorities can take value from
1 to10.
Thread class defines default priority constant values as
Default
MIN_PRIORITY = 1
priority
NORM_PRIORITY = 5 (Default Priority) values 1M
MAX_PRIORITY = 10
1. setPriority:
Syntax:public void setPriority(int number);
This method is used to assign new priority to the thread.
Each
2. getPriority: method
Syntax:public intgetPriority(); 1M
It obtain the priority of the thread and returns integer value.
(c) Write a program to generate Fibonacci series 1 1 2 3 5 8 13 4M
21 34 55 89.
Ans. class FibonocciSeries
{ Syntax
public static void main(String args[]) 2M
{
int num1 = 1,num2=1,ans;
System.out.println(num1); Logic 2M
while (num2< 100)
{
System.out.println(num2);
ans = num1+num2;
num1 = num2;

Page 17 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

num2=ans;
}
}
}
(d) Differentiate between Applet and Application (any 4 points). 4M
Ans. Sr. Applet Application
No.
1 Applet does not use Application usesmain()
main() method for method for initiating execution Any 4
initiating execution of of code. points 1M
code. each

2 Applet cannot run Application can run


independently. independently.
3 Applet cannot read Application can read from or
from or write to files in write to files in local computer.
local computer.
4 Applet cannot Application can communicate
communicate with with other servers on network.
other servers on
network.
5 Applet cannot run any Application can run any
program from local program from local computer.
computer.
6 Applet are restricted Application are not restricted
from using libraries from using libraries from other
from other language language.
such as C or C++.
4. (B) Attempt any ONE of the following: 1x6=6
(a) Write a program to draw a bar chart for plotting students 6M
passing percentage in last 5 years.
(Note: Any other logic can be considered)(HTML file with
separate applet tag may also be considered)
Ans.
importjava.awt.*; Applet tag
importjava.applet.*; 2M
/* <Applet code=BarChart width=400 height=400>
<param name=columns value=5>

Page 18 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

<param name=c1 value=80>


<param name=c2 value=90> Syntax
<param name=c3 value=100> 2M
<param name=c4 value=85>
<param name=c5 value=95>

<param name=label1 value=2012> Logic


<param name=label2 value=2013> 2M
<param name=label3 value=2014>
<param name=label4 value=2015>
<param name=label5 value=2016>
</Applet>
*/
public class BarChart extends Applet
{ int n=0;
String label[];
int value[];
public void init()
{

try
{
n=Integer.parseInt(getParameter("columns"));
label=new String[n];
value=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
label[4]=getParameter("label5");

value[0]=Integer.parseInt(getParameter("c1"));
value[1]=Integer.parseInt(getParameter("c2"));
value[2]=Integer.parseInt(getParameter("c3"));
value[3]=Integer.parseInt(getParameter("c4"));
value[4]=Integer.parseInt(getParameter("c5"));
}
catch(NumberFormatException e)
{

Page 19 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

System.out.println(e);
}
}
public void paint(Graphics g)
{
for(int i=0;i<n;i++)
{
g.setColor(Color.red);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.green);
g.fillRect(50,i*50+10,value[i],30);
}
}
}
(b) What is garbage collection in Java? Explain finalize method in 6M
Java.
(Note: Example optional)
Ans. Garbage collection:
Garbage collection is a process in which the memory allocated to
objects, which are no longer in use can be freed for further use.
Garbage collector runs either synchronously when system is out Garbage
of memory or asynchronously when system is idle. collection
In Java it is performed automatically. So it provides better explanati
memory management. on 4M
A garbage collector can be invoked explicitly by writing
statement
System.gc(); //will call garbage collector.
Example:
public class A
{
int p;
A()
{
p = 0;
}
}
class Test
{
public static void main(String args[])

Page 20 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

{
A a1= new A();
A a2= new A();
a1=a2; // it deallocates the memory of object a1
}
}

Method used for Garbage Collection finalize:


The java.lang.Object.finalize() is called by garbage collector on
an object when garbage collection determines that there are no Finalize
more reference to the object. method
A subclass override the finalize method to dispose of system explanati
resources or to perform other cleanup. on
Inside the finalize() method, the actions that are to be performed 2M
before an object is to be destroyed, can be defined. Before an
object is freed, the java run-time calls the finalize() method on
the object.
General Form :
protected void finalize()
{ // finalization code here
}
5. Attempt any TWO of the following: 2 x 8 = 16
(a) What is exception? WAP to accept a password from the user 8M
and throw Authentication Failure exception if the password
is incorrect.
Ans. An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program execution.
It can be handled by 5 keywords in java as follows : Exception
1) try: This block monitors the code for errors. 2M
2) catch: This block implements the code if exception is raised
due to some error in try block.
3) throw: To throw a user define exception
4) throws: Can be used with the methods declaration which are
may have some run time errors.
5) finally: Includes the code which executes irrespective of errors
in try block.
Program :
import java.io.*;

Page 21 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

class PasswordException extends Exception


{
PasswordException(String msg)
{
super(msg); Correct
} logic 3M
}
class PassCheck
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("abc123"))
{ Correct
System.out.println("Authenticated "); Syntax
} 3M
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
(b) Write a program to create two threads, one to print numbers in 8M
original order and other in reverse order from 1 to 10.
Ans. class thread1 extends Thread
{

Page 22 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

public void run()


{ Correct
for(int i=1 ; i<=10;i++) Logic 4M
{
System.out.println("Thread 1 :" +i);
}
}
}
class thread2 extends Thread
{
public void run() Correct
{ syntax
for(int i=10 ; i>=1;i--) 4M
{
System.out.println("Thread 2 :" +i);
}
}
}
class test
{
public static void main(String args[])
{
thread1 t1 = new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}
(c) Explain the following methods of applet class: 8M
(i) drawRect()
(ii) drawPolygon()
(iii) drawArc()
(iv) drawRoundRect()
Ans. (i) drawRect(): Each
method
The drawRect() method displays an outlined rectangle. 2M
Syntax: void drawRect(inttop, intleft, intwidth, int height)
The upper-left corner of the Rectangle is at top and left.
The dimension of the Rectangle is specified by width and height.
Example:
Page 23 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

g.drawRect(10,10,60,50);

(ii) drawPolygon():
drawPolygon() method is used to draw arbitrarily shaped figures.
Syntax: void drawPolygon(int x[], int y[], intnumPoints)
The polygons end points are specified by the co-ordinates pairs
contained within the x and y arrays. The number of points define by
x and y is specified by numPoints.
Example:
intxpoints[]={30,200,30,200,30};
intypoints[]={30,30,200,200,30};
intnum=5;
g.drawPolygon(xpoints,ypoints,num);

(iii) drawArc( ):
It is used to draw arc .
Syntax: void drawArc(int x, int y, int w, int h, intstart_angle,
intsweep_angle);
where x, y starting point, w & h are width and height of arc, and
start_angle is starting angle of arc sweep_angle is degree around the
arc
Example:g.drawArc(10, 10, 30, 40, 40, 90);

(iv)drawRoundRect():
It is used to draw rectangle with rounded corners.
Syntax : drawRoundRect(int x,int y,int width,int height,int
arcWidth,int arcHeight)
Where x and y are the starting coordinates, with width and height
as the width and height of rectangle.
arcWidth and arcHeight defines by what angle the corners of
rectangle are rounded.
Example: g.drawRoundRect(25, 50, 100, 100, 25, 50);

Page 24 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

6. Attempt any FOUR of the following: 4 x 4 = 16


(a) Write a program to implement following inheritance: 4M

Ans. interface gross


{
int ta=1000;
int da=4000;
public void gross_sal();
} Correct
class employee Logic 2M
{
String name="Abc";
int basic_sal=8000;
}
class salary extends employee implements gross Correct
{ syntax
int hra; 2M
int total=0;
salary(int h)
{
hra=h;
}
public void gross_sal()
{
total=basic_sal+ta+da+hra;
}

void disp_sal()
{
gross_sal();
System.out.println("Name :"+name);
System.out.println("Total salary :"+total);
}

Page 25 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

public static void main(String args[])


{
salary s = new salary(3000);
s.disp_sal();
}
}
(b) What is the use of ArrayList class? State any two methods with 4M
their use from ArrayList.
Ans. Use of ArrayList class:
1. ArrayList supports dynamic arrays that can grow as needed.
2. ArrayList is a variable-length array of object references. That is,
an ArrayListcan dynamically increase or decrease in size. Array
lists are created with an initial size. When this size is exceeded, the Use 2M
collection is automatically enlarged. When objects are removed, the
array may be shrunk.

Methods of ArrayList class :


1. void add(int index, Object element)
Inserts the specified element at the specified position index in Any two
this list. Throws IndexOutOfBoundsException if the specified methods
index is is out of range (index < 0 || index >size()). 2M

2.boolean add(Object o)
Appends the specified element to the end of this list.
booleanaddAll(Collection c)
Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified
collection's iterator. Throws NullPointerException if the specified
collection is null.

3. booleanaddAll(int index, Collection c)


Inserts all of the elements in the specified collection into this list,
starting at the specified position. Throws NullPointerException if
the specified collection is null.

4. void clear()
Removes all of the elements from this list. 6. Object clone()
Returns a shallow copy of this ArrayList.

Page 26 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

5. boolean contains(Object o)
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one
element e such that (o==null ? e==null : o.equals(e)).

6. void ensureCapacity(intminCapacity)
Increases the capacity of this ArrayList instance, if necessary, to
ensure that it can hold at least the number of elements specified by
the minimum capacity argument.

7. Object get(int index)


Returns the element at the specified position in this list.
Throws IndexOutOfBoundsException if the specified index is is out
of range (index < 0 || index >= size()).

8. intindexOf(Object o)
Returns the index in this list of the first occurrence of the specified
element, or -1 if the List does not contain this element.

9. intlastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified
element, or -1 if the list does not contain this element.

10. Object remove(int index)


Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 ||
index >= size()).

11. protected void removeRange(intfromIndex, inttoIndex)


Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.

12. Object set(int index, Object element)


Replaces the element at the specified position in this list with the
specified element. Throws IndexOutOfBoundsException if the
specified index is is out of range (index < 0 || index >= size()).

13. int size()

Page 27 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Returns the number of elements in this list.

14. Object[] toArray()


Returns an array containing all of the elements in this list in the
correct order. Throws NullPointerException if the specified array is
null.

15. Object[] toArray(Object[] a)


Returns an array containing all of the elements in this list in the
correct order; the runtime type of the returned array is that of the
specified array.

16.void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current
size.
(c) Design an applet which accepts username as a parameter for 4M
html page and display number of characters from it.
Ans. importjava.awt.*;
importjava.applet.*;
public class myapplet extends Applet
{ Correct
String str=""; Logic 2M
public void init()
{
str=getParameter("uname");
} Correct
public void paint(Graphics g) syntax
{ 2M
int n= str.length();
String s="Number of chars = "+Integer.toString(n);
g.drawString(s,100,100);
}
}

/*<applet code=myapplet height=200 width=200>


<param name="uname" value="student1">
</applet>*/
(d) List any four built-in packages from Java API along with their 4M
use.

Page 28 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

MODEL ANSWER
SUMMER - 2017 EXAMINATION
Subject: Java Programming Subject Code: 17515

Ans. 1. java.lang: Contains Language support classes which are used by


Java compiler during compilation of program Any 4
2. java.util: Contains language utility classes such as vectors, hash packages
tables, random numbers, date etc. with its
3. java.io: Contains I/O support classes which provide facility for use 1M
input and output of data. each
4. java.awt: Contains a set of classes for implementing graphical
user interface.
5. java.aplet: Contains classes for creating and implementing
applets.
6. java.sql: Contains classes for database connectivity.
7. java.net: Contains classes for networking.
(e) Write a program to accept two numbers as command line 4M
arguments and print the addition of those numbers.
Ans. class addition
{
public static void main(String args[])
{ Correct
int a,b; Logic 2M
a= Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]); Correct
int c= a+b; syntax2M
System.out.println("Addition= "+c);
}
}

Page 29 / 29

Você também pode gostar