0% found this document useful (0 votes)
26 views172 pages

Java Model Answers UNIT WISE

The document is a model answer for a Java Programming examination by the Maharashtra State Board of Technical Education. It includes important instructions for examiners, various questions related to Java features, inheritance, exception handling, and I/O streams, along with their respective answers and marking schemes. The content covers fundamental concepts of Java, including constructors, threading, and dynamic method dispatch, aimed at assessing students' understanding of the subject.

Uploaded by

rajmane5457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views172 pages

Java Model Answers UNIT WISE

The document is a model answer for a Java Programming examination by the Maharashtra State Board of Technical Education. It includes important instructions for examiners, various questions related to Java features, inheritance, exception handling, and I/O streams, along with their respective answers and marking schemes. The content covers fundamental concepts of Java, including constructors, threading, and dynamic method dispatch, aimed at assessing students' understanding of the subject.

Uploaded by

rajmane5457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT – I

UNIT – II

UNIT – III

UNIT – IV

UNIT – V

UNIT – VI

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 1 / 23

22412
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 cr edit 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, th e assumed
constant
values may vary and there may be some difference in the candidate’s 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 candidate’s understan ding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.

Q.
No
. Sub
Q.N. Answer Marking
Scheme
1.
a)
Ans. Attempt any FIVE of the following:
List any eight features of Java.
Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic 10
2M

Any
eight
features
2M
b)
Ans. State use of finali ze( ) method with its syntax.
Use of finalize( ):
Sometimes an object will need to perform some action when it is 2M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 2 / 23

22412
destroyed. Eg. If an object holding some non java resources such as
file handle or window character font, then before the object is
garbage co llected 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.

Syntax:
protected void finalize() {
}

Use 1M

Syntax
1M

c)

Ans. Name the wrapper class methods for the following:


(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
(i) To convert string objects to primitive int:
String str=”5”;
int value = [Link](str);

(ii) To convert primitive int to string objects:


int value=5;
String str=[Link](value); 2M

1M for
each
method
d)

Ans. List the types of inheritances in Java.


(Note: Any four types shall be considered)
Types of inheritances in Java:
i. Single level inheritance
ii. Multilevel inheritance
iii. Hierarchical inherita nce
iv. Multiple inheritance
v. Hybrid inheritance 2M

Any
four
types
½M
each
e)
Ans. Write the syntax of try -catch -finally blocks.
try{
//Statements to be monitored for any exception
} catch(ThrowableInstance1 obj) {
//Statements to execute if th is type of exception occurs
} catch(ThrowableInstance2 obj2) {
//Statements
}finally{ 2M

Correct
syntax
2M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 3 / 23

22412
//Statements which should be executed even if any exception happens
}
f)
Ans. Give the syntax of < param > tag to pass parameters to a n applet.

Syntax:
<param name=”name” value=”value”>

Example:
<param name=”color” value=”red”> 2M

Correct
syntax
2M

g)
Ans. Define stream class. List its types.
Definition of stream class:
An I/O Stream represents an input source or an output desti nation. 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 charact ers, and
objects. Java’s stream based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, Writer.

Types of stream classes:


i. Byte stream classes
ii. Character stream classes. 2M
Definitio
n 1M

Types
1M
2.
a)

Ans. Attempt any THREE of the following:


Explain the concept of platform independence and portability
with respect to Java language.
(Note: Any other relevant diagram shall be considered).
Java is a platform independent language. This is possible because
when a java program is co mpiled, an intermediate code called the
byte code is obtained rather than the machine code. Byte code is a
highly optimized set of instructions designed to be executed by the
JVM which is the interpreter for the byte code. Byte code is not a
machine specif ic code. Byte code is a universal code and can be
moved anywhere to any platform. Therefore java is portable, as it
can be carried to any platform. JVM is a virtual machine which exists
inside the computer memory and is a simulated computer within a
compu ter which does all the functions of a computer. Only the JVM
needs to be implemented for each platform. Although the details of
the JVM will defer from platform to platform, all interpret the same 12
4M

Explana
tion 3M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 4 / 23

22412
byte code.

Diagr am
1M
b)

Ans. Explain the types of constructors in Java with suitable example.


(Note: Any two types shall be considered).
Constructors are used to initialize an object as soon as it is created.
Every time an object is created using the ‘new’ keyword, a
constructor is invoked. If no constructor is defined in a class, java
compiler creates a default constructor. Constructors are similar to
methods but with to differences, constructor has the same name as
that of the class and it does not return any value.
The types of constructors are:
1. Default constructor
2. Constructor with no arguments
3. Parameterized constructor
4. Copy constructor

1. Default constructor: Java automatically creates default constructor


if the re is no default or parameterized constructor written by user .
Default constructor in Java initializes member data variable to default
values (numeric values are initialized as 0, Boolean is initialized as
false and references are initialized as null).
class test1 {
int i;
boolean b;
byte bt;
float ft;
String s; 4M

Explana
tion of
the two
types of
construc
tors 2M

Example
2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 5 / 23

22412
public static void main(String args[]) {
test1 t = new test1(); // default constructor is called.
[Link](t.i);
[Link](t.s);
[Link](t.b);
[Link] intln([Link]);
[Link]([Link]);
}
}
2. Constructor with no arguments: Such constructors does not have
any parameters. All the objects created using this type of constructors
has the same values for its datamembers.
Eg:
class Student {
int roll_n o;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
[Link]();
}
}

3. Parametrized co nstructor: Such constructor consists of parameters.


Such constructors can be used to create different objects with
datamembers having different values.
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r;

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 6 / 23

22412
name=n;
}
void display () {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
[Link]();
}
}

4. Copy Constructor : A copy constructor is a constructor that creates


a new o bject using an existing object of the same class and initializes
each instance variable of newly created object with corresponding
instance variables of the existing object passed as argument. This
constructor takes a single argument whose type is that of the class
containing the constructor.
class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = [Link];
breadth= [Link];
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
[Link]("Area of First Rectangle : "+
([Link]*[Link]));

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 7 / 23

22412
System .[Link]("Area of First Second Rectangle : "+
([Link]*[Link] th));
}
}
c)
Ans. Explain the two ways of creating threads in Java.
Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending t he Thread class.
Thread class provide constructors and methods to create and perform
operations on a thread. This class implements the Runnable interface.
When we extend the class Thread, we need to implement the method
run(). Once we create an object, we can call the start() of the thread
class for executing the method run().
Eg:
class MyThread extends Thread {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread t = new MyThrea d();
[Link]();
}
}
a. By implementing the runnable interface.
Runnable interface has only on one method - run().
Eg:
class MyThread implements Runnable {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
[Link]();
} 4M
2M
each for
explaini
ng of
two
types
with
example

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 8 / 23

22412
}

d)
Ans. Distinguish between Input stream class and output stream class.
Java I/O (Input and Output) is used to process the input and produce
the output .
Java uses the concept of a stream to make I/O operation fast. The
[Link] package contains all the classes required for input and output
operations. A stream is a sequence of data. In Java, a stream is
composed of bytes.

Sr.
No. Input stream class Output stream class
1 Java application uses an
input stream to read data
from a source; Java application uses an output
stream to write data to a
destination;.
2 It may read from a file, an
array, peripher al device or
socket It may be a write to file, an
array, peripheral device or
socket
3 Input stream classes reads
data as bytes Output stream classes writes
data as bytes
4 Super class is the abstract
inputStream class Super class is the abstract
OutputS tream class
5 Methods:
public int read() throws
IOException
public int available()
throws IOException
public void close() throws
IOException
Methods:
public void write(int b) throws
IOException
public void write(byte[] b)
throws IOException
public void f lush() throws
IOException
public void close() throws
IOException
6 The different subclasses
of Input Stream are:
File Input stream,
Byte Array Input Stream,
Filter Input Stream,
Piped Input Stream,
Object Input Stream,
DataInputStream. The different sub classes of
Output Stream class are:
File Output Stream,
Byte Array Output Stream ,
Filter output Stream,
Piped Output Stream,
Object Output Stream,
DataOutputStream
4M
Any
four
points
for input
stream
class
and
output
stream
class 1M
each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 9 / 23

22412
3.
a)

Ans. Attempt any THREE of the following:


Define a class student with int id and string name as data
members and a method void S etData ( ). Accept and display the
data for five students.
import [Link].*;
class student
{
int id;
String name;
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
void SetData()
{
try
{
[Link]("enter id and name for student");
id=[Link]([Link]());
name=[Link]();
}
catch(Exception ex)
{}
}
void display()
{
[Link]("The id is " + id + " and the name is "+ name);
}
public static void main(String are[])
{
student[] arr;
arr = new student[5];
int i;
for(i=0;i<5;i++)
{
arr[i] = new student();
}
for(i=0;i<5;i++)
{
arr[i].SetData();
} 12
4M

Correct
logic 4M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 10 / 23
22412
for(i=0;i<5;i++)
{
arr[i].display();
}
}
}
b)
Ans. Explain dynamic method dispatch in Java with suitable example.
Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
 When an overridden method is called through a su perclass
reference, Java determines which version (superclass/subclasses) of
that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is
made at run time.
 At run -time, it depend s on the type of the object being referred to
(not the type of the reference variable) that determines which version
of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This
is also known as upcasting. J ava uses this fact to resolve calls to
overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to through
a superclass reference variable, different ve rsions of the method are
executed. Here is an example that illustrates dynamic method
dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1() 4M
Explana
tion 2M

Example
2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 11 / 23

22412
{
[Link]("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = ne w C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 12 / 23

22412
// calling B's version of m1()
ref.m1();

// now ref refers t o a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}
c)

Ans. Describe the use of following methods:


(i) Drawoval ( )
(ii) getFont ( )
(iii) drawRect ( )
(iv) getFam ily ( )
(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 cor ner 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 .

Example: [Link](10,10,50,50);

(ii) getFont ( ): It is a method of Graphics class used to get the font


property
Font f = [Link]();
String fontName = [Link]();
Where g is a Graphics class object and fontName is string containing
name of the current font.

(iii) 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: [Link](10,10,60,50); 4M

Each
method
1M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 13 / 23

22412
(iv) getFamily ( ): The getfamily() metho d Returns the family of the
font.
String family = [Link]();
Where f is an object of Font class
d)

Ans. Write a program to count number of words from a text file using
stream classes.
(Note : Any other relevant logic shall be considered )
import [Link].*;
public class FileWordCount
{
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
if(c==(char)' ')
wc++;
}
[Link]("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
[Link]();
}
}
} 4M

Correct
program
4M
4.
a)

Ans.
Attempt any THREE of the following:
Describe instance Of and dot (.) operators in Java with suitable
example.
Instance of operator:
The java instance of operator is used to test whether the object is an
instance of the specified type (class or subclass or interface). 12
4M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 14 / 23

22412
The instance of in java is also known as type compa rison operator
because it compares the instance with type. It returns either true or
false. If we apply the instance of operator with any variable that has
null value, it returns false.
Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
[Link](s instance ofSimple1 );//true
}
}

dot (.) operator:


The dot operator , also known as separator or period used to separate a
variable or method from a reference variable. Only static variables or
methods can be accessed using class name. Code that is outside the
object's class must use an object reference or expression, followed by
the dot (.) operator, followed by a simple field name.
Example
[Link]=”john”; where name is a instance variable referenced by
‘this’ keyword
[Link](); where getdata() is a method invoked on object ‘c’.

Descript
ion and
example
of each
operator
2M
b)
Ans. Explain the four access specifiers in Java.
There are 4 types of java access modifiers:
1. private 2. default 3. Protected 4. public

1) private access modifier: The private access modifier is accessible


only within class.
2) default access specifier: If you don’t specify any access control
specifier, it is default, i.e. it becomes implicit public and it is
accessible within the program.
3) protected access specifier: Th e protected access specifier is
accessible within package and outside the package but through
inheritance only.
4) public access specifier: The public access specifier is accessible
everywhere. It has the widest scope among all other modifiers.
4M

Each
access
specifier
s 1M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 15 / 23

22412
c)

Ans. Differentiate between method overloading and method


overriding.
Sr.
No. Method overloading Method overriding
1 Overloading occurs when
two or more methods in
one class have the same
method name but different
parameters. Over ridin g means having two
methods with the same
method name and parameters
(i.e., method signature )
2 In contrast, reference type
determines which
overloaded method will be
used at compile time . The real object type in the
run-time, not the reference
variab le's type, determines
which overridden method is
used at runtime
3 Polymorphism not applies
to overloading Polymorphism applies to
overriding
4 overloading is a compile -
time concept. Overriding is a run -time
concept
4M

Any
four
points
1M each
d)

Ans. Different iate between Java Applet and Java Application (any
four points)
Sr.
No. Java Applet Java Application
1 Applets run in web pages Applications run on stand -
alone systems.
2 Applets are not full
featured application
programs. Applications are full featured
programs.
3 Applets are the small
programs. Applications are larger
programs.
4 Applet starts execution
with its init(). Application starts execution
with its main ().
5 Parameters to the applet
are given in the HTML
file. Parameters to the application
are given at the command
prompt
6 Applet cannot access the
local file system and
resources Application can access the
local file system and
resources.
7 Applets are event driven Applications are control
driven.
4M

Any
four
points
1M each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 16 / 23

22412
e)
Ans. Write a program to copy content of one file to another file.
class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("[Link]");
FileOutputStream out= new FileOutputStream("output .txt");
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
[Link](c);
}
[Link]("File copied to [Link]....");
}
finally
{
if(in!=null)
[Link]();
if(out!=null)
[Link]();
}
}
} 4M

Correct
logic 2M

Correct
Syntax
2M
5.
a)

Ans. Attempt any TWO of the following:


Describe the use of any methods of vector class with their syntax.
(Note: Any method other than this but in v ector class shall be
considered for answer).
 boolean add(Object obj) -Appends the specified element to the
end of this Vector.
 Boolean add(int index,Object obj) -Inserts the specified element a t
the specified position in this Vector.
 void addElement(Object obj) -Adds the specified component to
the end of this vector, increasing its size by one.
 int capacity() -Returns the current capacity of this vector.
 void clear() -Removes all of the elements fr om this vector.
 Object clone() -Returns a clone of this vector. 12
6M

Any 6
methods
with
their use
1M each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 17 / 23

22412
 boolean contains(Object elem) -Tests if the specified object is a
component in this vector.
 void copyInto(Object[] anArray) -Copies the components of this
vector into the specified array.
 Object firstElement() -Returns the first component (the item at
index 0) of this vector.
 Object elementAt(int index) -Returns the component at the
specified index.
 int indexOf(Object elem) -Searches for the first occurence of the
given argument, testing for equality using the equals method.
 Object lastElement() -Returns the last component of the vector.
 Object inser tElement At(Object obj,int index )-Inserts the specified
object as a component in this vector at the specified index.
 Object remove(int index) -Removes the el ement at the specified
position in this vector.
 void removeAllElements() -Removes all components from this
vector and sets its size to zero.
b)

Ans. Explain the concept of Dynamic method dispatch with suitab le


example.
Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which
a call to an overridden method is resolved at run time, rather than
compile time.
When an overridden method is c alled through a superclass reference,
Java determines which version (superclass/subclasses) of that method
is to be executed based upon the type of the object being referred to at
the time the call occurs. Thus, this determination is made at run time.
At run-time, it depends on the type of the object being referred to (not
the type of the reference variable) that determines which version of
an overridden method will be executed
A superclass reference variable can refer to a subclass object. This is
also kno wn as upcasting. Java uses this fact to resolve calls to
overridden methods at run time.
If a superclass contains a method that is overridden by a subclass,
then when different types of objects are referred to through a
superclass reference variable, diffe rent versions of the method are
executed. Here is an example that illustrates dynamic method
dispatch: 6M

Explana
tion 3M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 18 / 23

22412
/ A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]( "Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link] intln("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();

Example
3M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 19 / 23

22412
// obtain a reference of type A
A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();
// now ref refers to a B o bject
ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}

Output:
Inside A’s m1 method
Insid e B’s m1 method
Inside C’s m1 method
Explanation:
The above program creates one superclass called A and it’s two
subclasses B and C. These subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of
type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
C c = new C(); // object of type C

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 20 / 23

22412
c)

Ans. Write a program to create two threads. O ne thread will display


the numbers from 1 to 50 (ascending order) and other thread will
display numbers from 50 to 1 (descending order).
class Ascending extends Thread
{
public void run()
{
for(int i=1; i<=15;i++)
{
[Link]("Ascending Thread : " + i);
}
}
}

class Descending extends Thread


{
public void run()
{
for(int i=15; i>0;i --) {
[Link]("Descending Thread : " + i);
}
}
}

public class AscendingDescending Thread


{
public static void main(String[] args)
{
Ascending a=new Ascending();
[Link]();
Descending d=new Descending();
[Link]();
}
} 6M

Creation
of two
threads
4M
Creating
main to
create
and start
objects
of 2
threads :
2M
6.
a)
Ans. Attempt any TWO of the following:
Explain the command lin e arguments with suitable example.
Java Command Line Argument:
The java command -line argument is an argument i.e. passed at the
time of running the java program. 12
6M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 21 / 23

22412
The arguments passed from the console can be received in the java
program and it can be used as an input.
So, it provides a convenient way to check the behaviour of the
program for the different values. You can pass N (1,2,3 and so on)
numbers of arguments from the command prompt.

Command Line Arguments can be used to specify configuration


inform ation while launching your application.
There is no restriction on the number of java command line
arguments.
You can specify any number of arguments
Information is passed as Strings.
They are captured into the String args of your main method
Simple examp le of command -line argument in java

In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from
the command prompt.

class CommandLineExample
{
public static void main(String ar gs[]){
[Link]("Your first argument is: "+args[0]);
}
}
compile by > javac [Link]
run by > java CommandLineExample sonoo

4M for
explanat
ion

2M for
example
b)

Ans. Write a program to input name and salary of employee and


throw user defined exception if entered salary is negative.
import [Link].*;
class NegativeSalaryException extends Exception
{
public NegativeSalaryException (String str)
{
super(str);
}
}
public class S1 6M

Extende
d
Exceptio
n class
with
construc
tor 2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 22 / 23

22412
{
public static void main(String[] args) throws IOException
{
BufferedReaderbr= new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter Name of employee");
String name = [Link]();
[Link]("Enter S alary of employee");
int salary = [Link]([Link]());
Try
{
if(salary<0)
throw new NegativeSalaryException("Enter Salary amount
isnegative");
[Link]("Salary is "+salary);
}
catch (NegativeSalaryException a)
{
Syste [Link](a);
}
}
}

Acceptin
g data
1M

Throwin
g user
defining
Exceptio
n with
try catch
and
throw
3M
c)
Ans. Describe the applet life cycle in detail.

Below is the description of each applet life cycle method:


init(): The init() method is the first method to execute when the
applet is executed. Variable declaration and initialization operations 6M
2M
Diagram

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 23 / 23

22412

are performed in this method.

start(): The start() method contains the actual code of the a pplet that
should run. The start() method executes immediately after
the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab to another tab in the browser.

stop(): The stop() method stops the execution of the applet. The
stop() method executes when the applet is minimized or when
moving from one tab to another in the browser.

destroy(): The destroy() method executes when the applet window is


closed or when the tab containing the webpage is
closed. stop() metho d executes just before when destroy() method is
invoked. The destroy() method removes the applet object from
memory.

paint(): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution
of start() method and whenever the applet or browser is resized.
The method execution sequence when an applet is executed is:
 init()
 start()
 paint()
The method execution sequence when an applet is closed is:
 stop()
 destroy()

4M
descripti
on

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 1 / 26

22412
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 i ndicated in
the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed
constant values may vary and th ere may be some difference in the candidate’s answers and
model answer.
6) In case of some question s credit may be given by judgement on part of examiner of
relevant
answer based on candidate’s understanding.
7) For programming language papers, credit may be giv en to any other program based on
equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi

and Bilingual (English + Marathi) medium is introduced at first year of AICTE diploma
Programme from academic year 2021 -2022. Hence if the students in first year (first and
second semesters) write answers in Marathi or bilingual language (English +Marathi), the
Examiner shall consider the same and assess the answer based on matching of concepts
with model answer.
Q.
No Sub
Q.N. Answer Marking
Scheme
1.
a)
Ans. Attempt any FIVE of the following:
Enlist the logical operators in Java.
&& : Logical AND
|| : Logical OR
! : Logical NOT 10
2M
1M each
Any two
operator s
b)

Ans. Give the syntax and exam ple for the following functions
i) min ( )
ii) Sqrt ( )
i) min()
Syntax: (Any one of the following)
static int min(int x, int y) Returns minimum of x and y
static long min(long x, long y) Returns minimum of x and y
static float min(float x, float y) Returns m inimum of x and y
static double min(double x, int y) Returns minimum of x and y 2M

1M for
each
functi on
with
example

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 2 / 26

22412
Example:
int y= [Link](64,45);
ii)Sqrt()
Syntax:
static double sqrt(double arg) Returns square root of arg.
Example:
double y= [Link](64);
c)
Ans. Define the interface in Java.
Interface is similar to a class.
It consist of only abstract methods and final variables.
To implement an interface a class must define each of the method
declared in the interface.
It is used to ac hieve fully abstraction and multiple inheritance in
Java. 2M

1M for
each point,
Any two
points

d)
Ans. Enlist any four inbuilt packages in Java .
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] 2M
½ M for
each
package
Any four
packages

e)
Ans. Explain any two methods of File Class
1. 1. boolean createNewFile(): It creates a new, empty file named by
this abstract pathname automatically, if and only if no file with the
same name exists.
if([Link]())
[Link]("A n ew file is successfully created.");

2. 2. String getName(): It returns the name of the file or directory


denoted by the object‟s abstract pathname.
[Link]("File name : " + [Link]());

3. 3. String getParent(): It returns the parent‟s pathname string of the


object‟s abstract pathname or null if the pathname does not name a
parent directory.
[Link]("Parent name : " + [Link]());

2M
1M for
each
method
Any two
methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 3 / 26

22412
4. 4. boolean isFile(): It returns True if the file denoted by the abstract
pathname is a normal fil e, and False if it is not a normal file.
[Link]("File size (bytes) : " + [Link]());

5. 5. boolean canRead(): It returns True if the application can read the


file denoted by the abstract pathname, and returns False otherwise.
[Link] ln("Is file readable : " + [Link]());

6. 6. boolean canWrite(): It returns True if the application can modify


the file denoted by the abstract pathname, and returns False
otherwise.
[Link]("Is file writeable : " + [Link]());

7. 7. boolean canExecute(): It returns True if the application can execute


the file denoted by the abstract pathname, and returns False
otherwise.
[Link]("Is file executable : " + [Link] ());

f)
Ans. Write syntax of elipse .
Syntax: void fillOval(int top, int left, int width, int height)
The filled 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

OR
Syntax: void drawOval(int top, int left, int width, int height)
The empty 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
2M
2M for
correct
syntax
g)
Ans. Enlist any four compile time errors .
1)Missing semicolon
2)Missing of brackets in classes and methods
3)Misspelling of variables and keywords.
4)Missing double quotes in Strings.
5)Use of undeclared variable.
6)Incompatible type of assi gnment/initialization.
7)Bad reference to object. 2M
½ M for
each error

Any four
can be
considered

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 4 / 26

22412
2.
a)
Ans. Attempt any THREE of the following:
Explain any four features of Java
[Link] Oriented:
In Java, everything is an Object. Java can be easily extended since it
is based on the Object model.

[Link] Independent:
Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code
is distributed over the web and interpreted by the Virtual Machine
(JVM) on whichever platform it is being run on.
[Link]:
Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.

[Link]:
With Java's secure feature it enables to develop virus -free, tamper -
free systems. Authentication techniques are based on public -key
encryption.

[Link] -neutral:
Java compiler generates an architecture -neutral object file format,
which makes the compiled code executable on many processors, with
the presence of Java runtime system.

[Link]:
With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows
the devel opers to construct interactive applications that can run
smoothly.

[Link]: Java byte code is translated on the fly to native


machine instructions and is not stored anywhere. The development
process is more rapid and analytical since the linking is an
incremental and light -weight process. 12
4M

1M for
each
feature
Any four
features

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 5 / 26

22412
b)
Ans. Write a Java program to copy the content of one file into another.
import [Link].*;
class filecopy
{
public static void main(String args[]) throws IOExceptio n
{
FileReader fr= new FileReader(“[Link]");
FileWriter fo= new FileWriter("[Link]");
int ch;
try
{
while((ch=[Link]())!= -1)
{
[Link](ch);
}
[Link](“file copied successfully”);
[Link]();
[Link]();
}
finally
{
if(fr!=null)
[Link]();
if(fo!=null)
[Link]();
}}}
4M
2M for
correct
logic,

2M for
code

c)

Ans. Write the difference between vectors and arrays . (any four
points)
[Link] Array Vector
1 An array is a structure
that holds multiple
values of the same
type. The Vect or is similar to array holds
multiple objects and like an array;
it contains components that can be
accessed using an integer index.
2 An array is a
homogeneous data type
where it can hold only
objects of one data type Vectors are heterogeneous. You
can h ave objects of different data
types inside a Vector. 4M

1M for
each point

Any four
points

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 6 / 26

22412
3 After creation, an array
is a fixed -length
structure The size of a Vector can grow or
shrink as needed to accommodate
adding and removing items after
the Vector has been created
4 Array can store
primitive type data
element. Vector are store non primitive type
data element.
5 Declaration of an array
int arr[] = new int [10]; Declaration of Vector:
Vector list = new Vector(3)
6 Array is the static
memory allocation. Vector is the dynamic memory
allocation

d)

Ans. Explain exception handling mechanism w.r.t. try, catch, throw


and finally.
try:
Program statements that you want to monitor for exceptions are
contained within a try block. If an except ion occurs within the try
block, it is thrown.
Syntax:
try
{
// block of code to monitor for errors
}

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 can have one or more
statements that are necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionT ype1
}

4M

1M for
each
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 7 / 26

22412
throw:
It is mainly used to throw an instance of user defined exception.
Example: throw new myException(“Invalid number”); assuming
myException as a user defined exception

finally:
finally block is a block that is used to execute importan t code such as
closing connection, stream etc. Java finally block is always executed
whether exception is handled or not. Java finally block follows try or
catch block.
Syntax:
finally
{
// block of code to be executed before try block ends
}
3.
a)

Ans. Attempt any THREE of the following:


Write a Java Program to find out the even numbers from 1 to 100
using for loop .
class test
{
public static void main(String args[])
{
[Link]("Even numbers from 1 to 100 :");
for(int i=1;i<=100; i++)
{
if(i%2==0)
[Link](i+" ");
}
}
} 12
4M

2M for
Program
logic

2M for
program
syntax
b)
Ans. Explain any four visibility controls in Java .
Four visibility control specifiers in Java are public, default, private
and protected. The visibility control in java can be seen when concept
of package is used with the java application.
1) private : The access level of a private speci fier is only within the
class. It cannot be accessed from outside the class.
2) default : When no s pecifier is used in the declaration, it is called as
default specification. Default scope for anything declared in java 4M

3M for
Explanatio
n

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 8 / 26
22412
is implicit public. With this it can be accessed anywhere within
the same package.
3) protected : The access level of a protected specif ier is within the
package and outside the package through derived class.
4) public : The a ccess level of a public specifier is everywhere. It can
be accessed from within the class, outside the class, within
thepackage and outside the package.
5) private protected acc ess: The visibility level is between protected
access and private access. The fields are visible in all subclasses
regardless of what package they are in.
These five access specifiers can be mapped with four categories in
which packages in java can be mana ged with access specification
matrix as:
Access Modifier Public Protected Friendly
(default) Private
protected private
Access Location
Same Class Yes Yes Yes Yes Yes
Sub class in same
package Yes Yes Yes Yes No
Other classes in
same package Yes Yes Yes No No
Sub class in other
packages Yes Yes No Yes No
Non sub classes in
other packages Yes No No No No

1M for
access
specificatio
n table

c)
Ans. Explain single and multilevel inheritance with proper example.
Single level inheritance:
In single inheritance, a single subclass extends from a single
superclass.

Example :
class A
{ 4M

1M for
each
explanatio
n

1M for
each
exampl e

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 9 / 26

22412
void display()
{
[Link](“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
[Link].p rintln(“In child class B”);
}
public static void main(String args[])
{
B b= new B();
[Link](); //super class method call
[Link](); // sub class method call
}
}
Note : any other relevant example can be considered.

Multilevel inheritance:
In multilevel inheritance, a subclass extends from a superclass and
then the same subclass acts as a superclass for another class.
Basically it appears as derived from a derived class.

Example:
class A
{
void display()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 10 / 26

22412
{
[Link](“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
[Link](“In child class B”);
}
}
class C extends B //derived class C from B
{
public void print()
{
[Link](“In derived from derived class C”);
}
public static void main(S tring args[])
{
C c= new C();
[Link](); //super class method call
[Link](); // sub class method call
[Link](); //sub -sub class method call
}
}
Note : any other relevant example can be considered.

d)

Ans. Write a java applet to display the following output in Red color.
Refer Fig. No. 1 .

import [Link].*;
import [Link].*;
public class myapplet extends Applet 4M

2M for
correct
logic

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 11 / 26

22412
{
public void paint(Graphics g)
{
int x[]={10,200,70};
int y[]={ 10,10,100};
[Link]([Link]);
[Link] Polygon(x,y,3);
}
}
/*<applet code=myapplet height=400 width=400>
</applet>*/

2M for
correct
syntax

4.
a)

Ans. Attempt any THREE of the following:


Explain switch case and con ditional operator in java with
suitable example.
switch…case statement:
The switch …case statement allows us to execute a block of code
among many alternatives.
Syntax :
switch (expression)
{
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}

The expression is evaluated once and compared with the values of


each case.
If expression matches with value1, the code of case value1 are
executed. Similarly, the code of case value2 is executed if expre ssion
matches with value2. 12
4M

1M for
explanatio
n
switch case
statement

1M for
example

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 12 / 26
22412
break is a required statement, which is used to take break from switch
block, if any case is true. Otherwise even after executing a case, if
break is not given, it will go for the next case.
If there is no match, the code of the default case is executed.

Example :
// Java Program to print day of week
// using the switch...case statement
class test1{
public static void main(String[] args) {
int number = 1;
String day;
switch (number)
{
case 1:
day = "Monday";
break;
case 2:
day= "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day= "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day= "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day= "Invalid day";
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 13 / 26
22412
[Link](day);
}
}
Note : an y other relevant example can be considered.

Conditional Operator:
The Conditional Operator is used to select one of two expressions for
evaluation, which is based on the value of the first operands. It is used
to handling simple situations in a line.
Syntax:
expression1 ? expression2:expression3;
The above syntax means that if the value given in Expression1 is true,
then Expression2 will be evaluated; otherwise, expression3 will be
evaluated.

Example
class test
{
public static void main(String[] args) {
String result ;
int a = 6, b = 12;
result = (a==b ? " equal ":"No t equal ");
[Link]("Both are "+result );
}
}
Note : any other relevant example can be considered.

1M for
explanatio
n
Conditiona
l operator

1M for
example
b)
Ans. Draw and explain life cycle of thread .
Life cycle of thread includes following states :
[Link]
2. Runnable
3. Running
4. Blocked
5. Dead

4M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 14 / 26

22412
New – A new thread begins its life cycle in the new state. It is also
referred to as a born thread. This is the state where a thread has been
created, but it has not yet been started. A thread is started by calling
its start() meth od.

Runnable – The thread is in the runnable state after the invocation of


the start() method, but the scheduler has not selected it to be the
running thread. It is in the Ready -to-run state by calling the start
method and waiting for its turn.

Running – When the thread starts executing, then the state is


changed to a “running” state. The method invoked is run|().

Blocked –This is the state when the thread is still alive but is currently
not eligible to run. This state can be implemented by methods such as
suspend() -resume(), wait() -notify() and sleep(time in ms).

Dead – This is the state when the thread is terminated. The thread is
in a running state and as soon as it is completed processing it is in a
“dead state”. Once a thread is in this state, th e thread cannot even run
again.
2M for
diagram

2M for
explanatio
n

c)

Ans. Write a java program to sort an 1 -d array in ascending order


using bubble -sort.
public class BubbleSort
{
public static void main(String[] args) 4M

2M for
correct
logic

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 15 / 26

22412
{
int arr[] ={3 ,60,35,2,45,320,5};
[Link]("Array Before Bubble Sort");
for(int i=0; i<[Link]; i++)
{
[Link](arr[i] + " ");
}
[Link]();
int n = [Link];
int temp = 0;
for(int i=0; i< n; i ++)
{
for(int j=1; j < (n -i); j++)
{
if(arr[j -1] >arr[j])
{
//swap elements
temp = arr[j -1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
[Link]("Array After Bubble S ort");
for(int i=0; i<[Link]; i++)
{
[Link](arr[i] + " ");
}
}
}

2M for
correct
syntax

d)
Ans. Explain how to create a package and how to import it
To create package following steps can be taken:
1) Start the code by keyword „package ‟ followed by package name.
Example : package mypackage;
2) Complete the code with all required classes inside the package
with appropriate access modifiers.
3) Compile the code with „javac‟ to get .class file. 4M

3M
for steps to
create

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 16 / 26

22412
Example: javac [Link] to get [Link]
4) Create a folder which is same as package name and make sure
that class file of package is present inside it. If not, copy it inside
this folder.
To import the package inside any other program :
Make use of import statemen t to include package in your program.
It can be used with „*‟ to gain full access to all classes within package
or just by giving class name if just one class access is required.
Example :
import [Link];
or
importmypackage.*;
1M to
import

e)

Ans. Explain
i) drawLine
ii) drawOval
iii) drawRect
iv) drawArc
i) drawL ine(): It is a method from Graphics class and is used to draw
line between the points(x1, y1) and (x2, y2).
Syntax :
drawLine(int x1, int y1, int x2, int y 2)

ii) drawOval ():Its is a method from Graphics class and is used to


draw oval or ellipse and circle.
Syntax :
drawOval(int x, ,int y, int width, int height)
It is used to draw oval with the specifiedwidth and height. If width
and height are given equa l, then it draws circle otherwise oval/ellipse.
iii) drawRect ():It is a method from Graphics class and it draws a
rectangle with the specified widthand height .
Syntax :
drawRect(int x , int y, int width, int height)
iv) drawArc ():It is a method from Graphic s class and is used to draw
a circular or elliptical arc.
Syntax :
drawArc(int x, int y, int width, int height, intstartAngle,
intsweepAngle) 4M

1M for
each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 17 / 26

22412
where f irst fourare x, y, width and height as in case of oval or rect.
The next two are start angle and sweep angl [Link] sweep angle is
positive, it moves in anticlockwise direction. It is given as negative, It
moves in clockwise direction .

5.
a)

Ans. Attempt any TWO of the following:


How to create user defined package in Java. Explain with an
suitable example.
A java package is a group of similar types of classes, interfaces and
sub-packages
It also provides access protection and removes name collisions.

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
The java program is to be written and saved in the folder myPack. To
add a program to the package, the first line in the java program
should be packa ge <name>; followed by imports and the program
logic.

package myPack;
import [Link];
public class Myclass {
//code
}

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(); 12
6M

3M
Package
creation

(Note:
Code
snippet can
be used for
describing)

3M for
Example

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 18 / 26

22412
}
}
Examp le:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
[Link]("Volume is:"+(l*b*h));
}
}
Source file:
import [Link];
class volume {
public static void main(String args[])
{
Box b =new Box();
[Link]();
}}

(Note Any
other
similar
example
can be
considered
)
b)

Ans. Write a Java program in which thread A will displ ay the even
numbers between 1 to 50 and thread B will display the odd
numbers between 1 to 50. After 3 iterations thread A should go to
sleep for 500ms.

Import [Link] .*;


class A extends Thread
{
public void run()
{
try
{
for(int i=2;i<=50;i=i+2 )
{ 6M

3M
Correct
program
with syntax

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 19 / 26
22412
[Link](" \t A thread :"+i);
if(i == 6) // for 3rd iteration
sleep(500);
}
}
catch(Exception e)
{
[Link]("A thread interrupted");
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int i=1;i<50;i=i+2)
{
[Link](" \t B thread :"+i);
}
}
catch(Exception e)
{
[Link]("B thread interrupted");
}
}
}
class OddEven
{
public static void main(String args[])
{
new A().start();
new B().start();
}
}

3M
Correct
logic
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 20 / 26

22412
c)
Ans. What is constructor? List types of constructor. Explain
parameterized constructor with suitable example.
Constructor:
A constructor is a special member whi ch 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 nume ric 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.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with no arguments or No-Arg Constructor or Non -
Parameterized constructor.

Parameterized constructor: When constructor method is defined


with parameters inside it, different value sets can be provided to
different construct or with the same name.
Example
class Student {
int roll_no;
String name;
Student(int r, String n) // parameterized constructor
{
roll_no = r;
name=n;
}
void display()
{
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
} 6M

2M for
Definition
1M List
types
(Any 3 )

1M
parameteri
zed
constructor
2M
Example
(Any Other
Example
Can be

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 21 / 26

22412
public static void main(String a[])
{
Student s = new Student(20,"ABC"); // constructor
with parameters
[Link]();
}
} considere d
)

6.
a)
Ans. Attempt any TWO of the following:
Write a Java Program to count the number of words from a text
file using stream classes.
import [Link].*;
public class FileWordCount {
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;

try { while(c!= -1)


{
c=[Link]();
if(c==(char)' ')
wc++;
}
[Link]("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
[Link]();
}
}
} 12
6M
(Note :
Any other
relevant
logic shall
be
considered
)

3M
Correct
program
with syntax

3M
Correct
logic

b)

Explain the difference between string class and string buffer


class.
Explain any f our methods of string class 6M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 22 / 26

22412
Ans.

Methods of string class


1)toLowercase ():
Converts all of the characters in this String to lower case.
Syntax: [Link]()
Example: String s="Sachin";
[Link]([Link]());
Output: sachin

2) toUppercase():
Converts all of the characters in this String to upper case
Syntax: [Link]()
Example: String s="Sachin";
[Link]([Link]());
Output: SACHIN
3)trim ():
Returns a copy of the string, with leading and trailing whitespace
omitted.
Syntax: [Link]()
Example: String s=" Sachin ";
[Link]([Link]()); 1M each
Any 2
points

1M each
Any 4
Methods
correct
explanatio
n

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 23 / 26

22412
Output:Sachin
4)replace (): Returns a new string resulting from replacing all
occurrences of old Char in this string with new Char.
Syntax: [Link](‘x’,’y’)
Example: String s1="J ava is a programming language. Java is a
platform.";
String s2=[Link]("Java","Kava"); //replaces all occurrences of
"Java" to "Kava" [Link](s2);
Output: Kava is a programming language. Kava is a platform
5. length():
Syntax: int length()
It is used to return length of given string in integer.
Eg. String str=”INDIA”
[Link]([Link]()); // Returns 5
6. charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .
Eg. String s=”INDIA”
[Link]([Link](2) ); // returns D

7. substring():
Syntax:
String substring (int startindex)
startindex specifies the index at which the substring will [Link] will
returns a copy of the substring that begins at startindex and runs to the
end of the invoking string
Example:
[Link](("Welcome”.substring(3)); //come
(OR)
String substring(int startindex,int endindex)
Here startindex specifies the beginning index, and endindex specifies
the stopping point. The string returned all the c haracters from the

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 24 / 26

22412
beginning index, upto, but not including , the ending index.
Example :
[Link](("Welcome”.substring(3,5));//co

8. compareTo():
Syntax: int compareTo(Object o) or int compareTo(String
anotherString)
There are two variants of th is method. First method compares this
String to another Object and second method compares two strings
lexicographically.
Example. String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = [Link]( str2 );
[Link](result);
result = [Link]( str3 );
[Link](result);

c)

Ans. Write a Java applet to draw a bar cha rt for the following values .

import [Link].*;
import [Link].*;

/* <applet code=BarChart width=400 height=400>


<param name=c1 value=110>
<param name=c2 value=120>
<param name=c3 value=170>
<param name=c4 value=160>
<param name=label1 value=2011>
<param name=label2 value=2012>
<param name=label3 value=2013> 6M

2M for
Applet tag
2M for

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 25 / 26

22412
<param name=label4 value=2014>
<param name=Columns value=4>
</applet>
*/

public class BarChart extends Applet


{
int n=0;
String label[];
int value[];

public void init() {

setBackground(Color .yellow);
try {

int n = [Link](getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] = getParameter("label1");
label[1] = getParameter("label2");
label[2] = getParameter("label3");
label[3] = getPa rameter("label4");
value[0] = [Link](getParameter("c1"));
value[1] = [Link](getParameter("c2"));
value[2] = [Link](getParameter("c3"));
value[3] = [Link](getParameter("c4"));
}
catch(NumberFormatExcep tion e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++) {
[Link]([Link]);
[Link](label[i],20,i*50+30);
[Link]([Link]);
[Link](50,i*50+10,value[i],40);
} Syntax

2M
Correct
Logic
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 26 / 26

22412
}}

MSBTE QUESTION PAPERS & MODEL ANSWERS


1. MSBTE SUMMER -19 EXAMINATION
2. MSBTE WINTER -19 EXAMINATION

Zeal Education Society’s


ZEAL POLYTECHNIC, PUNE.
NARHE │PUNE -41 │ INDIA
SECOND YEAR (SY)
DIPLOMA IN COMPUTER ENGINEERING
SCHEME: I SEMESTER: IV

NAME OF SUBJECT: JAVA PROGRAMMING


SUBJECT CODE : 22412

22412
21819
3 Hours / 70 Marks Seat No.
Instructions – (1) All Questions are Compulsory.
(2) Answer each next main Question on a new page.
(3) Figures to the right indicate full marks.
(4) Assume suitable data, if necessary.
(5) Use of Non-programmable Electronic Pocket
Calculator is permissible.
(6) Mobile Phone, Pager and any other Electronic
Communication devices are not permissible in
Examination Hall.
Marks
1. Attempt any FIVE of the following: 10
a) List any eight features of Java.
b) State use of finalize( ) method with its syntax.
c) Name the wrapper class methods for the following:
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
d) List the types of inheritances in Java.
e) Write the syntax of try-catch-finally blocks.
f) Give the syntax of < param > tag to pass parameters to an
applet.
g) Define stream class. List its types.
P.T.O.

22412 [ 2 ]
Marks
2. Attempt any THREE of the following: 12
a) Explain the concept of platform independence and portability
with respect to Java language.
b) Explain the types of constructors in Java with suitable example.
c) Explain the two ways of creating threads in Java.
d) Distinguish between Input stream class and output stream
class.
3. Attempt any THREE of the following: 12
a) Define a class student with int id and string name as data
members and a method void SetData ( ). Accept and display
the data for five students.
b) Explain dynamic method dispatch in Java with suitable
example.
c) Describe the use of following methods:
(i) Drawoval ( )
(ii) getFont ( )
(iii) drawRect ( )
(iv) getFamily ( )
d) Write a program to count number of words from a text file
using stream classes.
4. Attempt any THREE of the following: 12
a) Describe instance Of and dot ( . ) operators in Java with
suitable example.
b) Explain the four access specifiers in Java.
c) Differentiate between method overloading and method
overriding.
d) Differentiate between Java Applet and Java Application ( any
four points)
e) Write a program to copy content of one file to another file.

22412 [ 3 ]
Marks
5. Attempt any TWO of the following: 12
a) Describe the use of any methods of vector class with their
syntax.
b) Explain the concept of Dynamic method dispatch with suitable
example.
c) Write a program to create two threads. One thread will
display the numbers from 1 to 50 (ascending order) and other
thread will display numbers from 50 to 1 (descending order).
6. Attempt any TWO of the following: 12
a) Explain the command line arguments with suitable example.
b) Write a program to input name and salary of employee and
throw user defined exception if entered salary is negative.
c) Describe the applet life cycle in detail.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 1 / 23

22412
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 cr edit 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, th e assumed
constant
values may vary and there may be some difference in the candidate’s 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 candidate’s understan ding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.

Q.
No
. Sub
Q.N. Answer Marking
Scheme
1.
a)
Ans. Attempt any FIVE of the following:
List any eight features of Java.
Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic 10
2M

Any
eight
features
2M
b)
Ans. State use of finali ze( ) method with its syntax.
Use of finalize( ):
Sometimes an object will need to perform some action when it is 2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 2 / 23

22412
destroyed. Eg. If an object holding some non java resources such as
file handle or window character font, then before the object is
garbage co llected 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.

Syntax:
protected void finalize() {
}

Use 1M

Syntax
1M

c)
Ans. Name the wrapper class methods for the following:
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
(i) To convert string objects to primitive int:
String str=”5”;
int value = [Link](str);

(ii) To convert primitive int to string objects:


int value=5;
String str=[Link](value); 2M

1M for
each
method
d)

Ans. List the types of inheritances in Java.


(Note: Any four types shall be considered)
Types of inheritances in Java:
i. Single level inheritance
ii. Multilevel inheritance
iii. Hierarchical inherita nce
iv. Multiple inheritance
v. Hybrid inheritance 2M

Any
four
types
½M
each
e)
Ans. Write the syntax of try -catch -finally blocks.
try{
//Statements to be monitored for any exception
} catch(ThrowableInstance1 obj) {
//Statements to execute if th is type of exception occurs
} catch(ThrowableInstance2 obj2) {
//Statements
}finally{ 2M

Correct
syntax
2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 3 / 23

22412
//Statements which should be executed even if any exception happens
}
f)
Ans. Give the syntax of < param > tag to pass parameters to a n applet.

Syntax:
<param name=”name” value=”value”>

Example:
<param name=”color” value=”red”> 2M

Correct
syntax
2M

g)
Ans. Define stream class. List its types.
Definition of stream class:
An I/O Stream represents an input source or an output desti nation. 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 charact ers, and
objects. Java’s stream based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, Writer.

Types of stream classes:


i. Byte stream classes
ii. Character stream classes. 2M

Definitio
n 1M

Types
1M
2.
a)

Ans. Attempt any THREE of the following:


Explain the concept of platform independence and portability
with respect to Java language.
(Note: Any other relevant diagram shall be considered).
Java is a platform independent language. This is possible because
when a java program is co mpiled, an intermediate code called the
byte code is obtained rather than the machine code. Byte code is a
highly optimized set of instructions designed to be executed by the
JVM which is the interpreter for the byte code. Byte code is not a
machine specif ic code. Byte code is a universal code and can be
moved anywhere to any platform. Therefore java is portable, as it
can be carried to any platform. JVM is a virtual machine which exists
inside the computer memory and is a simulated computer within a
compu ter which does all the functions of a computer. Only the JVM
needs to be implemented for each platform. Although the details of
the JVM will defer from platform to platform, all interpret the same 12
4M
Explana
tion 3M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 4 / 23

22412
byte code.

Diagr am
1M
b)

Ans. Explain the types of constructors in Java with suitable example.


(Note: Any two types shall be considered).
Constructors are used to initialize an object as soon as it is created.
Every time an object is created using the ‘new’ keyword, a
constructor is invoked. If no constructor is defined in a class, java
compiler creates a default constructor. Constructors are similar to
methods but with to differences, constructor has the same name as
that of the class and it does not return any value.
The types of constructors are:
1. Default constructor
2. Constructor with no arguments
3. Parameterized constructor
4. Copy constructor

1. Default constructor: Java automatically creates default constructor


if the re is no default or parameterized constructor written by user .
Default constructor in Java initializes member data variable to default
values (numeric values are initialized as 0, Boolean is initialized as
false and references are initialized as null).
class test1 {
int i;
boolean b;
byte bt;
float ft;
String s; 4M

Explana
tion of
the two
types of
construc
tors 2M

Example
2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 5 / 23

22412
public static void main(String args[]) {
test1 t = new test1(); // default constructor is called.
[Link](t.i);
[Link](t.s);
[Link](t.b);
[Link] intln([Link]);
[Link]([Link]);
}
}
2. Constructor with no arguments: Such constructors does not have
any parameters. All the objects created using this type of constructors
has the same values for its datamembers.
Eg:
class Student {
int roll_n o;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
[Link]();
}
}

3. Parametrized co nstructor: Such constructor consists of parameters.


Such constructors can be used to create different objects with
datamembers having different values.
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r;

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 6 / 23

22412
name=n;
}
void display () {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
[Link]();
}
}

4. Copy Constructor : A copy constructor is a constructor that creates


a new o bject using an existing object of the same class and initializes
each instance variable of newly created object with corresponding
instance variables of the existing object passed as argument. This
constructor takes a single argument whose type is that of the class
containing the constructor.
class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = [Link];
breadth= [Link];
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
[Link]("Area of First Rectangle : "+
([Link]*[Link]));
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 7 / 23

22412
System .[Link]("Area of First Second Rectangle : "+
([Link]*[Link] th));
}
}
c)
Ans. Explain the two ways of creating threads in Java.
Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending t he Thread class.
Thread class provide constructors and methods to create and perform
operations on a thread. This class implements the Runnable interface.
When we extend the class Thread, we need to implement the method
run(). Once we create an object, we can call the start() of the thread
class for executing the method run().
Eg:
class MyThread extends Thread {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread t = new MyThrea d();
[Link]();
}
}
a. By implementing the runnable interface.
Runnable interface has only on one method - run().
Eg:
class MyThread implements Runnable {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
[Link]();
} 4M

2M
each for
explaini
ng of
two
types
with
example

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 8 / 23

22412
}

d)
Ans. Distinguish between Input stream class and output stream class.
Java I/O (Input and Output) is used to process the input and produce
the output .
Java uses the concept of a stream to make I/O operation fast. The
[Link] package contains all the classes required for input and output
operations. A stream is a sequence of data. In Java, a stream is
composed of bytes.

Sr.
No. Input stream class Output stream class
1 Java application uses an
input stream to read data
from a source; Java application uses an output
stream to write data to a
destination;.
2 It may read from a file, an
array, peripher al device or
socket It may be a write to file, an
array, peripheral device or
socket
3 Input stream classes reads
data as bytes Output stream classes writes
data as bytes
4 Super class is the abstract
inputStream class Super class is the abstract
OutputS tream class
5 Methods:
public int read() throws
IOException
public int available()
throws IOException
public void close() throws
IOException
Methods:
public void write(int b) throws
IOException
public void write(byte[] b)
throws IOException
public void f lush() throws
IOException
public void close() throws
IOException
6 The different subclasses
of Input Stream are:
File Input stream,
Byte Array Input Stream,
Filter Input Stream,
Piped Input Stream,
Object Input Stream,
DataInputStream. The different sub classes of
Output Stream class are:
File Output Stream,
Byte Array Output Stream ,
Filter output Stream,
Piped Output Stream,
Object Output Stream,
DataOutputStream
4M

Any
four
points
for input
stream
class
and
output
stream
class 1M
each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 9 / 23

22412
3.
a)

Ans. Attempt any THREE of the following:


Define a class student with int id and string name as data
members and a method void S etData ( ). Accept and display the
data for five students.
import [Link].*;
class student
{
int id;
String name;
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
void SetData()
{
try
{
[Link]("enter id and name for student");
id=[Link]([Link]());
name=[Link]();
}
catch(Exception ex)
{}
}
void display()
{
[Link]("The id is " + id + " and the name is "+ name);
}
public static void main(String are[])
{
student[] arr;
arr = new student[5];
int i;
for(i=0;i<5;i++)
{
arr[i] = new student();
}
for(i=0;i<5;i++)
{
arr[i].SetData();
} 12
4M

Correct
logic 4M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 10 / 23

22412
for(i=0;i<5;i++)
{
arr[i].display();
}
}
}
b)
Ans. Explain dynamic method dispatch in Java with suitable example.
Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
 When an overridden method is called through a su perclass
reference, Java determines which version (superclass/subclasses) of
that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is
made at run time.
 At run -time, it depend s on the type of the object being referred to
(not the type of the reference variable) that determines which version
of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This
is also known as upcasting. J ava uses this fact to resolve calls to
overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to through
a superclass reference variable, different ve rsions of the method are
executed. Here is an example that illustrates dynamic method
dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1() 4M

Explana
tion 2M

Example
2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 11 / 23
22412
{
[Link]("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = ne w C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 12 / 23

22412

// calling B's version of m1()


ref.m1();

// now ref refers t o a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}
c)

Ans. Describe the use of following methods:


(i) Drawoval ( )
(ii) getFont ( )
(iii) drawRect ( )
(iv) getFam ily ( )
(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 cor ner 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 .

Example: [Link](10,10,50,50);

(ii) getFont ( ): It is a method of Graphics class used to get the font


property
Font f = [Link]();
String fontName = [Link]();
Where g is a Graphics class object and fontName is string containing
name of the current font.

(iii) 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: [Link](10,10,60,50); 4M

Each
method
1M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 13 / 23

22412
(iv) getFamily ( ): The getfamily() metho d Returns the family of the
font.
String family = [Link]();
Where f is an object of Font class
d)

Ans. Write a program to count number of words from a text file using
stream classes.
(Note : Any other relevant logic shall be considered )
import [Link].*;
public class FileWordCount
{
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
if(c==(char)' ')
wc++;
}
[Link]("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
[Link]();
}
}
} 4M

Correct
program
4M
4.
a)

Ans.
Attempt any THREE of the following:
Describe instance Of and dot (.) operators in Java with suitable
example.
Instance of operator:
The java instance of operator is used to test whether the object is an
instance of the specified type (class or subclass or interface). 12
4M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 14 / 23

22412
The instance of in java is also known as type compa rison operator
because it compares the instance with type. It returns either true or
false. If we apply the instance of operator with any variable that has
null value, it returns false.
Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
[Link](s instance ofSimple1 );//true
}
}

dot (.) operator:


The dot operator , also known as separator or period used to separate a
variable or method from a reference variable. Only static variables or
methods can be accessed using class name. Code that is outside the
object's class must use an object reference or expression, followed by
the dot (.) operator, followed by a simple field name.
Example
[Link]=”john”; where name is a instance variable referenced by
‘this’ keyword
[Link](); where getdata() is a method invoked on object ‘c’.
Descript
ion and
example
of each
operator
2M
b)
Ans. Explain the four access specifiers in Java.
There are 4 types of java access modifiers:
1. private 2. default 3. Protected 4. public

1) private access modifier: The private access modifier is accessible


only within class.
2) default access specifier: If you don’t specify any access control
specifier, it is default, i.e. it becomes implicit public and it is
accessible within the program.
3) protected access specifier: Th e protected access specifier is
accessible within package and outside the package but through
inheritance only.
4) public access specifier: The public access specifier is accessible
everywhere. It has the widest scope among all other modifiers.
4M

Each
access
specifier
s 1M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 15 / 23

22412
c)

Ans. Differentiate between method overloading and method


overriding.
Sr.
No. Method overloading Method overriding
1 Overloading occurs when
two or more methods in
one class have the same
method name but different
parameters. Over ridin g means having two
methods with the same
method name and parameters
(i.e., method signature )
2 In contrast, reference type
determines which
overloaded method will be
used at compile time . The real object type in the
run-time, not the reference
variab le's type, determines
which overridden method is
used at runtime
3 Polymorphism not applies
to overloading Polymorphism applies to
overriding
4 overloading is a compile -
time concept. Overriding is a run -time
concept
4M

Any
four
points
1M each
d)

Ans. Different iate between Java Applet and Java Application (any
four points)
Sr.
No. Java Applet Java Application
1 Applets run in web pages Applications run on stand -
alone systems.
2 Applets are not full
featured application
programs. Applications are full featured
programs.
3 Applets are the small
programs. Applications are larger
programs.
4 Applet starts execution
with its init(). Application starts execution
with its main ().
5 Parameters to the applet
are given in the HTML
file. Parameters to the application
are given at the command
prompt
6 Applet cannot access the
local file system and
resources Application can access the
local file system and
resources.
7 Applets are event driven Applications are control
driven.
4M

Any
four
points
1M each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 16 / 23
22412
e)
Ans. Write a program to copy content of one file to another file.
class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("[Link]");
FileOutputStream out= new FileOutputStream("output .txt");
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
[Link](c);
}
[Link]("File copied to [Link]....");
}
finally
{
if(in!=null)
[Link]();
if(out!=null)
[Link]();
}
}
} 4M

Correct
logic 2M

Correct
Syntax
2M
5.
a)

Ans. Attempt any TWO of the following:


Describe the use of any methods of vector class with their syntax.
(Note: Any method other than this but in v ector class shall be
considered for answer).
 boolean add(Object obj) -Appends the specified element to the
end of this Vector.
 Boolean add(int index,Object obj) -Inserts the specified element a t
the specified position in this Vector.
 void addElement(Object obj) -Adds the specified component to
the end of this vector, increasing its size by one.
 int capacity() -Returns the current capacity of this vector.
 void clear() -Removes all of the elements fr om this vector.
 Object clone() -Returns a clone of this vector. 12
6M

Any 6
methods
with
their use
1M each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 17 / 23

22412
 boolean contains(Object elem) -Tests if the specified object is a
component in this vector.
 void copyInto(Object[] anArray) -Copies the components of this
vector into the specified array.
 Object firstElement() -Returns the first component (the item at
index 0) of this vector.
 Object elementAt(int index) -Returns the component at the
specified index.
 int indexOf(Object elem) -Searches for the first occurence of the
given argument, testing for equality using the equals method.
 Object lastElement() -Returns the last component of the vector.
 Object inser tElement At(Object obj,int index )-Inserts the specified
object as a component in this vector at the specified index.
 Object remove(int index) -Removes the el ement at the specified
position in this vector.
 void removeAllElements() -Removes all components from this
vector and sets its size to zero.
b)

Ans. Explain the concept of Dynamic method dispatch with suitab le


example.
Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which
a call to an overridden method is resolved at run time, rather than
compile time.
When an overridden method is c alled through a superclass reference,
Java determines which version (superclass/subclasses) of that method
is to be executed based upon the type of the object being referred to at
the time the call occurs. Thus, this determination is made at run time.
At run-time, it depends on the type of the object being referred to (not
the type of the reference variable) that determines which version of
an overridden method will be executed
A superclass reference variable can refer to a subclass object. This is
also kno wn as upcasting. Java uses this fact to resolve calls to
overridden methods at run time.
If a superclass contains a method that is overridden by a subclass,
then when different types of objects are referred to through a
superclass reference variable, diffe rent versions of the method are
executed. Here is an example that illustrates dynamic method
dispatch: 6M

Explana
tion 3M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 18 / 23

22412
/ A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]( "Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link] intln("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();

Example
3M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 19 / 23

22412
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B o bject


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}

Output:
Inside A’s m1 method
Insid e B’s m1 method
Inside C’s m1 method
Explanation:
The above program creates one superclass called A and it’s two
subclasses B and C. These subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of
type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
C c = new C(); // object of type C

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 20 / 23
22412
c)

Ans. Write a program to create two threads. O ne thread will display


the numbers from 1 to 50 (ascending order) and other thread will
display numbers from 50 to 1 (descending order).
class Ascending extends Thread
{
public void run()
{
for(int i=1; i<=15;i++)
{
[Link]("Ascending Thread : " + i);
}
}
}

class Descending extends Thread


{
public void run()
{
for(int i=15; i>0;i --) {
[Link]("Descending Thread : " + i);
}
}
}

public class AscendingDescending Thread


{
public static void main(String[] args)
{
Ascending a=new Ascending();
[Link]();
Descending d=new Descending();
[Link]();
}
} 6M
Creation
of two
threads
4M

Creating
main to
create
and start
objects
of 2
threads :
2M
6.
a)
Ans. Attempt any TWO of the following:
Explain the command lin e arguments with suitable example.
Java Command Line Argument:
The java command -line argument is an argument i.e. passed at the
time of running the java program. 12
6M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 21 / 23

22412
The arguments passed from the console can be received in the java
program and it can be used as an input.
So, it provides a convenient way to check the behaviour of the
program for the different values. You can pass N (1,2,3 and so on)
numbers of arguments from the command prompt.
Command Line Arguments can be used to specify configuration
inform ation while launching your application.
There is no restriction on the number of java command line
arguments.
You can specify any number of arguments
Information is passed as Strings.
They are captured into the String args of your main method

Simple examp le of command -line argument in java

In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from
the command prompt.

class CommandLineExample
{
public static void main(String ar gs[]){
[Link]("Your first argument is: "+args[0]);
}
}
compile by > javac [Link]
run by > java CommandLineExample sonoo

4M for
explanat
ion
2M for
example
b)

Ans. Write a program to input name and salary of employee and


throw user defined exception if entered salary is negative.
import [Link].*;
class NegativeSalaryException extends Exception
{
public NegativeSalaryException (String str)
{
super(str);
}
}
public class S1 6M

Extende
d
Exceptio
n class
with
construc
tor 2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 22 / 23

22412
{
public static void main(String[] args) throws IOException
{
BufferedReaderbr= new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter Name of employee");
String name = [Link]();
[Link]("Enter S alary of employee");
int salary = [Link]([Link]());
Try
{
if(salary<0)
throw new NegativeSalaryException("Enter Salary amount
isnegative");
[Link]("Salary is "+salary);
}
catch (NegativeSalaryException a)
{
Syste [Link](a);
}
}
}

Acceptin
g data
1M

Throwin
g user
defining
Exceptio
n with
try catch
and
throw
3M
c)
Ans. Describe the applet life cycle in detail.
Below is the description of each applet life cycle method:
init(): The init() method is the first method to execute when the
applet is executed. Variable declaration and initialization operations 6M

2M
Diagram

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 23 / 23

22412

are performed in this method.

start(): The start() method contains the actual code of the a pplet that
should run. The start() method executes immediately after
the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab to another tab in the browser.

stop(): The stop() method stops the execution of the applet. The
stop() method executes when the applet is minimized or when
moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is
closed or when the tab containing the webpage is
closed. stop() metho d executes just before when destroy() method is
invoked. The destroy() method removes the applet object from
memory.

paint(): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution
of start() method and whenever the applet or browser is resized.
The method execution sequence when an applet is executed is:
 init()
 start()
 paint()
The method execution sequence when an applet is closed is:
 stop()
 destroy()

4M
descripti
on

22412
11920
3 Hours / 70 Marks Seat No.
P.T.O. Instructions – (1) All Questions are Compulsory.
(2) Answer each next main Question on a new page.
(3) Illustrate your answers with neat sketches wherever
necessary.
(4) Figures to the right indicate full marks.
(5) Assume suitable data, if necessary.
(6) Mobile Phone, Pager and any other Electronic
Communication devices are not permissible in
Examination Hall.
Marks
1. Attempt any FIVE of the following: 10
a) Define constructor. List its types.
b) Define class and object.
c) List the methods of File Input Stream Class.
d) Define error. List types of error.
e) List any four Java API packages.
f) Define array. List its types.
g) List access specifiers in Java.

22412 [ 2 ]
Marks
2. Attempt any THREE of the following: 12
a) Differentiate between String and String Buffer.
b) Define a class circle having data members Pi and radius.
Initialize and display values of data members also calculate
area of circle and display it.
c) Define exception. State built-in exceptions.
d) Write a syntax and example of
(i) drawRect( )
(ii) drawoval( )
3. Attempt any THREE of the following: 12
a) Explain the following classes.
(i) Byte Stream Class
(ii) Character Stream Class
b) Explain life cycle of Applet.
c) Differentiate between class and interfaces.
d) Define type casting. Explain its types with syntax and
example.
4. Attempt any THREE of the following: 12
a) Explain life cycle of thread.
b) Describe final variable and final method.
c) Explain any two logical operators in Java with example.
d) Differentiate between array and vector.
e) List any four methods of string class and state the use of each.

22412 [ 3 ]
Marks
5. Attempt any TWO of the following: 12
a) Write a program to create vector with five elements as
(5, 15, 25, 35, 45). Insert new element at 2nd position.
Remove 1st and 4th element from vector.
b) Define packages. How to create user defined package?
Explain with example.
c) Write a program to create two threads one thread will print
even no. between 1 to 50 and other will print odd number
between 1 to 50.
6. Attempt any TWO of the following: 12
a) Explain how to pass parameter to an applet? Write an
applet to accept username in the form of parameter and
print “Hello <username>”.
b) Write a program to perform following task.
(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file.
c) Implement the following inheritance.
Interface : Salary
Basic_Salary
Basic_Sal ( )Class : Employee
Name, age
Display ( )
Class: Gross_Salary
TA, DA, HRA
Total_Sal ( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

1 | 24

Winter – 19 EXAMINATION

Subject Name: Java Programming Model Answer Subject Code: 22412

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 (No t applicable for su bject 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 eq uivalent figure dra wn.
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 candidate’s 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 candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
Q.
No. Sub
Q. N. Answer Marking
Scheme
1. Attempt any Five of the following: 10M
a Define Constructor. List its types. 2M
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. W hen 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 ope rator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor Definition:1Mark
Types: 1 Mark
b Define Class and Object. 2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

2 | 24

Ans Class : A class is a user defined data type which groups data
member s and its associated functions together.
Objec t: It is a basic unit of Object Oriented Programming and
represents the real life entities. A typical Java program creates
many objects, which as you know, interact by invoking methods. Definition 1
Mark each
c List the methods of File Input Stream Class. 2M
Ans • void close()
• int read()
• int read(byte[] b)
• read(byte[] b, int off, int len)
• int available() Any Two Each
for 1 Mark
d Define error. List types of error. 2M
Ans • Errors are mistakes that can m ake a program go wrong. Errors
may be logical or may be typing mistakes. An error may
produce an incorrect output or may terminate the execution of
the program abruptly or even may cause the system to crash.
Errors are broadly classified into two categorie s:
1. Compile time errors
2. Runtime errors Definition: 1m
List: 1m
e List any four Java API packages. 2M
Ans [Link]
[Link]
[Link]
[Link]
[Link]
[Link]
1/2 Marks for
one Package
f Define array. List its types. 2M
Ans An array is a homogeneous data type where it can hold only
objects of one data type.
Types of Array: Definition 1
Mark, List 1
Mark

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

3 | 24

1)One -Dimensional
2)Two -Dimensional
g List access specifiers in Java. 2M
Ans 1)public
2)private
3)friendly
4)protecte d
5)Private Protected Any 2, 1M for
each

2. Attempt any Three of the following: 12M


a Differentiate between String and String Buffer. 4M
Ans
String String Buffer c
String is a major class String Buffer is a peer class
of String
Length is fi xed (immutable) Length is flexible (mutable )
Contents of object cannot be
modified Contents of object can be
modified
Object can be created by
assigning String constants
enclosed in double quotes. Obje cts can be created by
calling constructor of String
Buffer class using “new”
Ex:- String s=”abc” ; Ex:- StringBuffer s=new
StringBuffer (“abc”);

Any 4 Points
4 Marks
b Define a class circle having data members pi and radius.
Initialize and display values of data members also calculate
area of circle and display it.
Ans class abc
{ correct
Program with
correct logic 4
Mark

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
4 | 24

float pi,radius;
abc(float p, float r)
{
pi=p;
radius=r;
}
void area()
{
float ar=pi*radius*radius;
[Link]("Area="+ar);
}
void display()
{
[Link]("Pi="+pi);
[Link]("Radius= "+radius);
}}
class area
{
public static void main(String args[])
{
abc a=new abc(3.14f,5.0f);
[Link]();

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

5 | 24

[Link]();
}
}
c Define exception. State built -in exceptions. 4M
Ans An exception is a pro blem that arises during the execution of a
program.
Java exception handling is used to handle error conditions in a
program systemati cally by taking the necessary action
Built -in exceptions:
• Arithmetic exception : Arithmetic error such as division by
zero .
• ArrayIndexOutOfBounds Exception : Array index is out
of bound
• ClassNotFoundException
• FileNotFoundException : Caused by an attempt to access
a nonexistent file .
• IO Exception : Caused by general I/O failures, such as
inability to read from a file .
• NullPointerE xception : Caused by referencing a null object .
• NumberFormatException : Caused when a conversion
between strings and number fails.
• StringIndexOutOfBoundsException : Caused when a
program attempts to access a nonexistent character position
in a string .
• OutOfMe moryException: Caused when there’s not
enough memory to allocate a new object .
• SecurityException: Caused when an applet tries to perform
an action not allowed by the browser’s security setting .
• StackOverflowException: Caused when the system runs out
of sta ck space . Definition 2
Marks, List: 2
Marks
d Write syntax and example of : 4M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

6 | 24

1) drawRect()
2)drawOval()
Ans 1)drawRect() :
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: [Link](10,10,60,50);
2) drawOval( ) : Drawing Ellipses and circles: To draw an
Ellipses or circles used drawOval () me thod can b e 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 o r filled
circle, specify the same width and height the following program
draws several ellipses and circle.
Example: [Link](10,10,50,50); drawRect:
2Marks,
drawOval: 2
Marks

3. Attempt any Three of the following:


a Explain the following cl asses.
i)Byte stream class
ii)Character Stream Class 4M
Ans i)Byte stream class:

1) InputStream and OutputStream are designed for byte


streams
2) Use the byte stream classes when working with bytes or other
binary objects.
3) Input Stream is an abstract class that defines Java’s model of
streaming byte input 2M for any two
points

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

7 | 24

4)The Input stream class defines methods for performing input


function such as reading bytes, closing streams, Marking
position in stream.
5) Output Stream is an abstract class that defines streaming byte
output.
6) The output stream class defines methods for perfor ming
output function such as writing bytes, closing streams
ii)Character Stream Class:
1. Reader and Writer are designed for character streams.
2. Use character stream classes when workin g with characters or
strings.
3. Writer stream classes are designed t o write characters.
4. Reader stream classes are designed to read characters.
5The two subclasses used for handling characters in file are
FileReader (for reading characters) and FileWrit er (for writing
characters).

b Explain life cycle of Applet. 4M


Ans When an applet begins, the AWT calls the following methods, in
this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequ ence of method
calls takes place:
4. stop( )
5. destroy( ) 1M for diagram
,3M for
explanation

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

8 | 24

init ( ):The init( ) method is the first method to be called. This is


where you should initialize Variables . This method is called only
once dur ing the run time of your applet.

start( ) :The start( ) method is called after init( ) .It is also called
to restart an applet after it has Been stopped. Whereas init( ) is
called once —the first time an applet is loaded —start( ) is called
each time an applet’s HTML document is displayed onscreen.

Paint ( ): The paint ( ) method is called each time your applet’s


output must be redrawn. Paint ( ) is also called when the applet
begins execution. Whatever the cause, whenever the applet must
redraw its output , paint ( ) is called. The paint ( ) method has one
parameter of type Graphic s.

Stop ( ): When stop ( ) is called , the applet is probably running.


You should use stop ( ) to suspend threads that don’t need to run
when the applet is not visible.
destroy( ) : The destroy ( ) method is called when the environmen t
determines that your applet needs to be removed completely from
memory.
c Differentiate between class and interfaces. 4M
Ans
Class Interface
1)doesn’t Supports multiple
inheritance 1) Supports multiple
inheritanc e
2)”extend ” keyword is used
to inherit 2)”implements ” keyword is
used to inherit
3) class contain method body 3) interface contains abstract
method(method without
body) 1M for each
point

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

9 | 24

4)contains any type of


variable 4)contains only final variable
5)can have constr uctor 5)cannot have constructor
6)can have main() method 6)cannot have main() method

7)syntax
Class classname
{
Variable declaration,
Method declaration
} 7)syntax
Inteface Innterfacename
{
Final Variable declaration,
abstract Method declaration
}

d Define type casting. Explain its types with syntax and example. 4M
Ans 1. The process of converting one data type to another is called
casting or type casting.
2. If the two types are compatible, then java will perform the
conversion a utomatically.
3. It is possible to assign an int value to long variable.
4. However, if the tw o types of variables are not compatible, the
type conversions are not implicitly allowed, hence the need for
type casting.
There are two types of conversion:
[Link] type -casting:
[Link] type -casting:

1. Implicit type -casting:


Implicit type -casting performed by the compiler automatically ; if
there will be no loss of precision.
Example:
int i = 3;
double f;
f = i; 1M for
definition,3M for
types explanation

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

10 |
24

output:
f = 3.0
Widening Conversion :
The rule is to promote the smaller type to bigger type to prevent
loss of precision, known as Widening Conversion .
2. Explicit type -casting:
• Explicit type -casting performed via a type -casting
operator in the prefix form of ( new-type) operand.
• Type -castin g forces an explicit conversion of type of a
value. Type casting is an operation which takes one
operand, operates on it and returns an equivalent value in
the specified type.
Syntax:
newValue = (typecast)value;
Example:
double f = 3.5;
int i;
i = (int)f; // it cast double value 3.5 to int 3.
Narrowing Casting: Explicit type cast is requires to Narrowing
conversion to inform the compiler that you are aware of the
possible loss of precision.

4. Attempt any Three of the following:


a Explain life cycle of thread. 4M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

11 |
24
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.
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 sta te it can be scheduled for running
by start() or killed by stop(). If put in a queue it moves to
runnable state.
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
relinqu ish the control to another before its turn comes by yield(). 2M for
diagram,2M for
explanation

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

12 |
24
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 .
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.
1) suspend() : Thread can be suspended by this method. It
can be rescheduled by resume().
2) 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().
3) sleep(): We can put a thread to sleep for a specified time
period using sleep(time) where time is in ms. It re -enters
the runnable state as soon as period has elapsed /over
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 Describe final variable and final method. 4M
Ans Final method : making a method final ensures that the
functionality def ined in this method will never be altered in any
way, ie a final method cannot be overridden.
Syntax:
final void findAverage()
{
//implementation
}
Example of declaring a final method:
class A
{ 2M for
definition,2M for
example
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

13 |
24
final void show()
{
[Link](“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
[Link](“in show of B”);
}}
Final variable : the value of a final variable cannot be changed.
Final variable behaves l ike class variables and they do not take
any space on individual objects of the class.
Example of declaring final variable: final int size = 100;
c Explain any two logical operator in java with example. 4M
Ans 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:

Operator Meaning
&& Logical
AND
|| Logical
OR
! Logical
NOT
Program demonstrating logical Operators
public class Test 2M for each
operator with eg.

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
14 |
24
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
[Link]("a && b = " + (a&&b));
[Link]("a || b = " + (a||b) );
[Link]("!(a && b) = " + !(a && b));
}
}
Output:
a && b = false
a || b = true
!(a && b) = true

d Differentiate between array and vector. 4M


Ans

Array Vector
1) An array is a structure that
holds multiple values of the
same type. 1)The Vector is similar to
array holds multiple objects
and like an array; i t contains
components that can be
accessed using an integer
index. any four points
1m for each point

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

15 |
24
2) An array is a homogeneous
data type where it can hold
only objects of one data type. 2) Vectors are heterogeneous.
You can have objects of
different data types insi de a
Vector.
3) Afte r creation, an array is a
fixed -length structure . 3) The size of a Vector can
grow or shrink as needed to
accommodate adding and
removing items after the
Vector has been created.
4) Array can store primitive
type data element. 4) Vect or are store non -
prim itive type data element.
5)Declaration of an array :
int arr[] = new int [10]; 5)Declaration of Vector:
Vector list = new Vector(3);
6) Array is the static memory
allocation. 6) Vector is the dynamic
memory allocation.

e List any four methods of string class and state the use of
each. 4M
Ans The [Link] class provides a lot of methods to work on
string. By the help of these methods,
We can perform operations on string such as trimming,
concatenating, conver ting, comparing , replacing strings etc.
1) to Lowercase ( ): Converts all of the characters in this String
to lower case.
Syntax: [Link]()
Example: String s="Sachin" ;
[Link]([Link]());
Output: sachin
2)to Uppercase(): Converts all of the characters in this String to
upper case any four methods
of string class
can be
consider ed

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

16 |
24
Syntax: [Link]()
Example:
String s="Sachin";
[Link]([Link]());
Output: SACHIN
3) trim ( ): Returns a copy of the string, with leading and trailing
whitespace omitted.
Syntax: [Link]( )
Example:
String s=" Sachin ";
[Link]([Link]());
Output:Sachin
4) replace ( ):Returns a new string resulting from replacing all
occurrences of old Char in this string with new Char.
Syntax: [Link](‘x’,’y’)
Example:
String s1="Java is a prog ramming language. Java is a platform.";
String s2=[Link]("Java","Kava"); //replaces all occurrences
of "Java" to "Kava"
[Link](s2);
Output: Kava is a programming language. Kava is a platform.

5. Attempt any Three of the following: 12-Total Marks


a Write a program to create a vector with five elements as (5 ,
15, 25, 35, 45 ). Insert new element at 2nd position. Remove 1st
and 4th element from vector. 6M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

17 |
24
Ans import [Link].*;
class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector();
[Link](new Integer(5));
[Link](new Integer(15));
[Link](new Integer(25));
[Link](new Integer(35));
[Link](new Integer(45));
[Link]("Original array elements are
");
for(int i=0;i<[Link]();i++)
{
[Link]([Link](i)) ;
}
[Link](new Integer(20),1); // insert
new element at 2nd position
[Link](0);
//remove first element
[Link](3);
//remove fourth element
[Link]("Array elements after insert
and remove operation " );
for(int i=0;i<[Link]();i++)
{
[Link]([Link](i));
}}} (Vector creation
with elements – 2
M,

Insert ne w
element – 2M,

Remove elements
2 M,

(Any other logic


can be
considered)
b Define package. How to create user defined package?
Explain with example. 6M
Ans Java provides a mechanism for partitioning the class namespace
into more manageable parts. T his mechanism is the package. 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 . Package defines a namespace in (Definition of
package - 1M,

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

18 |
24
which classes are stored.
The syntax for defining a 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 pack ages. 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 mus t match with the
package name exactly. A hierarchy can be created by separating
package name and sub pa ckage name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as
pkg1 \pkg2 \pkg3.
Syntax:
To access package In a Java source file, import statements
occur immediately following the package statement (if
it exists) and before any class d efinitions.
Syntax:
import pkg1 [.pkg2 ].(classname |*);
Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
[Link]("Volume is:"+(l*b*h));
}
}
Source file:
import [Link];
class volume
{

Package creation
- 2M

Example - 3M

(Note Any other


example can be
considered)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

19 |
24
public static void main(String args[])
{
Box b=new Box();
[Link]();
}
}
c Write a program to create two threads one th read will print
even no. between 1 to 50 and other will print odd number
between 1 to 50. 6M
Ans import [Link].*;
class Even extends Thread
{
public void run()
{
try
{
for(int i=2;i<=50;i=i+2)
{
[Link](" \t Even thread :"+i);
sleep(500);
}
}
catch(InterruptedException e)
{[Link]("even thread interrupted");
}
}
}
class Odd extends Thread
{
public void run()
{
try
{
for(int i=1;i<50;i=i+2)
{
[Link](" \t Odd thread :"+i);
sleep(500); Creation of two
threads 4M

Creating main to
create and start
objects of 2
threads: 2M

(Any other logic


can be
considered)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

20 |
24
}
}
catch(InterruptedException e)
{[Link]("odd thread interrupted");
}
}
}
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}

6. Attempt any Three of the following: 12 M


a Explain how to pass parameter to an applet ? Write an applet
to accept username in the form of parameter and print “H ello
<username>”. 6M
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 use d 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 pa rameters, two things must be done.
1. Include appropriate <PARAM..>tags in the HTML document.
The Applet tag in HTML doc ument allows passing the
arguments using param tag. The syntax of <PARAM…> tag
<Applet code=”AppletDemo” height=300 width=300>
<PARA M NAME = name1 VALUE = value1> </Applet>
NAME:attribute name
VALUE: value of attribute named by
corresponding PARAM NAM E.
(Explanation for
parameter
passing - 3M,

Correct Program
– 3M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

21 |
24
2. Provide code in the applet to parse these parameters. The
Applet access their attributes using the getParameter method.
The sy ntax is : String getParameter(String name);
Program
import [Link].*;
import [Link].*;
public class hellouser ext ends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
[Link](str,10,100);
}
}
<HTML>
<Applet code = [Link] width = 400 height = 400>
<PARAM NAME = "username" V ALUE = abc> </Applet>
</HTML>
(OR)
import [Link].*;
import [Link].*;
/*<Applet code = [Link] 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;
}

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

22 |
24
public void pain t(Graphics g)
{
[Link](str,10,100);
}
}

b Write a program to perform following task


(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file. 6M
Ans import [Link].*;
import [Link].*;
class Model6B
{
public static void main(String[] args) throws Exception
{
int lineCount=0, wordCount=0;
String line = " ";
BufferedReader br1 = new BufferedReader(new
InputStreamReader([Link]));

FileWriter fw = new FileWriter("[Link]");


//create text file for writing
[Link]("Enter data to be inserted in
file: ");
String fileData = [Link]();
[Link](fileData);
[Link]();
BufferedReader br = new BufferedReader(new
FileReader("[Link]"));
while ((line = [Link]()) != null)
{
lineCount++; // no of lines count
String[] words = [Link](" ");
wordCount = wordCount + [Link];
// no of words count
}
[Link]("Number of lines is : " +
lineCount);
[Link]("Number of words is : " +
wordCount);
} Create file and
store data : 3M,

Get lines and


word count : 3M)

(Any other logic


can be
considered )
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

23 |
24
}
c Implement the following inheritance

6M
Ans interface Salary
{
double Basic Salary =10000.0;
void Basic Sal ();
}
class Employee
{
String Name;
int age;
Employee(String n, int b)
{
Name=n;
age=b;
}
void Display()
{
[Link]("Name of Employee
:"+Name);
[Link]("Age of Employee :"+age);
}
}
class Gross_Salary extends Employee implements Salary
{
double HRA,TA,DA;
Gross_Salary(String n, int b, dou ble h,double t,double d)
{
super(n,b);
HRA=h;
(Interface: 1M,
Employee class:
2M,

Gross_ Salary
class: 3M)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


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

24 |
24
TA=t;
DA=d;
}
public void Basic_Sal()
{
[Link]("Basic Salary
:"+Basic_Salary);
}
void Total_Sal()
{
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
[Link]("Total Salary :"+Total_Sal);
}
}
class EmpDetails
{ public static void main(String args[])
{ Gross_Salary s=new
Gross_Salary("Sachin",20,1000,2000,7000);
s.Total_Sal();
}
}
(Any other logic
considered)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 1 | 24

WINTER – 2022 EXAMINATION


Subject Name: Java Programming Model Answer Subject Code:

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 i n
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 b e some difference in the candidate’s 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
candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi
and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic
year 2021 -2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual
language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching
of concepts with
model answer.
Q.
No. Sub
Q. N. Answer Marking
Scheme
1 Attempt any FIVE of the following: 10 M
a) State any four relational operators and their use. 2 M
Ans
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
= = Equal to
!= Not equal to 2M (1/2 M
each)
Any Four
b) Enlist access speci fiers in Java. 2 M
Ans The access specifiers in java specify accessibility (scope) of a data member,
method, constructor or class. There are 5 types of java access specifier :
 public
 private 2M (1/2 M
each)
Any Four 22412
XXXXX
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 2 | 24

 default (Friendly)
 protected
 private protected
c) Explain constructor with suitable example. 2 M
Ans Constructors are used to assign initial value to instance variable of the class.
It has the same name as class name in which it resides and it is syntactically similar
to any method.
Constructors do not have return value, not even ‘void’ because they return the instance
if
class.
Constructor called by new operator.
Example:
class Rect
{
int length, breadth;
Rect() //constructor
{
length=4; breadth=5;
}
public static void main(String args[])
{
Rect r = new Rect();
[Link](“Area : ” +([Link]*[Link]));
}
}
Output : Area : 20 1M-
Explanation
1M-
Example
d) List the types of inheritance which is supported by java. 2 M
Ans
Any two
1 M each

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 3 | 24

e) Define thread. Mention 2 ways to create thread. 2 M


Ans 1. Thread is a smallest unit of executable code or a single task is also called as thread.
2. Each tread has its own local variable, program counter and lifetime.
3. A thread is similar to program that has a single flow of control.
There are two ways to create threads in java:
1. By extending thread class
Syntax: -
class Mythread extends Thread
{
-----
}
2. Implementing the Runnable Interface
Syntax:
class MyThrea d implements Runnable
{
public void run()
{
------
} 1 M-
Define
Thread

1M -2ways
to create
thread
f) Distinguish between Java applications and Java Applet (Any 2 points) 2 M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 4 | 24

Ans

Applet Application
Applet does not use main()
method for initiating execution of
code Application use main() method
for initiating execution of code
Applet cannot run independently Application can run
independently
Applet cannot read from or write
to files in local com puter Application can read from or
write to files in local computer
Applet cannot communicate with
other servers on network Application can communicate
with other servers on network
Applet cannot run any program
from local computer. Application can run any program
from local computer.
Applet are restricted from using
libraries from other language
such as C or C++ Application are not restricted
from using libraries from other
language
Applets are event driven. Applications are control driven.
1 M for
each point
(any 2
Points)
g) Draw the hierarchy of stream classes. 2 M
Ans

Fig: hierarchy of stream classes


2M-Correct
diagram

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 5 | 24

2. Attempt any THREE of the following: 12 M


a) Write a program to check whether the given number is prime or not. 4 M
Ans Code:
class PrimeExample
{
public static void main(String args[]){
int i,m=0,flag=0;
int n=7;//it is the number to be checked
m=n/2;
if(n==0||n==1){
[Link](n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
[Link](n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { Syste [Link](n+" is prime number"); }
}//end of else
}
}
Output:
7 is prime number
4M (for any
correct
program
and logic)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 6 | 24

b) Define a class employee with data members 'empid , name and salary.
Accept data for three objects and display it 4 M
Ans class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader([Link]));
[Link]("Enter Emp number : ");
empid=[Link]([Link]());
[Link]("Enter Emp Name : ");
name=[Link]();
[Link]("Enter Emp Salary : ");
salary=[Link]([Link]());
}
void show()
{
[Link]("Emp ID : " + empid);
[Link](“Name : " + name);
[Link] ntln(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3; i++)
{
e[i] = new employee(); e[i].getdata();
}
[Link](" Employee Details are : ");
for(inti=0; i<3; i++)
e[i].show();
}
}

4M (for
correct
program
and logic)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 7 | 24

c) Describe Life cycle of thread with suitable diagram. 4 M


Ans 1) Newborn State
A NEW Thread (or a Born Thread) is a thread that's been created but not yet
started. It remains in this state until we start it using the start() method.
The following code snippet shows a newly created thread that's in the NEW state:
Runnable runnable = new NewState();
Thread t = new Thread(runnable);

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().
Runnable runnable = new NewState();
Thread t = new Thread(runnable ); [Link]();
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.

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


by resume().
o 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().
o 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
stop() 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
1M-digram
of life
cycle
3M-
explanation

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 8 | 24

Fig: Life cycle of Thread


d) Write a program to read a file (Use character stream) 4 M
Ans import [Link];
import [Link];
public class IOStreamsExample {
public static void main(String args[]) throws IOException {
//Creating FileReader object
File file = new File("D:/[Link]");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) [Link]()];
//Readi ng data from the file
[Link](chars);
//Writing data to another file
File out = new File("D:/[Link]");
FileWriter writer = new FileWriter(out);
//Writing data to the file
[Link](chars);
writer.f lush();
[Link]("Data successfully written in the specified file");
}
}
4M (for
correct
program
and logic)

3. Attempt any THREE of the following: 12 M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 9 | 24
a) Write a program to find reverse of a number. 4 M
Ans public class ReverseNumberExample1
{ public static void main(S tring [] args)
{
int number = 987654, reverse =0;
while(number !=0)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10;
}
[Link](“The reverse of the given number is: “ + reverse);
} } Any
Correct
program
with proper
logic -4M
b) State the use of final keyword with respect to inheritance. 4 M
Ans Final keyword : 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 m ethod overriding is one of Java’ s most powerful
features,
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 fin al:
class A
{
final void meth()
{
[Link]("This is a final method."); Use of final
keyword -2
M
Program -2
M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 10 | 24
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
[Link]("Illegal!");
}
}
As base class declared method as a final , derived class can not override the definition of
base class methods.
c) Give the usage of following methods
i) drawPolygon ()
ii) DrawOval ()
iii) drawLine ()
iv) drawArc () 4 M
Ans i) drawPolygon ():
 drawPolygon() method is used to draw arbitrarily shaped figures.
 Syntax: void drawPolygon(int x[], int y[], int numPoints)
‟The polygon‟ s 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;
[Link](xpoints,ypoints,num);
ii) drawOval ():
 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 he ight 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: [Link](10,10,50,50);
ii) drawLine ():
 The drawLine() method is used to draw line which take two pair of coordinates, Method
use
with
description
1M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 11 | 24

(x1,y1) and (x2,y2) as arguments and draws a line between them.


 The graphics object g is passed to paint() method.
 Syntax: [Link](x1,y1,x2,y2);
 Example: [Link](100,100,300,300;)
iv) drawArc ()
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 aroun d the arc
Example: [Link](10, 10, 30, 40, 40, 90);
d) Write any four methods of file class with their use. 4 M
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, or null if this pathname does not name a parent
directory
public String getPath() Converts this abstract pathname into a pathname string.
public boolean isAbsolute() Tests whether this abstract pathname is absolute. Returns
true if this abstract pathname is absolute, false otherwise
public boolean exists() Tests whether the file or directory denoted by this abstract
pathname exists. Returns true if and on ly if the file or
directory denoted by this abstract pathname exists; false
otherwise
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 pathn ame exists and is a directory; false
otherwise.
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 -dependent criteria. Any
nondirectory 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.
One
method
1M
4. Attempt any THREE of the following: 12 M
a) Write all primitive data types available in Java with their storage Sizes in 4 M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 12 | 24

bytes.
Ans
Data Type Size
Byte 1 Byte
Short 2 Byte
Int 4 Byte
Long 8 Byte
Double 8 Byte
Float 4 Byte
Char 2 Byte
boolean 1 Bit Data type
name, size
and default
value and
description
carries 1 M
b) Write a program to add 2 integer, 2 string and 2 float values in a vector.
Remove the element specified by the user and display the list. 4 M
Ans import [Link].*;
import [Link].*;
import [Link].*;
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");
Float s7=new Float(1.1f);
Float s8=new Float(1 .2f);
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
[Link](s7);
[Link](s8);
[Link](v);
[Link](s2);
[Link](4);
[Link](v);
}
} Correct
program - 4
M, stepwise
can give
marks
c) Devel op a program to create a class ‘ Book’ having data members author, title
and price. Derive a class 'Booklnfo' having data member 'stock position ’ and 4 M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 13 | 24

method to initialize and display the information for three objects .


Ans class Book
{
String author, title, publisher;
Book(String a, String t, String p)
{
author = a;
title = t;
publisher = p;
}
}
class BookInfo extends Book
{
float price;
int stock_position;
BookInfo(String a, String t, String p, float amt, int s)
{
super(a, t, p);
price = amt;
stock_position = s;
}
void show()
{
[Link]("Book Details:");
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Publisher: " + publisher);
[Link]("Pric e: " + price);
[Link]("Stock Available: " + stock_position);
}
}
class Exp6_1
{
public static void main(String[] args)
{
BookInfo ob1 = new BookInfo("Herbert Schildt", "Complete Reference", "ABC
Publication", 359.50F,10);
BookInfo ob2 = new BookInfo("Ulman", "system programming", "XYZ Publication",
359.50F, 20);
BookInfo ob3 = new BookInfo("Pressman", "Software Engg", "Pearson Publication",
879.50F, 15);
[Link](); Correct
program - 4
M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 14 | 24

[Link]();
[Link]();
}
}
OUTPUT
Book Details:
Title: Complete Reference
Author: Herbert Schildt
Publisher: ABC Publication
Price: 2359.5
Stock Available: 10
Book Details:
Title: system programming
Author: Ulman
Publisher: XYZ Publication
Price: 359.5
Stock Available: 20
Book Details:
Title: Software Engg
Author: Pressman
Publisher: Pearson Publication
Price: 879.5
Stock Available: 15
d) Mention the steps to add applet to HTML file. Give sample code. 4 M
Ans Adding Applet to the HTML file:
Steps to add an applet in HTML document
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the body section
of HTML
file.
2. Specify the name of the applet’s .class file.
3. If the .class file is not in the current directory then use the codebase parameter to
specify: -
a. the relative path if file is on the local system, or
b. the uniform resource locator(URL) of the directory containing the file if it is on a remote
computer.
4. Specify the space required for display of the applet in terms of width and height in
pixels.
5. Add any user -defined parameters using <param> tags
6. Add alternate HTML text to be displayed when a non -java browser is used.
7. Close the applet declaration with the </APPLET> tag.
Open notepad and type the following source code and save it into file nam e Steps – 2M
Example –
2M

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 15 | 24

“[Link]”
import [Link].*;
import [Link].*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
[Link]("Hello Java",10,100);
}}
Use the java compiler to compile the applet “[Link]” file.
C:\jdk> javac H [Link]
After compilation “[Link]” file will be created. Executable applet is nothing but
the .class file
of the applet, which is obtained by compiling the source code of the applet. If any error
message is
received, then check the errors, c orrect them and compile the applet again.
We must have the following files in our current directory.
o [Link]
o [Link]
o [Link]
If we use a java enabled web browser, we will be able to see the entire web page containing
the
applet.
We have included a pair of <APPLET..> and </APPLET> tags in the HTML body section.
The
<APPLET…> tag supplies the name of the applet to be loaded and tells the browser how
much space
the applet requires. The <APPLET> tag given below specifies the minimum requirements
to place the
HelloJava applet on a web page. The display area for the applet output as 300 pixels width
and 200
pixels height. CENTER tags are used to display area in the center of the screen.
<APPLET CODE = [Link] WIDTH = 400 HEIGHT = 200 > </APPLET>
Example: Adding applet to HTML file:
Create [Link] file with following code:
<HTML>
<! This page includes welcome title in the title bar and displays a welcome message. Then
it specifies
the applet to be loaded and executed.
>
<HE AD> <TITLE> Welcome to Java Applet </TITLE> </HEAD>
<BODY> <CENTER> <H1> Welcome to the world of Applets </H1> </CENTER> <BR>
<CENTER>

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 16 | 24

<APPLET CODE=[Link] WIDTH = 400 HEIGHT = 200 > </APPLET>


</CENTER>
</BODY>
</HTML>
e) Write a program to copy contents of one file to another. 4 M
Ans import [Link].*;
class copyf
{
public static void main(String args[]) throws IOException
{
BufferedReader in=null;
BufferedWriter out=null;
try
{
in=new BufferedReader(new FileReader("[Link]"));
out=new BufferedWriter(new FileWriter("[Link]"));
int c;
while((c=[Link]())!= -1)
{
[Link](c);
}
[Link]("File copied successfully");
}
finally
{
if(in!=null)
{
[Link]();
}
if(out!=null)
{
[Link]();
}
}
}
} Correct
program - 4
M

5. Attempt any TWO of the following: 12 M


a) Compare array and vector. Explain elementAT( ) and addElement( ) methods. 6 M
Ans

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 17 | 24

Sr.
No. Array Vector
1 An array is a structure that holds
multiple values of the same type. The Vector is similar to array holds
multiple objects and like an array; it
contains components that can be
accessed using an integer index.
2 An array is a homogeneous data type
where it can hold only objects of one
data type. Vectors are heterogeneous. You can
have objects of different data types
inside a Vector.
3 After creation, an array is a fixed -
length structure. The size of a Vector can grow or shrink
as needed to accommodate adding and
removing items after the Vector has
been created.
4 Array can store primitive type data
element. Vector are store non -primitive type data
element
5 Array is unsynchronized i.e.
automatically increase the size when
the initialized size will be exceed. Vector is synchronized i.e. when the
size will be exceeding at the time;
vector size will increase double of
initial size.
6 Declaration of an array :
int arr[] = new int [10]; Declaration of Vector:
Vector list = new Vector(3);
7 Array is the static memory allocation. Vector is the dynamic memory
allocation
8 Array allocates the memory for the
fixed size ,in array there is wastage of
memory. Vector allocates the memory
dynamically means according to the
requirement no wastage of memory.
9 No methods are provided for adding
and removing elements. Vector provides methods for adding and
removing elements.
10 In array wrapper classes are not used. Wrapper classes are used in vector
11 Array is not a class. Vector is a class.
elementAT( ):
The elementAt() method of Java Vector class is used to get the element at the specified

4 M for
any 4
correct
points
1 M for
elementAt()
1 M for
addElement
()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 18 | 24

index in the vector. Or The elementAt() method returns an element at the specified index.
addElement( ):
The addElement() method of Java Vector class is used to add the specified element to the
end of this vector. Adding an element increases the vector size by one.
b) Write a program to create a class 'sa lary with data members empid', ‘name'
and ‘ basicsalary'. Write an interface 'Allowance ’ which stores rates of
calculatio n for da as 90% of basic salary, hra as 10% of basic salary and pf as
8.33% of basic salary. Include a method to calculate net salary and display i t. 6 M
Ans interface allowance
{
double da=0.9*basicsalary;
double hra=0.1*basicsalary;
double pf=0.0833*basicsalary;
void netSalary();
}

class Salary
{
int empid;
String name;
float basicsalary;
Salary(int i, String n, float b)
{
empid=I;
name=n;
basicsalary =b;
}
void display()
{
[Link]("Empid of Emplyee="+empid);
[Link]("Name of Employee="+name);
[Link]("Basic Salary of Employee="+ basicsalary);
}
}

class net_salary extends salary implements allowance


{
float ta;
net_salary(int i, String n, float b, float t)
{ 6 M for
correct
program

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 19 | 24

super(i,n,b);
ta=t;
}
void disp()
{
display();
[Link]("da of Employee="+da);
}
public void netsalary()
{
double net_sal=basicsalary+ta+hra+da;
[Link]("netSalary of Employe e="+net_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
net_salary s=new net_salary(11, “abcd”, 50000);
[Link]();
[Link]();
}
}
c) Define an exception called 'No Match Exception' that is thrown when the
passward accepted is not equal to "MSBTE'. Write the program. 6 M
Ans import [Link].*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader([Link]) );
[Link]("Enter a word:");
String str= [Link]();
try
{ 6 M for
correct
program

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 20 | 24

if ([Link]("MSBTE")!=0) // can be done with equals()


throw new NoMatchException("Strings ar e not equal");
else
[Link]("Strings are equal");
}
catch(NoMatchException e)
{
[Link]([Link]());
}
}
}

6. Attempt any TWO of the following: 12 M


a) Write a program to check whether the string provided by the user is palindrome
or not. 6 M
Ans import [Link].*;
import [Link].*;
import [Link].*;
class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter String:");
String word=[Link]( );
int len=[Link]( ) -1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{ 6 M for
correct
program

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 21 | 24

if([Link](l)==[Link](r))
{
l++;
r--;
}
else
{
flag=0;
break;
}
}
if(flag==1)
{
[Link]("palindrome");
}
else
{
[Link]("not palindrome");
}
}
}
b) Define thread priority ? Write default priority values and the methods to set
and change them. 6 M
Ans 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.
Default priority v alues as follows 2 M for
define
Thread
priority
2 M for

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 22 | 24

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.
getPriority(): The [Link]() method returns the priority of the given
thread.
setPriority(int newPriority): The [Link]() method updates or assign
the priority of the thread to newPriority. The method throws IllegalArgumentException if
the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
import [Link].*;

public class ThreadPriorityExample extends Thread


{
public void run()
{
[Link]("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
[Link]("Priority of the thread th1 is : " + [Link]());
[Link]("Priority of the thread th2 is : " + [Link]());
[Link]("Priority of the thread th2 is : " + [Link]());
[Link](6);
[Link](3);
[Link](9);
[Link]("Priority of the thread th1 is : " + [Link]());
[Link]("Priority of the thread th2 is : " + [Link]());
[Link]("Priority of the thread th3 is : " + [Link]());
[Link].p rintln("Currently Executing The Thread : " +
[Link]().gtName());
[Link]("Priority of the main thread is : " +
[Link]().getPrority();
[Link]().setPriority(10);
[Link]("Priority of the main thread is : " +
[Link]().getPiority());
} default
priority
values

2 M for
method to
set and
change

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 23 | 24

}
c) Design an applet to perform all arithmetic operations and display the result by using
labels. textboxes and buttons. 6 M
Ans import [Link].*;
import [Link].*;
public class sample extends Frame implements ActionListener {
Label l1, l2,l3;
TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;
sample() {
l1=new Lable(“First No.”);
[Link](10, 10, 50, 20);
tf1 = new TextField();
[Link](50, 50, 150, 20);
l2=new Lable(“Second No.”);
[Link](10, 60, 50, 20);
tf2 = new TextField();
[Link](50, 100, 150, 20);
l3=new Lable(“Result”);
[Link](10, 110, 150, 20);
tf3 = new TextField();
[Link](50, 150, 150, 20);
[Link]( false );
b1 = new Button("+");
[Link](50, 200, 50, 50);
b2 = new Button(" -");
[Link](120,200,50,50);
b3 = new Button("*");
[Link](220, 200, 50, 50);
b4 = new Button("/");
[Link](320,200,50,50);
[Link]( this);
[Link]( this);
[Link]( this);
[Link]( this);

add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(b4); 6 M for
correct
program

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION


(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 24 | 24
setSize(400,400);
setLayout( null);
setVisible( true);
}
public void actionPerformed(ActionEvent e) {
String s1 = [Link]();
String s2 = [Link]();
int a = [Link](s1);
int b = [Link](s2);
int c = 0;
if ([Link]() == b1){
c = a + b;
}
else if ([Link]() == b2){
c = a - b;
else if ([Link]() == b3){
c = a * b;
else if ([Link]() == b4){
c = a / b;
}
String result = [Link](c);
[Link](result);
}
public static void main(String[] args) {
new sample();
}
}

You might also like