0% found this document useful (0 votes)
16 views145 pages

Ilovepdf Merged

Uploaded by

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

Ilovepdf Merged

Uploaded by

khaparderahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

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

WINTER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
Important Instructions to examiners:
1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the 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. S. Answer Marking
No. Q. Scheme
No.
1 A Attempt any three of the following. 3x4=12
a) Explain following terms related to Java features. 4
i) Object Oriented ii) Complied and interpreted.
Ans: i) Object Oriented: 2 Marks for
 Almost everything in java is in the form of object. each)
 All program codes and data reside within objects and classes.
 Similar to other OOP languages java also has basic OOP properties
such as encapsulation, polymorphism, data abstraction, inheritance
etc.
 Java comes with an extensive set of classes (default) in packages.

ii) Compiled and Interpreted:


 Java is a two staged system. It combines both approaches.
 First java compiler translates source code into byte code instruction.
Byte codes are not machine instructions.
 In the second stage java interpreter generates machine code that can
be directly executed by machine. Thus java is both compile and
interpreted language.
b) Differentiate between Input stream class and Reader class. 4
Ans: any 4
Input Stream Class Reader Class Correct
Input Streams are used to read Reader classes are used to read Points. 1
bytes from a stream. character streams. Mark for
Input Stream class useful for Reader classes are best used to one point)
binary data such as images, video read character data.
1
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

and serialized objects.


Input Stream classes are used to Reader class is used to read 16 bit
read 8 bit bytes. Unicode character stream.
An Input Stream is byte-oriented.A Reader is character-oriented.
Constructor: InputStream() Constructor:
Reader() and Reader(Object lock)
Methods: Methods:
read(); read();
read(byte[] b); read(char[] buf);
read(byte[] b, int off, int len); read(char[] buf, int off, int len);
read(charBuffer dest);
c) Explain any two logical operators in java with example. 4
Ans: Logical Operators: Logical operators are used when we want to form 2 Marks for
compound conditions by combining two or more relations. Java has three each
logical operators: operator.
&& : Logical AND Any 2
|| : Logical OR operators)
! : Logical NOT

Example:
public class Test
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output:
a && b = false
a || b = true
!(a && b) = true
d) Describe life cycle of thread. 4
Ans: 1 Mark for
correct
diagram,
3 M for
proper
explanation

Thread Life Cycle Thread has five different states throughout its life.
2
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state
to another by different methods and ways.
1. Newborn state: When a thread object is created it is said to be in a new
born state. When the thread is in a new born state it is not scheduled running
from this state it can be scheduled for running by start() or killed by stop(). If
put in a queue it moves to runnable state.
2. Runnable State: It means that thread is ready for execution and is waiting
for the availability of the processor i.e. the thread has joined the queue and is
waiting for execution. If all threads have equal priority, then they are given
time slots for execution in round robin fashion. The thread that relinquishes
control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
3. Running State: It means that the processor has given its time to the thread
for execution. The thread runs until it relinquishes control on its own or it is
pre-empted by a higher priority thread.
4 Blocked State: A thread can be temporarily suspended or blocked from
entering into the runnable and running state by using either of the following
thread method.
suspend() : Thread can be suspended by this method. It can be rescheduled
by resume().
wait(): If a thread requires to wait until some event occurs, it can be done
using wait method and can be scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using
sleep(time) where time is in ms. It reenters the runnable state as soon as
period has elapsed /over.
5 Dead State: Whenever we want to stop a thread form running further we
can call its stop(). The statement causes the thread to move to a dead state. A
thread will also move to dead state automatically when it reaches to end of
the method. The stop method may be used when the premature death is
required
1 B Attempt any One of the following. 1x6=6
a) Define a class ‘Book’ with data members bookid, bookname and price. 6
Accept data for seven objects using Array of objects and display it.
Ans: import java.lang.*; Correct
import java.io.*; program
class Book with proper
{ logic 4
String bookname; Marks
int bookid;
int price;
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
void getdata()
{
3
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

try
{
System.out.println("Enter Book ID=");
bookid=Integer.parseInt(br.readLine());
System.out.println("Enter Book Name=");
bookname=br.readLine();
System.out.println("Enter Price=");
price=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Error");
}
}
void display()
{
System.out.println("Book ID="+bookid);
System.out.println("Book Name="+bookname);
System.out.println("Price="+price);
}
}
class bookdata
{
public static void main(String args[])
{
Book b[]=new Book[7];
for(int i=0;i<7;i++)
{
b[i]=new Book();
}
for(int i=0;i<7;i++)
{
b[i].getdata();
}
for(int i=0;i<7;i++)
{
b[i].display();
}
}
}
b) What is interface? Describe its syntax and features. 6
Ans: Definition: Java does not support multiple inheritances with only classes. Definition:
Java provides an alternate approach known as interface to support concept of 1 Mark,
multiple inheritance. An interface is similar to class which can define only 1 Mark for
abstract methods and final variables. syntax and
Syntax: 2 Marks for
access interface InterfaceName Features
{
Variables declaration;
4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Methods declaration;
}

Features:
 The interfaces are used in java to implementing the concept of
multiple inheritance.
 The members of an interface are always declared as constant i.e. their
values are final.
 The methods in an interface are abstract in nature. I.e. there is no code
associated with them.
 It is defined by the class that implements the interface.
 Interface contains no executable code.
 We are not allocating the memory for the interfaces.
 We can‘t create object of interface.
 Interface cannot be used to declare objects. It can only be inherited by
a class.
 Interface can only use the public access specifier.
 An interface does not contain any constructor.
 Interfaces are always implemented.
 Interfaces can extend one or more other interfaces.
2 Attempt any Two of following 2x8=16
a) Write a program to create a vector with seven elements as 8
rd th
(10,30,50,20,40,10,20). Remove elements 3 and 4 position. Insert new
elements at 3rd position. Display original and current size of vector.
Ans: import java.util.*; (Correct
public class VectorDemo Program
{ with
public static void main(String args[]) Correct
{ logic 8
Vector v = new Vector(); marks
v.addElement(new Integer(10)); Creation of
v.addElement(new Integer(30)); vector:
v.addElement(new Integer(50)); 3Marks,
v.addElement(new Integer(20)); removing
v.addElement(new Integer(40)); elements 2
v.addElement(new Integer(10)); Marks
v.addElement(new Integer(20)); inserting
System.out println(v.size()); // display original size element 1
v.removeElementAt(2); // remove 3rd element Mark
v.removeElementAt(3); // remove 4th element Display
v.insertElementAt(11,2) // new element inserted at 3rd position original size
System.out.println("Size of vector after insert delete operations: " + v.size()); : 1 Mark
} and
} Current
size:
1Mark)

b) What is package in Java? Write a program to create a package and 8


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

import the package in another class.


Ans: Package: Java provides a mechanism for partitioning the class namespace (Definition:
into more manageable parts called package (i.e package are container for a 2 Mark,
classes). The package is both naming and visibility controlled mechanism. any correct
Package can be created by including package as the first statement in java Program
source code. Any classes declared within that file will belong to the specified with proper
package. logic: 6
Syntax: Mark)
package pkg;
Here, pkg is the name of the package

Program:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}

Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
c) Write syntax and example of 8
i)Draw Poly ii)Draw Rect iii)Filloval iv)Draw Arc()
Ans: i) Draw Poly: drawPoly() method is used to draw arbitrarily shaped figures. (Each one
Syntax: void drawPoly(int x[], int y[], int numPoints) for 2 Mark)
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;
g.drawPoly(xpoints,ypoints,num);

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

ii) Draw Rect: The drawRect() method display an outlined rectangle.


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

iii)Fill Oval: Drawing Ellipses and circles: To draw an Ellipses or circles


used fillOval() method can be used. It draws the Solid Ellipses and circles.
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 to draw filled circle, specify the same width and height
the following program draws several ellipses and circle.
Example: g.fillOval(10,10,50,50);

iv) Draw Arc(): It is used to draw arc.


Syntax:
void drawArc(int x, int y, int w, int h, int start_angle, int sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle is
starting angle of arc, sweep_angle is degree around the arc
Example: g.drawArc(10, 10, 80, 40, 10, 90);
3 Attempt any four of the following: 4x4=16
a) Differentiate between array and Vector. 4
Ans: any 4
Array Vector Correct
An Array is a structure that holds The Vector is similar to array Points. 1
multiple values of same data type. which holds multiple values but Mark for
different data types. one point)
Array is a fixed-Length structure. The size of a vector can grow or
shrink as per the requirement.
Array is a data structure. Vector is a Class.
Array is primitive data type. Vector implements the List
interface.
Array is a static-memory Vector is a dynamic-memory
allocation. allocation.
No methods provided by Array Vector provides methods for
for doing operations on values. doing operations like adding,
deleting, inserting, etc…
Wrapper classes are not used. Wrapper classes are used in
vector.
Declaration of Array: Declaration of vector:
int a[]=new int[10]; Vector v=new Vector(4,5);
b) Write a program to calculating area and perimeter of rectangle. 4
Ans: import java.io.*; 4m for
import java.lang.*; Correct
class rect program
{ and logic
public static void main(String args[]) throws Exception
7
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

{
DataInputStream dr=new DataInputStream(System.in);
int l,w;
System.out.println(“Enter length and width:”);
l=Integer.parseInt(dr.readLine());
w=Integer.parseInt(dr.readLine());
int a=l*w;
System.out.println(“Area is=”+a);
int p=2(l+w);
System.out.println(“Area is=”+p);
}
}
c) Explain fileinputstream class to read the content of a file. 4
Ans: Java FileInputStream class obtains input bytes from a file. It is used for 4m for
reading byte-oriented data (streams of raw bytes) such as image data, audio, proper
video etc. You can also read character-stream data. But, for reading streams explanation
of characters, it is recommended to use File Reader class.
Java FileInputStream class methods
Method Description
It is used to return the estimated number of bytes that
int available()
can be read from the input stream.
It is used to read the byte of data from the input
int read()
stream.
It is used to read up to b.length bytes of data from the
int read(byte[] b)
input stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.
It is used to skip over and discards x bytes of data
long skip(long x)
from the input stream.
FileChannel It is used to return the unique FileChannel object
getChannel() associated with the file input stream.
FileDescriptor
It is used to return the FileDescriptor object.
getFD()
protected void It is used to ensure that the close method is call when
finalize() there is no more reference to the file input stream.
void close() It is used to closes the stream.

Program for Reading contents from file:


import java.io.*;
public class f_demo
{
public static void main(String args[]) throws Exception
{
File f=new File(“c:/input.txt”);
DataInputStream dr=new DataInputStream(new FileInputStream(f));
while(dr.available() !=0)

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

{
System.out.println(dr.readLine());
}
dr.close();
}
}
d) Explain applet life cycle with suitable diagram. 4
Ans: Java applet inherits features from the class Applet. Thus, whenever an applet 1m for
is created, it undergoes a series of changes from initialization to destruction. diagram
Various stages of an applet life cycle are depicted in the figure below: and
3 marks for
explanation

Initial State: When a new applet is born or created, it is activated by calling


init() method. At this stage, new objects to the applet are created, initial
values are set, images are loaded and the colors of the images are set. An
applet is initialized only once in its lifetime.
It's general form is:
public void init( )
//Action to be performed
}
Running State: An applet achieves the running state when the system calls
the start() method. This occurs as soon as the applet is initialized. An applet
may also start when it is in idle state. At that time, the start() method is
overridden.
It's general form is:
public void start( )
{
//Action to be performed
}
Idle State: An applet comes in idle state when its execution has been stopped
either implicitly or explicitly. An applet is implicitly stopped when we leave
the page containing the currently running applet. An applet is explicitly
stopped when we call stop() method to stop its execution.
It's general form is:
public void stope
{
//Action to be performed
}
Dead State: An applet is in dead state when it has been removed from the
9
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

memory. This can be done by using destroy() method.

It's general form is:


public void destroy( )
{
//Action to be performed
}
Display State (paint ()): Apart from the above stages, Java applet also
possess paint( ) method. The paint() method is used for applet display on the
screen. This method helps in drawing, writing and creating colored
backgrounds of the applet. It takes an argument of the graphics class. To use
The graphics, it imports the package java.awt.Graphics
e) What is use of super and final with respect to inheritance. 4
Ans: Super Keyword: The super keyword in Java is a reference variable which is 2m for
used to refer immediate parent class object. Whenever you create the instance Use of
of subclass, an instance of parent class is created implicitly which is referred super
by super reference variable. And
Usage of Java super Keyword 2m for
 super can be used to refer immediate parent class instance variable. Final
 super can be used to invoke immediate parent class method. keyword
 super() can be used to invoke immediate parent class constructor.
Example:
class A
{
int i;
A(int a, iont b)
{
i=a+b;
}
void add()
{
System.out.println(“sum of a and b=”+i);
}
}
class B extends A
{
int j;
B(int a,int b, int c)
{
super(a,b);
j=a+b+c;
}
void add()
{
super.add();
System.out.println(“Sum of a, b and c is:” +j);
}
}

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

Final Keyword: A parameter to a function can be declared with the keyword


“final”.
This indicates that the parameter cannot be modified in the function.
The final keyword can allow you to make a variable constant.

Example:
Final Variable: The final variable can be assigned only once. The value of a
final variable can never be changed.
final float PI=3.14;

Final Methods: A final method cannot be overridden. Which means even


though a sub class can call the final method of parent class without any issues
but it cannot override it.
Example:
class XYZ
{
final void demo(){
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ{


void demo()
{
System.out.println("ABC Class Method");
}

public static void main(String args[])


{
ABC obj= new ABC();
obj.demo();
}
}

The above program would throw a compilation error, however we can use the
parent class final method in sub class without any issues.
class XYZ
{
final void demo(){
System.out.println("XYZ Class Method");
}
}

class ABC extends XYZ


{
public static void main(String args[])
{
ABC obj= new ABC();
11
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

obj.demo();
}
}
Output:
XYZ Class Method

final class: We cannot extend a final class. Consider the below example:
final class XYZ
{
}

class ABC extends XYZ


{
void demo()
{
System.out.println("My Method");
}
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
The type ABC cannot subclass the final class XYZ
4 A Attempt any THREE of following. 3x4=12
a) Explain type casting with suitable example. 4
Ans: In Java, type conversion is performed automatically when the type of the 4m for
expression on the right hand side of an assignment operation can be safely proper
promoted to the type of the variable on the left hand side of the assignment. explanation
Assigning a value of one type to a variable of another type is known as Type
Casting.

Every expression has a type that is determined by the components of the


expression.
Example:
double x;
int y=2;
float z=2.2f;
x=y+z;
12
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

The expression to the right of the “=“ operator is solved first and the result is
stored in x. The int value is automatically promoted to the higher data type
float (float has a larger range than int) and then, the expression is evaluated.
The resulting expression is of float data type. This value is then assigned to x,
which is a double (larger range than float) and therefore, the result is a
double.
Java automatically promotes values to a higher data type, to prevent any loss
of information.
Example: int x=5.5/2
In above expression the right evaluates to a decimal value and the expression
on left is an integer and cannot hold a fraction. Compiler will give you
following error.
“Incompatible type for declaration, Explicit vast needed to convert double to
int.”
This is because data can be lost when it is converted from a higher data type
to a lower data type. The compiler requires that you typecast the assignment.
Solution: int x=(int)5.5/2;
b) Explain following clause w.r.t. exception handling 4
i) try ii) catch iii) throw iv) finally
Ans: try: Program statements that you want to monitor for exceptions are 1m for each
contained within a try block. If an exception occurs within the try block, it is term
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 ExceptionType1
}

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 important 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
13
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

c) Write a program to print sum of even numbers from 1 to 20. 4


Ans: public class sum_of_even 4m for
{ Correct
public static void main(String[] args) program
{ and logic
int sum=0;
for (int i=0; i<=20;i=i+2)
{
sum = sum+i;
}
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Sum of even numbers: 110
d) Differentiate between Applet and Application. 4
Ans: any 4
Applet Application Correct
Applets run in web pages. Applications run on stand-alone Points. 1
systems. Mark for
Applets are not full featured Applications are full featured one point)
application programs. programs.
Applets are the small programs. Applications are larger programs.
Applet starts execution with its Application starts execution with its
init(). main ().
Parameters to the applet are given in Parameters to the application are
the HTML file. given at the command prompt.
Applet cannot access the local file Application can access the local file
system and resources. system and resources.
Applets are event driven Applications are control driven.
4 B Attempt any ONE of the following. 1x6=6
a) Write a program to create an applet for displaying circle, rectangle and 6
triangle one below the other and filled them with red, green and yellow
respectively.
import java.awt.*; To display
import java.applet.*; circle with
/* <applet code="test.class" width=200 height=200> red
</applet> */ color=2m
To display
public class test extends Applet rectangle
{ with green
public void paint(Graphics g) color=2m
{ To display
triangle
g.setColor(Color.RED); with yellow
g.fillOval(80,50,50,50); color=2m
14
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

g.setColor(Color.GREEN);
g.fillRect(50,120,100,50);

g.setColor(Color.YELLOW);
int x1[]={50, 100, 150, 50};
int y1[]={250, 200, 250, 250};
int n1=4;
g.fillPolygon(x1, y1, n1);

}
}

Output:

b) Describe following methods related to vector addElement(), 6


removeElement() and insertElementAt().
Ans: addElement(): Adds the specified component to the end of the vector, 2m for each
increasing its size by one. method
Syntax: void addElement(Object obj)
Example:
v.addElement("Apple");
v.addElement(10);

removeElement():Removes the specified component from the vector.


Decreasing the size of vector.
Syntax: removeElement(Object obj)
Example: v.removeElement(“Apple”);

insertElementAt():Inserts the item at nth position.


Syntax: insertElementAt(item,n)
Example: v.insertElementAt(“Orange”,3);
5 Attempt any two of the following: 2x8=16
a) Explain following terms: i) Thread priority ii) Types of Exception 8
Ans: (i) Thread Priority: In java, each thread is assigned a priority which affects Explanation
the order in which it is scheduled for running. Threads of same priority are of thread
15
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

given equal treatment by the java scheduler. The Thread class defines several priority=4m
priority constants as Explanation
MIN_PRIORITY=1 of Types of
NORM_PRIORITY=5 Exception=
MAX_PRIORITY=10 4m
Thread priorities can take values from 1 to 10.
To set the priority Thread class provides setPriority() method as
Thread.setPriority(priority value);
Eg: If t1 is a Thread class object then
T1.setPriority(Thread.MAX_PRIORITY);
To see the priority value of a thread the method available is getPrioriy() as
int Thread.getPriority();
eg : int p= Thread.getPriority();

(ii) Types of Exceptions: Java exceptions can be classified as Built-in


exceptions and user defined exceptions
1) Built-in Exceptions: Built-in exceptions are the exceptions which are
available in Java libraries. These exceptions are suitable to explain certain
error situations. Below is the list of important built-in exceptions in Java.
Arithmetic Exception: It is thrown when an exceptional condition has
occurred in an arithmetic operation.
ArrayIndexOutOfBoundException: It is thrown to indicate that an array
has been accessed with an illegal index. The index is either negative or
greater than or equal to the size of the array.
ClassNotFoundException: This Exception is raised when we try to access a
class whose definition is not found
FileNotFoundException: This Exception is raised when a file is not
accessible or does not open.
IOException: It is thrown when an input-output operation failed or
interrupted

2) User-Defined Exceptions: Sometimes, the built-in exceptions in Java are


not able to describe a certain situation. In such cases, user can also create
exceptions which are called ‘user-defined Exceptions’.
Following steps are followed for the creation of user-defined Exception.
The user should create an exception class as a subclass of Exception class.
Since all the exceptions are subclasses of Exception class, the user should
also make his class a subclass of it. This is done as:
class MyException extends Exception
We can create a parameterized constructor with a string as a parameter.We
can use this to store exception details.
MyException(String str)
{
super(str);
}
To raise exception of user-defined type, we need to create an object to his
exception class and throw it using throw clause, as
throw new MyException(“Error message here….”);
b) Write a program to create two threads.so one thread will print even 8
16
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

numbers between 1 to 10 whereas other will print odd number between


11 to 20.
Ans: class eventhread extends Thread Correct
{ Logic : 4 M,
public void run() Correct
{ syntaxes : 4
for(int i=1;i<=10;i=i+2) M
{
System.out.println("Even no="+ i);
}
}
}
class oddthread extends Thread
{
public void run()
{
for(int i=11;i<=20;i=i+2)
{
System.out.println("Odd no="+ i);
}
}
}
class threadtest
{
public static void main(String args[])
{
eventhread e1= new eventhread();
oddthread o1= new oddthread();
e1.start();
o1.start();
}
}
Output:
E:\java\bin>javac threadtest.java
E:\java\bin>java threadtest
Odd no=11
Even no=2
Odd no=13
Odd no=15
Even no=4
Even no=6
Odd no=17
Odd no=19
Even no=8
Even no=10
c) How can parameters be passed to an applet? Write an applet to accept 8
username in the parameter and print “Hello<username> “.
Ans: User defined parameters can be passed using <Param> tag. Parameter
Parameters are passed to an applet when it is loaded. We can call passing
17
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

getParameter() method to collect the value of parameter sent from <param> explanation
tag to applet. getParameter() takes one String argument representing name of : 2M,
the parameter and returns the value of the same. In program
Syntax: : correct
<Param name=”variable-name” value=”value of the variable> logic 3M,
String getParameter(“variable-name”); correct
Program: syntaxes :
import java.awt.*; 3M
import java.applet.*;
public class myapplet extends Applet
{
String uname="";
public void paint(Graphics g)
{
uname=getParameter("username");
g.drawString("Hello "+uname,100,100);
}
}
/*<applet code=myapplet height=300 width=300>
<param name="username" value="ABC">
</applet>*/
Output:

6 Attempt any four of the following 4x4=16


a) Demonstrate the concept of method overriding with example. 4
Ans: Method overriding: In a class hierarchy, when method in a subclass has Explanation
same name, type, & parameter list as a method in superclass then the method of method
is said to override the method in superclass. When an overridden method is overriding:
called from within a subclass it will always refer to the version of method 2M, correct
defined by subclass. The version of method from superclass will be hidden. example:
Example: 2M
class overridetest
{
int x,y;
overridetest(int a,int b)
{
x=a;
y=b;
}
18
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

void display()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
}
class test extends overridetest
{
int z;
test(int a,int b,int c)
{
super(a,b);
z=c;
}
void display() //method overridden
{
super.display(); //call to super class display()
System.out.println("z="+z);
}
public static void main(String args[])
{
test t= new test(4,5,6);
t.display();
}
}
b) Write any two methods of file and file input stream class each. 4
Ans: File class methods: Any two
boolean canExecute() : Tests whether the application can execute the file methods
denoted by this abstract pathname. from file
boolean canRead() : Tests whether the application can read the file denoted class=2m
by this abstract pathname. Any two
boolean canWrite() : Tests whether the application can modify the file methods
denoted by this abstract pathname. from
int compareTo(File pathname) : Compares two abstract pathnames fileinput
lexicographically. stream=2m
boolean createNewFile() : Atomically creates a new, empty file named by
this abstract pathname .
static File createTempFile(String prefix, String suffix) : Creates an empty
file in the default temporary-file directory.
boolean delete() : Deletes the file or directory denoted by this abstract
pathname.
boolean equals(Object obj) : Tests this abstract pathname for equality with
the given object.
boolean exists() : Tests whether the file or directory denoted by this abstract
pathname exists.
String getAbsolutePath() : Returns the absolute pathname string of this
abstract pathname.
long getFreeSpace() : Returns the number of unallocated bytes in the
partition
19
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

String getName() : Returns the name of the file or directory denoted by this
abstract pathname.
String getParent() : Returns the pathname string of this abstract pathname’s
parent.
File getParentFile() : Returns the abstract pathname of this abstract
pathname’s parent.
String getPath() : Converts this abstract pathname into a pathname string.
boolean isDirectory() : Tests whether the file denoted by this pathname is a
directory.
boolean isFile() : Tests whether the file denoted by this abstract pathname is
a normal file.
boolean isHidden() : Tests whether the file named by this abstract pathname
is a hidden file.
long length() : Returns the length of the file denoted by this abstract
pathname.
String[] list() : Returns an array of strings naming the files and directories in
the directory .
File[] listFiles() : Returns an array of abstract pathnames denoting the files in
the directory.
boolean mkdir() : Creates the directory named by this abstract pathname.
boolean renameTo(File dest) : Renames the file denoted by this abstract
pathname.
boolean setExecutable(boolean executable) : A convenience method to set
the owner’s execute permission.
boolean setReadable(boolean readable) : A convenience method to set the
owner’s read permission.
boolean setReadable(boolean readable, boolean ownerOnly) : Sets the
owner’s or everybody’s read permission.
boolean setReadOnly() : Marks the file or directory named so that only read
operations are allowed.
boolean setWritable(boolean writable) : A convenience method to set the
owner’s write permission.
String toString() : Returns the pathname string of this abstract pathname.
URI toURI() : Constructs a file URI that represents this abstract pathname.

FileInputStream class methods :


int available(): It is used to return the estimated number of bytes that can be
read from the input stream.
int read():It is used to read the byte of data from the input stream.
int read(byte[] b): It is used to read up to b.length bytes of data from the
input stream.
int read(byte[] b, int off, int len): It is used to read up to len bytes of data
from the inpu stream.
long skip(long x) :It is used to skip over and discards x bytes of data from
the input stream.
FileChannel getChannel() : It is used to return the unique FileChannel
object associated with the file input stream.
FileDescriptor getFD() : It is used to return the FileDescriptor object.
protected void finalize() : It is used to ensure that the close method is call
20
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

when there is no more reference to the file input stream.


void close(): It is used to closes the stream.
c) Design an applet which displays rectangle filled with blue colour and 4
display message as “MSBTE EXAM” in red colour below it.
Ans: import java.awt.*; Correct
import java.applet.*; logic: 2M,
public class myapplet extends Applet Correct
{ syntaxes:
public void paint(Graphics g) 2M
{
g.setColor(Color.blue);
g.fillRect(50,50,100,50);
g.setColor(Color.red);
g.drawString("MSBTE EXAM",60,120);
}
}

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


</applet>*/

Output:

d) Write a program to demonstrate multiple inheritances. 4


Ans: interface sports Program
{ logic
int sports_weightage=5; showing
void calc_total(); multiple
} inheritance
: 2M,
class person correct
{ syntaxes :
String name; 2M
String category;
person(String nm,String c)
{
name=nm;
category=c;
}
21
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

}
class student extends person implements sports
{
int marks1,marks2;
student(String n,String c, int m1,int m2)
{
super(n,c);
marks1=m1;
marks2=m2;
}
public void calc_total()
{
int total;
if (category.equals("sportsman"))
total=marks1+marks2+sports_weightage;
else
total=marks1+marks2;
System.out.println("Name="+name);
System.out.println("Category ="+category);
System.out.println("Marks1="+marks1);
System.out.println("Marks2="+marks2);
System.out.println("Total="+total);
}
public static void main(String args[])
{
student s1=new student("ABC","sportsman",67,78);
student s2= new student("PQR","non-sportsman",67,78);
s1.calc_total();
s2.calc_total();
}
}
e) Write a program to find greater number among two numbers using 4
conditional operator.
Ans: class greater correct logic
{ 1 M, correct
public static void main(String args[]) use of
{ conditional
int a,b; operator
int bignum; :2M, other
a=100; correct
b=150; syntaxes :
bignum=(a>b?a:b); //conditional operator 1M
System.out.println("Greater number between "+a+ " and "+b +" is =
"+bignum);
}
}
Output:
E:\java\bin>javac greater.java
E:\java\bin>java greater
22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Greater number between 100 and 150 is = 150

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming 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
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the 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. Sub Answer Marking


No Q.N. Scheme
.
1. Attempt any FIVE of the following: 10
a) List any eight features of Java. 2M
Ans. Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence Any
5. Portability eight
6. Robust features
2M
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic
b) State use of finalize( ) method with its syntax. 2M
Ans. Use of finalize( ):
Sometimes an object will need to perform some action when it is

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 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 collected these resources should be freed. To handle such
situations java provide a mechanism called finalization. In Use 1M
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: Syntax
protected void finalize() { 1M
}
c) Name the wrapper class methods for the following: 2M
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
Ans. (i) To convert string objects to primitive int:
String str=”5”;
int value = Integer.parseInt(str); 1M for
each
(ii) To convert primitive int to string objects: method
int value=5;
String str=Integer.toString(value);
d) List the types of inheritances in Java. 2M
(Note: Any four types shall be considered)
Ans. Types of inheritances in Java:
i. Single level inheritance Any
ii. Multilevel inheritance four
iii. Hierarchical inheritance types
iv. Multiple inheritance ½M
v. Hybrid inheritance each

e) Write the syntax of try-catch-finally blocks. 2M


Ans. try{
//Statements to be monitored for any exception
} catch(ThrowableInstance1 obj) { Correct
//Statements to execute if this type of exception occurs syntax
} catch(ThrowableInstance2 obj2) { 2M
//Statements
}finally{

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

//Statements which should be executed even if any exception happens


}
f) Give the syntax of < param > tag to pass parameters to an applet. 2M
Ans.
Syntax:
<param name=”name” value=”value”> Correct
syntax
Example: 2M
<param name=”color” value=”red”>

g) Define stream class. List its types. 2M


Ans. Definition of stream class:
An I/O Stream represents an input source or an output destination. A
stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs, and Definitio
memory arrays. Streams support many different kinds of data, n 1M
including simple bytes, primitive data types, localized characters, 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 Types
ii. Character stream classes. 1M

2. Attempt any THREE of the following: 12


a) Explain the concept of platform independence and portability 4M
with respect to Java language.
(Note: Any other relevant diagram shall be considered).
Ans. Java is a platform independent language. This is possible because
when a java program is compiled, 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 Explana
JVM which is the interpreter for the byte code. Byte code is not a tion 3M
machine specific 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
computer 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
Page 3 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

byte code.

Diagram
1M

b) Explain the types of constructors in Java with suitable example. 4M


(Note: Any two types shall be considered).
Ans. 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. Explana
The types of constructors are: tion of
1. Default constructor the two
2. Constructor with no arguments types of
3. Parameterized constructor construc
4. Copy constructor tors 2M

1. Default constructor: Java automatically creates default constructor


if there is no default or parameterized constructor written by user. Example
Default constructor in Java initializes member data variable to default 2M
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;

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

public static void main(String args[]) {


test1 t = new test1(); // default constructor is called.
System.out.println(t.i);
System.out.println(t.s);
System.out.println(t.b);
System.out.println(t.bt);
System.out.println(t.ft);
}
}
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_no;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
s.display();
}
}

3. Parametrized constructor: 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;

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

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

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


a new object 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 = obj.length;
breadth= obj.breadth;
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
System.out.println("Area of First Rectangle : "+
(r1.length*r1.breadth));

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

System .out.println("Area of First Second Rectangle : "+


(r1.length*r1.breadth));
}
}
c) Explain the two ways of creating threads in Java. 4M
Ans. Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending the Thread class.
Thread class provide constructors and methods to create and perform 2M
operations on a thread. This class implements the Runnable interface. each for
When we extend the class Thread, we need to implement the method explaini
run(). Once we create an object, we can call the start() of the thread ng of
class for executing the method run(). two
Eg: types
class MyThread extends Thread { with
public void run() { example
for(int i = 1;i<=20;i++) {
System.out.println(i);
}
}
public static void main(String a[]) {
MyThread t = new MyThread();
t.start();
}
}
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++) {
System.out.println(i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
t.start();
}

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

d) Distinguish between Input stream class and output stream class. 4M


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

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

3. Attempt any THREE of the following: 12


a) Define a class student with int id and string name as data 4M
members and a method void SetData ( ). Accept and display the
data for five students.
Ans. import java.io.*;
class student
{
int id;
String name;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
void SetData() Correct
{ logic 4M
try
{
System.out.println("enter id and name for student");
id=Integer.parseInt(br.readLine());
name=br.readLine();
}
catch(Exception ex)
{}
}
void display()
{
System.out.println("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();
}

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

for(i=0;i<5;i++)
{
arr[i].display();
}
}
}
b) Explain dynamic method dispatch in Java with suitable example. 4M
Ans. 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 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
Explana
(not the type of the reference variable) that determines which version
tion 2M
of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This
is also known as upcasting. Java 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 versions 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()
{
System.out.println("Inside A's m1 method");
}
}
Example
2M
class B extends A
{
// overriding m1()
void m1()

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("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();

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

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

// 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();
}
}
c) Describe the use of following methods: 4M
(i) Drawoval ( )
(ii) getFont ( )
(iii) drawRect ( )
(iv) getFamily ( )
Ans. (i) Drawoval ( ): Drawing Ellipses and circles: To draw an Ellipses
or circles used drawOval() method can be used. Syntax: void
drawOval(int top, int left, int width, int height) The ellipse is drawn
within a bounding rectangle whose upper-left corner is specified by
top and left and whose width and height are specified by width and
height.To draw a circle or filled circle, specify the same width and Each
height. method
1M
Example: g.drawOval(10,10,50,50);

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


property
Font f = g.getFont();
String fontName = f.getName();
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: g.drawRect(10,10,60,50);

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

(iv) getFamily ( ): The getfamily() method Returns the family of the


font.
String family = f.getFamily();
Where f is an object of Font class
d) Write a program to count number of words from a text file using 4M
stream classes.
(Note : Any other relevant logic shall be considered)
Ans. import java.io.*;
public class FileWordCount
{
public static void main(String are[]) throws IOException
{
File f1 = new File("input.txt");
int wc=0;
FileReader fr = new FileReader (f1); Correct
int c=0; program
try 4M
{
while(c!=-1)
{
c=fr.read();
if(c==(char)' ')
wc++;
}
System.out.println("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
fr.close();
}
}
}
4. Attempt any THREE of the following: 12
a) Describe instance Of and dot (.) operators in Java with suitable 4M
example.
Ans. 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).

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

The instance of in java is also known as type comparison 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{ Descript
public static void main(String args[]){ ion and
Simple1 s=new Simple1(); example
of each
System.out.println(sinstanceofSimple1);//true
operator
} 2M
}

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
this.name=”john”; where name is a instance variable referenced by
‘this’ keyword
c.getdata(); where getdata() is a method invoked on object ‘c’.
b) Explain the four access specifiers in Java. 4M
Ans. 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. Each
2) default access specifier: If you don’t specify any access control access
specifier, it is default, i.e. it becomes implicit public and it is specifier
accessible within the program. s 1M
3) protected access specifier: The 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.

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

c) Differentiate between method overloading and method 4M


overriding.
Ans. Sr. Method overloading Method overriding
No.
1 Overloading occurs when Overriding means having two
two or more methods in methods with the same
one class have the same method name and parameters Any
method name but different (i.e., method signature) four
parameters. points
2 In contrast, reference type The real object type in the 1M each
determines which run-time, not the reference
overloaded method will be variable's type, determines
used at compile time. which overridden method is
used at runtime
3 Polymorphism not applies Polymorphism applies to
to overloading overriding
4 overloading is a compile- Overriding is a run-time
time concept. concept
d) Differentiate between Java Applet and Java Application (any 4M
four points)
Ans. Sr. Java Applet Java Application
No.
1 Applets run in web pages Applications run on stand-
alone systems.
2 Applets are not full Applications are full featured
featured application programs.
programs. Any
3 Applets are the small Applications are larger four
programs. programs. points
4 Applet starts execution Application starts execution 1M each
with its init(). with its main ().
5 Parameters to the applet Parameters to the application
are given in the HTML are given at the command
file. prompt
6 Applet cannot access the Application can access the
local file system and local file system and
resources resources.
7 Applets are event driven Applications are control
driven.

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

e) Write a program to copy content of one file to another file. 4M


Ans. class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("input.txt");
FileOutputStream out= new FileOutputStream("output.txt");
int c=0; Correct
try logic 2M
{
while(c!=-1)
{
c=in.read(); Correct
out.write(c); Syntax
} 2M
System.out.println("File copied to output.txt....");
}
finally
{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
}
}
5. Attempt any TWO of the following: 12
a) Describe the use of any methods of vector class with their syntax. 6M
(Note: Any method other than this but in vector class shall be
considered for answer).
Ans.  boolean add(Object obj)-Appends the specified element to the
end of this Vector.
 Boolean add(int index,Object obj)-Inserts the specified element at Any 6
the specified position in this Vector. methods
 void addElement(Object obj)-Adds the specified component to with
the end of this vector, increasing its size by one. their use
 int capacity()-Returns the current capacity of this vector. 1M each
 void clear()-Removes all of the elements from this vector.
 Object clone()-Returns a clone of this vector.

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 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 insertElementAt(Object obj,int index)-Inserts the specified
object as a component in this vector at the specified index.
 Object remove(int index)-Removes the element at the specified
position in this vector.
 void removeAllElements()-Removes all components from this
vector and sets its size to zero.
b) Explain the concept of Dynamic method dispatch with suitable 6M
example.
Ans. 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 called through a superclass reference,
Explana
Java determines which version (superclass/subclasses) of that method
tion 3M
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 known 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, different versions of the method are
executed. Here is an example that illustrates dynamic method
dispatch:

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

/ A Java program to illustrate Dynamic Method


// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1() Example
void m1() 3M
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("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();

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 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 object


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

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

c) Write a program to create two threads. One thread will display 6M


the numbers from 1 to 50 (ascending order) and other thread will
display numbers from 50 to 1 (descending order).
Ans. class Ascending extends Thread
{
public void run()
{
for(int i=1; i<=15;i++)
{
System.out.println("Ascending Thread : " + i); Creation
} of two
} threads
} 4M

class Descending extends Thread Creating


{ main to
public void run() create
{ and start
for(int i=15; i>0;i--) { objects
System.out.println("Descending Thread : " + i); of 2
} threads:
} 2M
}

public class AscendingDescending Thread


{
public static void main(String[] args)
{
Ascending a=new Ascending();
a.start();
Descending d=new Descending();
d.start();
}
}
6. Attempt any TWO of the following: 12
a) Explain the command line arguments with suitable example. 6M
Ans. Java Command Line Argument:
The java command-line argument is an argument i.e. passed at the
time of running the java program.

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 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.
4M for
Command Line Arguments can be used to specify configuration explanat
information while launching your application. ion
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 example 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 args[]){
System.out.println("Your first argument is: "+args[0]); 2M for
} example
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
b) Write a program to input name and salary of employee and 6M
throw user defined exception if entered salary is negative.
Ans. import java.io.*;
class NegativeSalaryException extends Exception Extende
{ d
public NegativeSalaryException (String str) Exceptio
{ n class
super(str); with
} construc
} tor 2M
public class S1

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

{
public static void main(String[] args) throws IOException
{ Acceptin
BufferedReaderbr= new BufferedReader(new g data
InputStreamReader(System.in)); 1M
System.out.print("Enter Name of employee");
String name = br.readLine();
System.out.print("Enter Salary of employee");
int salary = Integer.parseInt(br.readLine()); Throwin
Try g user
{ defining
if(salary<0) Exceptio
throw new NegativeSalaryException("Enter Salary amount n with
isnegative"); try catch
System.out.println("Salary is "+salary); and
} throw
catch (NegativeSalaryException a) 3M
{
System.out.println(a);
}
}
}
c) Describe the applet life cycle in detail. 6M
Ans.

2M
Diagram

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

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

SUMMER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

are performed in this method.

start(): The start() method contains the actual code of the applet that 4M
should run. The start() method executes immediately after descripti
the init() method. It also executes whenever the applet is restored, on
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() method 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()

Page 23 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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 (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the 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. Sub Answer Marking


No. Q. N. 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 Definition:1Mark
an object immediately upon creation. It has the same name as Types: 1 Mark
class name in which it resides and it is syntactically similar to
any method. When a constructor is not defined, java executes a
default constructor which initializes all numeric members to zero
and other types to null or spaces. Once defined, constructor is
automatically called immediately after the object is created
before new operator completes.

Types of constructors:

1. Default constructor
2. Parameterized constructor
3. Copy constructor
b Define Class and Object. 2M

1|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Ans Class: A class is a user defined data type which groups data Definition 1
members and its associated functions together. Mark each

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

c List the methods of File Input Stream Class. 2M


Ans • void close() Any Two Each
• int read() for 1 Mark
• int read(byte[] b)
• read(byte[] b, int off, int len)
• int available()

d Define error. List types of error. 2M


Ans • Errors are mistakes that can make a program go wrong. Errors Definition: 1m
may be logical or may be typing mistakes. An error may List: 1m
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 categories:

1. Compile time errors

2. Runtime errors
e List any four Java API packages. 2M
Ans 1.java.lang 1/2 Marks for
2.java.util one Package
3.java.io
4.java.awt
5.java.net
6.ava.applet

f Define array. List its types. 2M


Ans An array is a homogeneous data type where it can hold only Definition 1
objects of one data type. Mark, List 1
Mark
Types of Array:

2|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

1)One-Dimensional

2)Two-Dimensional
g List access specifiers in Java. 2M
Ans 1)public Any 2, 1M for
each
2)private

3)friendly

4)protected

5)Private Protected

2. Attempt any Three of the following: 12M


a Differentiate between String and String Buffer. 4M
Ans Any 4 Points
String String Buffer c 4 Marks

String is a major class String Buffer is a peer class


of String

Length is fixed (immutable) Length is flexible (mutable)

Contents of object cannot be Contents of object can be


modified modified

Object can be created by Objects can be created by


assigning String constants calling constructor of String
enclosed in double quotes. Buffer class using “new”

Ex:- String s=”abc”; Ex:- StringBuffer s=new


StringBuffer (“abc”);

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

3|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

float pi,radius;

abc(float p, float r)

pi=p;

radius=r;

void area()

float ar=pi*radius*radius;

System.out.println("Area="+ar);

void display()

System.out.println("Pi="+pi);

System.out.println("Radius="+radius);

}}

class area

public static void main(String args[])

abc a=new abc(3.14f,5.0f);

a.display();

4|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

a.area();

}
c Define exception. State built-in exceptions. 4M
Ans An exception is a problem that arises during the execution of a Definition 2
program. Marks, List: 2
Marks
Java exception handling is used to handle error conditions in a
program systematically 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.
• NullPointerException: 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.
• OutOfMemoryException: 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 stack space.

d Write syntax and example of : 4M

5|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

1) drawRect()

2)drawOval()
Ans 1)drawRect() : drawRect:
2Marks,
drawRect () method display an outlined rectangle. drawOval: 2
Marks
Syntax: void drawRect(int top,int left, int width,int height)

The upper-left corner of the Rectangle is at top and left. The


dimension of the Rectangle is specified by width and height.

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

2) drawOval( ): Drawing Ellipses and circles: To draw an


Ellipses or circles used drawOval () method can be used.

Syntax: void drawOval(int top, int left, int width, int height)

The ellipse is drawn within a bounding rectangle whose upper-


left corner is specified by top and left and whose width and
height are specified by width and height to draw a circle or filled
circle, specify the same width and height the following program
draws several ellipses and circle.
Example: g.drawOval(10,10,50,50);

3. Attempt any Three of the following:


a Explain the following classes. 4M
i)Byte stream class
ii)Character Stream Class
Ans i)Byte stream class: 2M for any two
points
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

6|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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 performing


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 working with characters or
strings.
3. Writer stream classes are designed to 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 FileWriter (for writing
characters).

b Explain life cycle of Applet. 4M


Ans When an applet begins, the AWT calls the following methods, in 1M for diagram
this sequence: ,3M for
explanation
1. init( )

2. start( )

3. paint( )

When an applet is terminated, the following sequence of method


calls takes place:

4. stop( )

5. destroy( )

7|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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


where you should initialize Variables. This method is called only
once during 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 Graphics.

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 environment


determines that your applet needs to be removed completely from
memory.

c Differentiate between class and interfaces. 4M


Ans 1M for each
Class Interface point
1)doesn’t Supports multiple 1) Supports multiple
inheritance inheritance
2)”extend ” keyword is used 2)”implements ” keyword is
to inherit used to inherit
3) class contain method body 3) interface contains abstract
method(method without
body)

8|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

4)contains any type of 4)contains only final variable


variable
5)can have constructor 5)cannot have constructor
6)can have main() method 6)cannot have main() method

7)syntax 7)syntax
Class classname Inteface Innterfacename
{ {
Variable declaration, Final Variable declaration,
Method 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 1M for
casting or type casting. definition,3M for
types explanation
2. If the two types are compatible, then java will perform the
conversion automatically.
3. It is possible to assign an int value to long variable.
4. However, if the two 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:

1.Implicit type-casting:

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

9|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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

10 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Ans 2M for
diagram,2M for
explanation

Thread Life Cycle Thread has five different states throughout its
life.

1. Newborn State

2. Runnable State

3. Running State

4. Blocked State

5. Dead State

Thread should be in any one state of above and it can be move


from one state to another by different methods and ways.

Newborn state: When a thread object is created it is said to be in


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

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

11 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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 2M for
functionality defined in this method will never be altered in any definition,2M for
way, ie a final method cannot be overridden. example

Syntax:

final void findAverage()

{
//implementation
}
Example of declaring a final method:
class A
{

12 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

final void show()


{
System.out.println(“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
System.out.println(“in show of B”);
}}
Final variable: the value of a final variable cannot be changed.
Final variable behaves like class variables and they do not take
any space on individual objects of the class.

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 2M for each
form compound conditions by combining two or more relations. operator with eg.
Java has three logical operators as shown in table:

Operator Meaning
&& Logical
AND
|| Logical
OR
! Logical
NOT
Program demonstrating logical Operators

public class Test

13 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

public static void main(String args[])

boolean a = true;

boolean b = false;

System.out.println("a && b = " + (a&&b));

System.out.println("a || b = " + (a||b) );

System.out.println("!(a && b) = " + !(a && b));

Output:

a && b = false

a || b = true

!(a && b) = true

d Differentiate between array and vector. 4M


Ans any four points
1m for each point

Array Vector
1) An array is a structure that 1)The Vector is similar to
holds multiple values of the array holds multiple objects
same type. and like an array; it contains
components that can be
accessed using an integer
index.

14 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

2) An array is a homogeneous 2) Vectors are heterogeneous.


data type where it can hold You can have objects of
only objects of one data type. different data types inside a
Vector.

3) After creation, an array is a 3) The size of a Vector can


fixed-length structure. grow or shrink as needed to
accommodate adding and
removing items after the
Vector has been created.
4) Array can store primitive 4) Vector are store non-
type data element. primitive type data element.

5)Declaration of an array : 5)Declaration of Vector:

int arr[] = new int [10]; Vector list = new Vector(3);

6) Array is the static memory 6) Vector is the dynamic


allocation. memory allocation.
e List any four methods of string class and state the use of 4M
each.
Ans The java.lang.String class provides a lot of methods to work on any four methods
string. By the help of these methods, of string class
can be
We can perform operations on string such as trimming, considered
concatenating, converting, comparing, replacing strings etc.

1) to Lowercase (): Converts all of the characters in this String


to lower case.

Syntax: s1.toLowerCase()

Example: String s="Sachin";

System.out.println(s.toLowerCase());

Output: sachin

2)to Uppercase():Converts all of the characters in this String to


upper case

15 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Syntax: s1.toUpperCase()

Example:

String s="Sachin";

System.out.println(s.toUpperCase());

Output: SACHIN

3) trim (): Returns a copy of the string, with leading and trailing
whitespace omitted.

Syntax: s1.trim()

Example:

String s=" Sachin ";

System.out.println(s.trim());

Output:Sachin

4) replace ():Returns a new string resulting from replacing all


occurrences of old Char in this string with new Char.

Syntax: s1.replace(‘x’,’y’)

Example:

String s1="Java is a programming language. Java is a platform.";

String s2=s1.replace("Java","Kava"); //replaces all occurrences


of "Java" to "Kava"

System.out.println(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, 6M
15, 25, 35, 45). Insert new element at 2nd position. Remove 1st
and 4th element from vector.

16 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Ans import java.util.*; (Vector creation


class VectorDemo with elements – 2
{ M,
public static void main(String[] args)
{
Vector v = new Vector();
v.addElement(new Integer(5));
v.addElement(new Integer(15));
v.addElement(new Integer(25));
v.addElement(new Integer(35)); Insert new
v.addElement(new Integer(45)); element – 2M,
System.out.println("Original array elements are
");
for(int i=0;i<v.size();i++) Remove elements
{ 2 M,
System.out.println(v.elementAt(i));
} (Any other logic
v.insertElementAt(new Integer(20),1); // insert can be
new element at 2nd position considered)
v.removeElementAt(0);
//remove first element
v.removeElementAt(3);
//remove fourth element
System.out.println("Array elements after insert
and remove operation ");
for(int i=0;i<v.size();i++)
{
System.out.println(v.elementAt(i));
}}}
b Define package. How to create user defined package? 6M
Explain with example.
Ans Java provides a mechanism for partitioning the class namespace (Definition of
into more manageable parts. This mechanism is the package. The package - 1M,
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

17 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

which classes are stored.


The syntax for defining a package is:
package pkg;
Here, pkg is the name of the package
eg : package
mypack; Package creation
Packages are mirrored by directories. Java uses file system - 2M
directories to store packages. The class files of any classes which
are declared in a package must be stored in a directory which has
same name as package name. The directory must match with the
package name exactly. A hierarchy can be created by separating
package name and sub package name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3. Example - 3M
Syntax:
To access package In a Java source file, import statements
occur immediately following the package statement (if
it exists) and before any class definitions.
Syntax:
(Note Any other
import pkg1[.pkg2].(classname|*); example can be
Example: considered)
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class volume
{

18 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

public static void main(String args[])


{
Box b=new Box();
b.display();
}
}
c Write a program to create two threads one thread will print 6M
even no. between 1 to 50 and other will print odd number
between 1 to 50.
Ans import java.lang.*; Creation of two
class Even extends Thread threads 4M
{
public void run()
{
try
{
for(int i=2;i<=50;i=i+2)
{
System.out.println("\t Even thread :"+i); Creating main to
sleep(500); create and start
} objects of 2
} threads: 2M
catch(InterruptedException e)
{System.out.println("even thread interrupted");
}
}
}
class Odd extends Thread
{ (Any other logic
public void run() can be
{ considered)
try
{
for(int i=1;i<50;i=i+2)
{
System.out.println("\t Odd thread :"+i);
sleep(500);

19 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

}
}
catch(InterruptedException e)
{System.out.println("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 6M
to accept username in the form of parameter and print “Hello
<username>”.
Ans Passing Parameters to Applet
• User defined parameters can be supplied to an applet (Explanation for
using <PARAM…..> tags. parameter
passing - 3M,
• PARAM tag names a parameter the Java applet needs to
run, and provides a value for that parameter.
• PARAM tag can be used to allow the page designer to
specify different colors, fonts, URLs or other data to be Correct Program
used by the applet. – 3M
To set up and handle parameters, two things must be done.
1. Include appropriate <PARAM..>tags in the HTML document.
The Applet tag in HTML document allows passing the
arguments using param tag. The syntax of <PARAM…> tag
<Applet code=”AppletDemo” height=300 width=300>
<PARAM NAME = name1 VALUE = value1> </Applet>
NAME:attribute name
VALUE: value of attribute named by
corresponding PARAM NAME.

20 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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


Applet access their attributes using the getParameter method.
The syntax is : String getParameter(String name);
Program
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc> </Applet>
</HTML>
(OR)
import java.awt.*;
import java.applet.*;
/*<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>*/
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}

21 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

public void paint(Graphics g)


{
g.drawString(str,10,100);
}
}

b Write a program to perform following task 6M


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

FileWriter fw = new FileWriter("Sample.txt");


//create text file for writing
System.out.println("Enter data to be inserted in (Any other logic
file: "); can be
String fileData = br1.readLine(); considered )
fw.write(fileData);
fw.close();
BufferedReader br = new BufferedReader(new
FileReader("Sample.txt"));
while ((line = br.readLine()) != null)
{
lineCount++; // no of lines count
String[] words = line.split(" ");
wordCount = wordCount + words.length;
// no of words count
}
System.out.println("Number of lines is : " +
lineCount);
System.out.println("Number of words is : " +
wordCount);
}

22 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

}
c Implement the following inheritance 6M

Ans interface Salary


{ (Interface: 1M,
double Basic Salary=10000.0;
void Basic Sal();
}
class Employee
{
String Name;
int age; Employee class:
Employee(String n, int b) 2M,
{
Name=n;
age=b;
}
void Display()
{
System.out.println("Name of Employee
:"+Name);
System.out.println("Age of Employee :"+age);
} Gross_Salary
} class: 3M)
class Gross_Salary extends Employee implements Salary
{
double HRA,TA,DA;
Gross_Salary(String n, int b, double h,double t,double d)
{
super(n,b);
HRA=h;

23 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

TA=t;
DA=d; (Any other logic
} considered)
public void Basic_Sal()
{
System.out.println("Basic Salary
:"+Basic_Salary);
}
void Total_Sal()
{
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
System.out.println("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();
}
}

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming 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 (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed
constant values may vary and there may be some difference in the 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. Sub Answer Marking


No Q.N. Scheme
1. Attempt any FIVE of the following: 10
a) Enlist the logical operators in Java. 2M
Ans. && : Logical AND 1M each
|| : Logical OR Any two
! : Logical NOT operators
b) Give the syntax and example for the following functions 2M
i) min ( )
ii) Sqrt ( )
Ans. i) min()
Syntax: (Any one of the following) 1M for
static int min(int x, int y) Returns minimum of x and y each
static long min(long x, long y) Returns minimum of x and y function
static float min(float x, float y) Returns minimum of x and y with
static double min(double x, int y) Returns minimum of x and y example
Page 1 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

Example:
int y= Math.min(64,45);
ii)Sqrt()
Syntax:
static double sqrt(double arg) Returns square root of arg.
Example:
double y= Math.sqrt(64);
c) Define the interface in Java. 2M
Ans. Interface is similar to a class.
It consist of only abstract methods and final variables. 1M for
To implement an interface a class must define each of the method each point,
declared in the interface. Any two
It is used to achieve fully abstraction and multiple inheritance in points
Java.
d) Enlist any four inbuilt packages in Java. 2M
Ans. 1.java.lang ½ M for
2.java.util each
3.java.io package
4.java.awt Any four
5.java.net packages
6.java.applet
e) Explain any two methods of File Class 2M
Ans.1. 1. boolean createNewFile(): It creates a new, empty file named by 1M for
this abstract pathname automatically, if and only if no file with the each
same name exists. method
if(file.createNewFile()) Any two
System.out.println("A new file is successfully created."); methods

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


denoted by the object‟s abstract pathname.
System.out.println("File name : " + file.getName());

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.
System.out.println("Parent name : " + file.getParent());

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

4. 4. boolean isFile(): It returns True if the file denoted by the abstract


pathname is a normal file, and False if it is not a normal file.
System.out.println("File size (bytes) : " + file.isFile());

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


file denoted by the abstract pathname, and returns False otherwise.
System.out.println("Is file readable : " + file.canRead());

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


the file denoted by the abstract pathname, and returns False
otherwise.
System.out.println("Is file writeable : " + file.canWrite());

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


the file denoted by the abstract pathname, and returns False
otherwise.
System.out.println("Is file executable : " + file.canExecute());

f) Write syntax of elipse. 2M


Ans. Syntax: void fillOval(int top, int left, int width, int height) 2M for
The filled ellipse is drawn within a bounding rectangle whose upper- correct
left corner is specified by top and left and whose width and height are syntax
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

g) Enlist any four compile time errors. 2M


Ans. 1)Missing semicolon ½ M for
2)Missing of brackets in classes and methods each error
3)Misspelling of variables and keywords.
4)Missing double quotes in Strings. Any four
5)Use of undeclared variable. can be
6)Incompatible type of assignment/initialization. considered
7)Bad reference to object.

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

2. Attempt any THREE of the following: 12


a) Explain any four features of Java 4M
Ans. 1.Object Oriented:
In Java, everything is an Object. Java can be easily extended since it 1M for
is based on the Object model. each
feature
2.Platform Independent: Any four
features
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.

3.Simple:
Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.

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

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

6.Multithreaded:
With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows
the developers to construct interactive applications that can run
smoothly.

7.Interpreted: 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.
Page 4 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

b) Write a Java program to copy the content of one file into another. 4M
Ans. import java.io.*; 2M for
class filecopy correct
{ logic,
public static void main(String args[]) throws IOException
{ 2M for
FileReader fr= new FileReader(“file1.txt"); code
FileWriter fo= new FileWriter("file2.txt");
int ch;
try
{
while((ch=fr.read())!= -1)
{
fo.write(ch);
}
System.out.println(“file copied successfully”);
fr.close();
fo.close();
}
finally
{
if(fr!=null)
fr.close();
if(fo!=null)
fo.close();
}}}

c) Write the difference between vectors and arrays. (any four 4M


points)
Ans. S.No Array Vector 1M for
1 An array is a structure The Vector is similar to array holds each point
that holds multiple multiple objects and like an array;
values of the same it contains components that can be Any four
type. accessed using an integer index. points
2 An array is a Vectors are heterogeneous. You
homogeneous data type can have objects of different data
where it can hold only types inside a Vector.
objects of one data type
Page 5 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

3 After creation, an array The size of a Vector can grow or


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

d) Explain exception handling mechanism w.r.t. try, catch, throw 4M


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

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

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 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 important 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. Attempt any THREE of the following: 12
a) Write a Java Program to find out the even numbers from 1 to 100 4M
using for loop.
Ans. class test
{ 2M for
public static void main(String args[]) Program
{ logic
System.out.println("Even numbers from 1 to 100 :");
for(int i=1;i<=100; i++) 2M for
{ program
if(i%2==0) syntax
System.out.print(i+" ");
}
}
}
b) Explain any four visibility controls in Java. 4M
Ans. Four visibility control specifiers in Java are public, default, private
and protected. The visibility control in java can be seen when concept 3M for
of package is used with the java application. Explanatio
1) private :The access level of a private specifier is only within the n
class. It cannot be accessed from outside the class.
2) default :When no specifier is used in the declaration, it is called as
default specification. Default scope for anything declared in java
Page 7 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

is implicit public. With this it can be accessed anywhere within 1M for


the same package. access
3) protected :The access level of a protected specifier is within the specificatio
package and outside the package through derived class. n table
4) public :The access 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 access: 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 fiveaccess specifiers can be mapped with four categories in
which packages in java can be managed with access specification
matrix as:
Access Modifier Public Protected Friendly Private private
Access Location (default) protected
Same Class Yes Yes Yes Yes Yes
Sub class in same Yes Yes Yes Yes No
package
Other classes in Yes Yes Yes No No
same package
Sub class in other Yes Yes No Yes No
packages
Non sub classes in Yes No No No No
other packages

c) Explain single and multilevel inheritance with proper example. 4M


Ans. Single level inheritance:
In single inheritance, a single subclass extends from a single 1M for
superclass. each
explanatio
n

1M for
Example : each
class A example
{
Page 8 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

void display()
{
System.out.println(“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
System.out.println(“In child class B”);
}
public static void main(String args[])
{
B b= new B();
b.display(); //super class method call
b.show(); // 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()
Page 9 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

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

d) Write a java applet to display the following output in Red color. 4M


Refer Fig. No. 1.

Ans. import java.awt.*; 2M for


import java.applet.*; correct
public class myapplet extends Applet logic

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

{
public void paint(Graphics g) 2M for
{ correct
int x[]={10,200,70}; syntax
int y[]={10,10,100};
g.setColor(Color.red);
g.drawPolygon(x,y,3);
}
}
/*<applet code=myapplet height=400 width=400>
</applet>*/

4. Attempt any THREE of the following: 12


a) Explain switch case and conditional operator in java with 4M
suitable example.
Ans. switch…case statement:
The switch…case statement allows us to execute a block of code
among many alternatives. 1M for
Syntax : explanatio
switch (expression) n
{ switch case
case value1: statement
// code
break; 1M for
case value2: example
// 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 expression
matches with value2.

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 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";
}

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

System.out.println(day);
}
}
Note : any 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 1M for
to handling simple situations in a line. explanatio
Syntax: n
expression1 ? expression2:expression3; Conditiona
The above syntax means that if the value given in Expression1 is true, l operator
then Expression2 will be evaluated; otherwise, expression3 will be
evaluated. 1M for
example
Example
class test
{
public static void main(String[] args) {
String result;
int a = 6, b = 12;
result = (a==b ? "equal":"Not equal");
System.out.println("Both are "+result);
}
}
Note : any other relevant example can be considered.

b) Draw and explain life cycle of thread. 4M


Ans. Life cycle of thread includes following states :
1.Newborn
2. Runnable
3. Running
4. Blocked
5. Dead

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

2M for
diagram

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 2M for
created, but it has not yet been started. A thread is started by calling explanatio
its start() method. n

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, the thread cannot even run
again.
c) Write a java program to sort an 1-d array in ascending order 4M
using bubble-sort.
Ans. public class BubbleSort 2M for
{ correct
public static void main(String[] args) logic

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

{
int arr[] ={3,60,35,2,45,320,5};
System.out.println("Array Before Bubble Sort"); 2M for
for(int i=0; i<arr.length; i++) correct
{ syntax
System.out.print(arr[i] + " ");
}
System.out.println();
int n = arr.length;
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;
}
}
}
System.out.println("Array After Bubble Sort");
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}

d) Explain how to create a package and how to import it 4M


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

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

Example: javac myclass.java to get myclass.class


4) Create a folder which is same as package name and make sure 1M to
that class file of package is present inside it. If not, copy it inside import
this folder.
To import the package inside any other program :
Make use of import statement 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 mypackage.myclass;
or
importmypackage.*;
e) Explain 4M
i) drawLine
ii) drawOval
iii) drawRect
iv) drawArc
Ans. i) drawLine(): It is a method from Graphics class and is used to draw 1M for
line between the points(x1, y1) and (x2, y2). each
Syntax :
drawLine(int x1, int y1, int x2, int y2)

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 equal, 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 Graphics class and is used to draw
a circular or elliptical arc.
Syntax :
drawArc(int x, int y, int width, int height, intstartAngle,
intsweepAngle)

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

where first fourare x, y, width and height as in case of oval or rect.


The next two are start angle and sweep angle.When sweep angle is
positive, it moves in anticlockwise direction. It is given as negative, It
moves in clockwise direction.

5. Attempt any TWO of the following: 12


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

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 (Note:
d:\myPack Code
The java program is to be written and saved in the folder myPack. To snippet can
add a program to the package, the first line in the java program be used for
should be package <name>; followed by imports and the program describing)
logic.

package myPack;
import java.util;
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. 3M for
import mypack.*; Example
public class
MyClassExample{
public static void main(String a[]) {
Myclass c= new Myclass();

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

}
}

Example: (Note Any


other
package package1; similar
public class Box example
{ can be
int l= 5; considered
int b = 7; )
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class volume {
public static void main(String args[])
{
Box b=new Box();
b.display();
}}

b) Write a Java program in which thread A will display the even 6M


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.

Ans. Import java.lang.*;


class A extends Thread
{
public void run() 3M
{ Correct
try program
{ with syntax
for(int i=2;i<=50;i=i+2)
{
Page 18 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

System.out.println("\t A thread :"+i);


if(i == 6) // for 3rd iteration 3M
sleep(500); Correct
} logic
}
catch(Exception e)
{
System.out.println("A thread interrupted");
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int i=1;i<50;i=i+2)
{
System.out.println("\t B thread :"+i);
}
}
catch(Exception e)
{
System.out.println("B thread interrupted");
}
}
}
class OddEven
{
public static void main(String args[])
{
new A().start();
new B().start();
}
}

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

c) What is constructor? List types of constructor. Explain 6M


parameterized constructor with suitable example.
Ans. Constructor:
A constructor is a special member which initializes an object 2M for
immediately upon creation. Definition
• It has the same name as class name in which it resides and it is
syntactically similar to any method.
• When a constructor is not defined, java executes a default
constructor which initializes all numeric members to zero and other
types to null or spaces.
• Once defined, constructor is automatically called immediately after
the object is created before new operator completes.

Types of constructors:
1. Default constructor
2. Parameterized constructor 1M List
3. Copy constructor types
4. Constructor with no arguments or No-Arg Constructor or Non-
Parameterized constructor. (Any 3 )

Parameterized constructor: When constructor method is defined


with parameters inside it, different value sets can be provided to
different constructor with the same name.

Example
class Student {
int roll_no;
String name; 1M
Student(int r, String n) // parameterized constructor parameteri
{ zed
roll_no = r; constructor
name=n;
} 2M
void display() Example
{
(Any Other
System.out.println("Roll no is: "+roll_no);
Example
System.out.println("Name is : "+name);
Can be
}
Page 20 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

public static void main(String a[]) considered


{ )
Student s = new Student(20,"ABC"); // constructor
with parameters
s.display();
}
}
6. Attempt any TWO of the following: 12
a) Write a Java Program to count the number of words from a text 6M
file using stream classes. (Note :
Ans. import java.io.*; Any other
public class FileWordCount { relevant
public static void main(String are[]) throws IOException logic shall
{ be
File f1 = new File("input.txt"); considered
int wc=0; )
FileReader fr = new FileReader (f1);
int c=0;

try { while(c!=-1) 3M
{ Correct
c=fr.read(); program
if(c==(char)' ') with syntax
wc++;
}
System.out.println("Number of words :"+(wc+1));
3M
}
Correct
finally
logic
{
if(fr!=null)
fr.close();
}
}
}
b) Explain the difference between string class and string buffer 6M
class.
Explain any four methods of string class

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

Ans. 1M each
Any 2
points

1M each
Methods of string class Any 4
1)toLowercase (): Methods
Converts all of the characters in this String to lower case. correct
Syntax: s1.toLowerCase() explanatio
Example: String s="Sachin"; n
System.out.println(s.toLowerCase());
Output: sachin

2) toUppercase():
Converts all of the characters in this String to upper case
Syntax: s1.toUpperCase()
Example: String s="Sachin";
System.out.println(s.toUpperCase());
Output: SACHIN
3)trim ():
Returns a copy of the string, with leading and trailing whitespace
omitted.
Syntax: s1.trim()
Example: String s=" Sachin ";
System.out.println(s.trim());

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

Output:Sachin
4)replace ():Returns a new string resulting from replacing all
occurrences of old Char in this string with new Char.
Syntax: s1.replace(‘x’,’y’)
Example: String s1="Java is a programming language. Java is a
platform.";
String s2=s1.replace("Java","Kava"); //replaces all occurrences of
"Java" to "Kava" System.out.println(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”
System.out.println(str.length()); // Returns 5
6. charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .
Eg. String s=”INDIA”
System.out.println(s.charAt(2) ); // returns D

7. substring():
Syntax:
String substring (int startindex)
startindex specifies the index at which the substring will begin.It will
returns a copy of the substring that begins at startindex and runs to the
end of the invoking string
Example:
System.out.println(("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 characters from the

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

beginning index, upto, but not including, the ending index.


Example :
System.out.println(("Welcome”.substring(3,5));//co

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

c) Write a Java applet to draw a bar chart for the following values. 6M

Ans. import java.awt.*;


import java.applet.*; 2M for
Applet tag
/* <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> 2M for
Page 24 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

<param name=label4 value=2014> Syntax


<param name=Columns value=4>
</applet>
*/

public class BarChart extends Applet


{ 2M
int n=0; Correct
String label[]; Logic
int value[];

public void init() {

setBackground(Color.yellow);
try {

int n = Integer.parseInt(getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] = getParameter("label1");
label[1] = getParameter("label2");
label[2] = getParameter("label3");
label[3] = getParameter("label4");
value[0] = Integer.parseInt(getParameter("c1"));
value[1] = Integer.parseInt(getParameter("c2"));
value[2] = Integer.parseInt(getParameter("c3"));
value[3] = Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++) {
g.setColor(Color.black);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.red);
g.fillRect(50,i*50+10,value[i],40);
}

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

SUMMER – 2022 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 22412

}}

Page 26 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2022 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 22412

Important Instructions to examiners: XXXXX


1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the 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. Sub Answer Marking


No. Q. N. Scheme

1 Attempt any FIVE of the following: 10 M

a) State any four relational operators and their use. 2M

Ans 2M (1/2 M
Operator Meaning
each)
< Less than Any Four
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

b) Enlist access specifiers in Java. 2M

Ans The access specifiers in java specify accessibility (scope) of a data member, 2M (1/2 M
method, constructor or class. There are 5 types of java access specifier: each)
 public Any Four
 private

Page No: 1 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
 default (Friendly)
 protected
 private protected
c) Explain constructor with suitable example. 2M

Ans Constructors are used to assign initial value to instance variable of the class. 1M-
It has the same name as class name in which it resides and it is syntactically similar Explanation
to anymethod. 1M-
Constructors do not have return value, not even ‘void’ because they return the instance if Example
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();
System.out.println(“Area : ” +(r.length*r.breadth));
}
}
Output : Area : 20
d) List the types of inheritance which is supported by java. 2M

Ans Any two

1 M each

Page No: 2 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

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

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

Page No: 3 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans 1 M for
each point
(any 2
Applet Application Points)
Applet does not use main() Application use main() method
method for initiating execution of for initiating execution of code
code
Applet cannot run independently Application can run
independently
Applet cannot read from or write Application can read from or
to files in local computer write to files in local computer
Applet cannot communicate with Application can communicate
other servers on network with other servers on network
Applet cannot run any program Application can run any program
from local computer. from local computer.
Applet are restricted from using Application are not restricted
libraries from other language from using libraries from other
such as C or C++ language
Applets are event driven. Applications are control driven.

g) Draw the hierarchy of stream classes. 2M

Ans 2M-Correct
diagram

Fig: hierarchy of stream classes

Page No: 4 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
2. Attempt any THREE of the following: 12 M

a) Write a program to check whether the given number is prime or not. 4M

Ans Code: 4M (for any


correct
class PrimeExample program
{ and logic)

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

System.out.println(n+" is not prime number");

}else{

for(i=2;i<=m;i++){

if(n%i==0){

System.out.println(n+" is not prime number");

flag=1;

break;

if(flag==0) { System.out.println(n+" is prime number"); }

}//end of else

Output:

7 is prime number

Page No: 5 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
b) Define a class employee with data members 'empid , name and salary. 4M
Accept data for three objects and display it
Ans class employee 4M (for
{ correct
int empid; program
String name; and logic)
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter Emp number : ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine();
System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3; i++)
{
e[i] = new employee(); e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<3; i++)
e[i].show();
}
}

Page No: 6 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
c) Describe Life cycle of thread with suitable diagram. 4M

Ans 1) Newborn State 1M-digram


A NEW Thread (or a Born Thread) is a thread that's been created but not yet of life
started. It remains in this state until we start it using the start() method. cycle
3M-
The following code snippet shows a newly created thread that's in the NEW state:
explanation
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); t.start();
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

Page No: 7 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

Fig: Life cycle of Thread


d) Write a program to read a file (Use character stream) 4M

Ans import java.io.FileWriter; 4M (for


import java.io.IOException; correct
public class IOStreamsExample { program
public static void main(String args[]) throws IOException { and logic)
//Creating FileReader object
File file = new File("D:/myFile.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()];
//Reading data from the file
reader.read(chars);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileWriter writer = new FileWriter(out);
//Writing data to the file
writer.write(chars);
writer.flush();
System.out.println("Data successfully written in the specified file");
}
}

3. Attempt any THREE of the following: 12 M

Page No: 8 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
a) Write a program to find reverse of a number. 4M

Ans public class ReverseNumberExample1 Any


Correct
{ public static void main(String[] args) program
{ with proper
logic -4M
int number = 987654, reverse =0;

while(number !=0)

int remainder = number % 10;

reverse = reverse * 10 + remainder;

number = number/10;

System.out.printtln(“The reverse of the given number is: “ + reverse);

} }

b) State the use of final keyword with respect to inheritance. 4M

Ans Final keyword : The keyword final has three uses. First, it can be used to create the Use of final
equivalent of a named constant.( in interface or class we use final as shared constant or keyword-2
constant.) M
Program-2
Other two uses of final apply to inheritance
M
Using final to Prevent Overriding While method 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 final:
class A
{
final void meth()
{
System.out.println("This is a final method.");

Page No: 9 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
As base class declared method as a final , derived class can not override the definition of
base class methods.

c) Give the usage of following methods 4M


i) drawPolygon ()
ii) DrawOval ()
iii) drawLine ()
iv) drawArc ()
Ans i) drawPolygon (): Method use
with
 drawPolygon() method is used to draw arbitrarily shaped figures. description
 Syntax: void drawPolygon(int x[], int y[], int numPoints) 1M
 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;
g.drawPolygon(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 height are specified by width and height to draw a circle or
filled circle, specify the same width and height the following program draws
several ellipses and circle.
 Example: g.drawOval(10,10,50,50);
ii) drawLine ():
 The drawLine() method is used to draw line which take two pair of coordinates,

Page No: 10 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
(x1,y1) and (x2,y2) as arguments and draws a line between them.
 The graphics object g is passed to paint() method.
 Syntax: g.drawLine(x1,y1,x2,y2);
 Example: g.drawLine(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 around the arc

Example: g.drawArc(10, 10, 30, 40, 40, 90);

d) Write any four methods of file class with their use. 4M

Ans One
public String getName() Returns the name of the file or directory denoted by this method
abstract pathname.
public String getParent() Returns the pathname string of this abstract pathname's 1M
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 only 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 pathname 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.

4. Attempt any THREE of the following: 12 M

a) Write all primitive data types available in Java with their storage Sizes in 4M

Page No: 11 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
bytes.

Ans Data type


name, size
Data Type Size
and default
Byte 1 Byte
Short 2 Byte value and
Int 4 Byte description
Long 8 Byte carries 1 M
Double 8 Byte
Float 4 Byte
Char 2 Byte
boolean 1 Bit
b) Write a program to add 2 integer, 2 string and 2 float values in a vector. 4M
Remove the element specified by the user and display the list.

Ans import java.io.*; Correct


import java.lang.*; program- 4
import java.util.*; M, stepwise
class vector2 can give
{ marks
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);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}
c) Develop a program to create a class ‘Book’ having data members author, title 4M
and price. Derive a class 'Booklnfo' having data member 'stock position’ and

Page No: 12 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
method to initialize and display the information for three objects.
Ans class Book Correct
{ program- 4
String author, title, publisher; M
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()
{
System.out.println("Book Details:");
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
System.out.println("Price: " + price);
System.out.println("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);
ob1.show();

Page No: 13 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
ob2.show();
ob3.show();
}
}
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. 4M

Ans Adding Applet to the HTML file: Steps – 2M


Steps to add an applet in HTML document Example –
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the body section 2M
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 name

Page No: 14 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
“Hellojava.java”
import java.awt.*;
import java.applet.*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello Java",10,100);
}}
Use the java compiler to compile the applet “Hellojava.java” file.
C:\jdk> javac Hellojava.java
After compilation “Hellojava.class” 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, correct them and compile the applet again.
We must have the following files in our current directory.
o Hellojava.java
o Hellojava.class
o HelloJava.html
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 = hellojava.class WIDTH = 400 HEIGHT = 200 > </APPLET>
Example: Adding applet to HTML file:
Create Hellojava.html 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.
>
<HEAD> <TITLE> Welcome to Java Applet </TITLE> </HEAD>
<BODY> <CENTER> <H1> Welcome to the world of Applets </H1> </CENTER> <BR>
<CENTER>
Page No: 15 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<APPLET CODE=HelloJava.class WIDTH = 400 HEIGHT = 200 > </APPLET>
</CENTER>
</BODY>
</HTML>
e) Write a program to copy contents of one file to another. 4M

Ans import java.io.*; Correct


class copyf program- 4
{ M
public static void main(String args[]) throws IOException
{
BufferedReader in=null;
BufferedWriter out=null;
try
{
in=new BufferedReader(new FileReader("input.txt"));
out=new BufferedWriter(new FileWriter("output.txt"));
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
System.out.println("File copied successfully");
}
finally
{
if(in!=null)
{
in.close();
}
if(out!=null)
{
out.close();
}
}
}
}

5. Attempt any TWO of the following: 12 M

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

Ans
Page No: 16 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Sr. Array Vector
No.

1 An array is a structure that holds The Vector is similar to array holds


4 M for
multiple values of the same type. multiple objects and like an array; it
any 4
contains components that can be
correct
accessed using an integer index.
points
2 An array is a homogeneous data type Vectors are heterogeneous. You can
1 M for
where it can hold only objects of one have objects of different data types
elementAt()
data type. inside a Vector.
1 M for
3 After creation, an array is a fixed- The size of a Vector can grow or shrink
addElement
length structure. as needed to accommodate adding and
()
removing items after the Vector has
been created.

4 Array can store primitive type data Vector are store non-primitive type data
element. element

5 Array is unsynchronized i.e. Vector is synchronized i.e. when the


automatically increase the size when size will be exceeding at the time;
the initialized size will be exceed. vector size will increase double of
initial size.

6 Declaration of an array : Declaration of Vector:

int arr[] = new int [10]; 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 Vector allocates the memory
fixed size ,in array there is wastage of dynamically means according to the
memory. requirement no wastage of memory.

9 No methods are provided for adding Vector provides methods for adding and
and removing elements. 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
Page No: 17 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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 'salary with data members empid', ‘name' 6M
and ‘basicsalary'. Write an interface 'Allowance’ which stores rates of
calculation 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 it.
Ans interface allowance 6 M for
{ correct
double da=0.9*basicsalary; program
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()
{
System.out.println("Empid of Emplyee="+empid);
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+ basicsalary);
}
}

class net_salary extends salary implements allowance


{
float ta;
net_salary(int i, String n, float b, float t)
{
Page No: 18 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
super(i,n,b);
ta=t;
}
void disp()
{
display();
System.out.println("da of Employee="+da);
}
public void netsalary()
{
double net_sal=basicsalary+ta+hra+da;
System.out.println("netSalary of Employee="+net_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
net_salary s=new net_salary(11, “abcd”, 50000);
s.disp();
s.netsalary();
}
}
c) Define an exception called 'No Match Exception' that is thrown when the 6M
passward accepted is not equal to "MSBTE'. Write the program.

Ans import java.io.*; 6 M for


class NoMatchException extends Exception correct
{ program
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
Page No: 19 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}

6. Attempt any TWO of the following: 12 M

a) Write a program to check whether the string provided by the user is palindrome 6M
or not.

Ans import java.lang.*; 6 M for


correct
import java.io.*; program
import java.util.*;

class palindrome

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

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

System.out.println("Enter String:");

String word=br.readLine( );

int len=word.length( )-1;

int l=0;

int flag=1;

int r=len;

while(l<=r)

Page No: 20 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
if(word.charAt(l)==word.charAt(r))

l++;

r--;

else

flag=0;

break;

if(flag==1)

System.out.println("palindrome");

else

System.out.println("not palindrome");

b) Define thread priority ? Write default priority values and the methods to set 6M
and change them.
Ans Thread Priority: 2 M for
define
In java each thread is assigned a priority which affects the order in which it is scheduled for Thread
running. Threads of same priority are given equal treatment by the java scheduler. priority
Default priority values as follows 2 M for

Page No: 21 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
The thread class defines several priority constants as: - default
priority
MIN_PRIORITY =1 values

NORM_PRIORITY = 5

MAX_PRIORITY = 10
2 M for
Thread priorities can take value from 1-10. method to
set and
getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given change
thread.

setPriority(int newPriority): The java.lang.Thread.setPriority() 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 java.lang.*;

public class ThreadPriorityExample extends Thread


{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().gtName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrority();
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPiority());
}
Page No: 22 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
c) Design an applet to perform all arithmetic operations and display the result by using 6M
labels. textboxes and buttons.
Ans import java.awt.*; 6 M for
import java.awt.event.*; correct
public class sample extends Frame implements ActionListener { program
Label l1, l2,l3;
TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;
sample() {
l1=new Lable(“First No.”);
l1.setBounds(10, 10, 50, 20);
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
l2=new Lable(“Second No.”);
l2.setBounds(10, 60, 50, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
l3=new Lable(“Result”);
l3.setBounds(10, 110, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
b3 = new Button("*");
b3.setBounds(220, 200, 50, 50);
b4 = new Button("/");
b4.setBounds(320,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);

add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(b4);
Page No: 23 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
else if (e.getSource() == b3){
c = a * b;
else if (e.getSource() == b4){
c = a / b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new sample();
}
}

Page No: 24 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION
Model Answer – Only for the Use of RAC Assessors

Subject Name: Java Programming Subject Code: 22412


Important Instructions to examiners: XXXXX
1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the 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. Sub Answer Marking


No Q. Scheme
. N.

1 Attempt any FIVE of the following: 10 M

a) Define the terms with example. 2M

i) Class
ii) Object

Ans i) Class: Class is a set of object, which shares common characteristics/ behavior and 1 M for any
common properties/ attributes. suitable class
definition
and 1 M for
ii) Object: It is a basic unit of Object-Oriented Programming and represents real-life any suitable
entities. object
definition
Example:

class Student
{

int id;
String name;
Page No: 1 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
public static void main(String args[])
{
Student s1=new Student(); //creating an object of Student
}
}

In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student s1 by new keyword.
b) Enlist any two access specifier with syntax. 2M

Ans There are 5 types of java access specifier: List any 2


• public access
specifiers -
• private
2M
• default (Friendly)
• protected
• private protected
c) Give a syntax to create a package and accessing package in java. 2M

Ans To Create a package follow the steps given below: syntax to


create a
package-1 M
• Choose the name of the package
and
• Include the package command as the first line of code in your Java Source File.
accessing
• The Source file contains the classes, interfaces, etc. you want to include in the
package-1 M
package
• Compile to create the Java packages

Syntax to create a package:

package nameOfPackage;
Example:
package p1;

Accessing Package:
• Package can be accessed using keyword import.
• There are 2 ways to access java system packages:
o Package can be imported using import keyword and the wild card(*) but
drawback of this shortcut approach is that it is difficult to determine from
which package a particular member name.
Syntax: import package_name.*;

Page No: 2 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
For e.g. import java.lang.*;
o The package can be accessed by using dot(.) operator and can be terminated
using semicolon(;)
Syntax: import package1.package2.classname;
d) Give a syntax of following thread method 2M

i) Notify ( )
ii) Sleep ( )

Ans i) notify() Syntax of


notify( )-1 M
The notify() method of thread class is used to wake up a single thread. This method gives
the notification for only one thread which is waiting for a particular object. and

Syntax: public final void notify() sleep ()-1 M

ii) sleep()
Sleep() causes the current thread to suspend execution for a specified period.
Syntax: public static void sleep(long milliseconds)

e) Give a syntax of (param) tag to pass parameters to an applet. 2M

Ans User-define Parameter can be applied in applet using <PARAM…> tags. Syntax of
<param> - 1
Each <PARAM…> tag has a name and value attribute.
M
Syntax: <PARAM name = ……… Value = “………” >
And syntax
For example, the param tags for passing name and age parameters looks as shown below: of
getParameter
<param name=”name” value=”Ramesh” />
( )- 1 M
<param name=”age” value=”25″ />

The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page. The syntax of getParameter() method is as follows:
String getParameter(String param-name);
Example:

public void init()

n = getParameter("name");

a = getParameter("age");

Page No: 3 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
f) Define stream class and list types of stream class. 2M

Ans A java stream is a group of objects that can be piped together to produce the desired result. Define
Streams are used in Java to transfer data between programs and I/O devices like a file, stream
network connections, or consoles. class=1 M
and
any 2 types
of stream
class=1 M

Fig: Types of stream classes

g) Give use of garbage collection in java. 2M

Ans The garbage collector provides the following uses: Any 2


uses=2 M
1. Frees developers from having to manually release memory means destroy the
unused objects
2. Allocates objects on the managed heap efficiently.
3. Reclaims objects that are no longer being used, clears their memory, and keeps the
memory available for future allocations.
4. It is automatically done by the garbage collector(a part of JVM), so we don’t need extra
effort.

2. Attempt any THREE of the following: 12 M

a) Describe type casting in java with example. 4M

Ans In Java, type casting is a method or process that converts a data type into another data Definition of

Page No: 4 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
type in both ways manually and automatically. The automatic conversion is done by the type casting-
1M
compiler and manual conversion performed by the programmer.
Type casting is of two types: widening, narrowing. Types of
type
Widening (Implicit)
casting-1 M
• The process of assigning a smaller type to a larger one is known as widening or
implicit.
Byte short int long float double Example-2
M
For e.g.
(1 M for
class widening
each
{ example)
public static void main(String arg[])
{
int i=100;
long l=I;
float f=l;
System.out.println(“Int value is”+i);
System.out.println(“Long value is”+l);
System.out.println(“Float value is”+f);
}
}

Narrowing (Explicit)
• The process of assigning a larger type into a smaller one is called narrowing.
• Casting into a smaller type may result in loss of data.
• double long int short byte
For e.g.
class narrowing
{
Public static void main(String[])
{
Double d=100.04;
Long l=(long) d;
Int i=(int) l;
Page No: 5 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
System.out.println(“Int value is”+i);
System.out.println(“Long value is”+l);
System.out.println(“Float value is”
}
}
b) Differentiate between String and String Buffer Class. (any four points) 4M

Ans String class StringBuffer class Any 4


correct
String is a major class StringBuffer is a peer class of String points-4 M
Length is fixed (immutable) Length is flexible (mutable)
Contents of object cannot be modified Contents of object can be modified
Object can be created by Objects can be created by calling
assigning String constants constructor ofStringBuffer class using
enclosed in double quotes. “new”
Methods of string class: toLowerCase(), Methods of StringBuffer class: setCharAt(),
toUpperCase(), replace(), trim(), equals(), append(), insert(), append(), reverse(),
length(), charAt(), concat(), substring(), delete()
compareTo()
Ex:- String s=”abc”‖; Ex:- StringBuffer s=new StringBuffer
(“abc”);
c) Write a program to create a user defined exception in java. 4M

Ans Following example shows a user defined exception as ‘Invalid Age’, if age entered by For any
the user is less than eighteen. Correct
import java.lang.Exception; program-4 M
import java.io.*;
class myException extends Exception
{
myException(String msg)
{
super(msg);
}
}
class agetest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Scanner class is also valid
try
{
System.out.println("enter the age : ");
int n=Integer.parseInt(br.readLine());
if(n < 18 )
throw new myException("Invalid Age"); //user defined exception
Page No: 6 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
else
System.out.println("Valid age");
}
catch(myException e)
{
System.out.println(e.getMessage());
}
catch(IOException ie)
{}
}
}
d) Write a program for reading and writing character to and from the given files 4M
using character stream classes.

Ans import java.io.FileWriter; 4 M (for any


import java.io.IOException; correct
public class IOStreamsExample { program and
logic)
public static void main(String args[]) throws IOException {
//Creating FileReader object
File file = new File("D:/myFile.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()];
//Reading data from the file
reader.read(chars);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileWriter writer = new FileWriter(out);
//Writing data to the file
writer.write(chars);
writer.flush();
System.out.println("Data successfully written in the specified file");
}
}

3. Attempt any THREE of the following: 12 M

a) Write a program to print all the Armstrong numbers from 0 to 999 4M

Ans import java.util.Scanner; Correct logic


class ArmstrongWhile –4M
{
public static void main(String[] arg)
{
int i=0,arm;
System.out.println("Armstrong numbers between 0 to 999");
while(i<1000)
Page No: 7 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{
arm=armstrongOrNot(i);
if(arm==i)
System.out.println(i);
i++;
}
}
static int armstrongOrNot(int num)
{
int x,a=0;
while(num!=0)
{
x=num%10;
a=a+(x*x*x);
num/=10 ;
}
return a;
}
}

OR
class ArmstrongWhile
{
public static void main(String[] arg)
{
int i=1,a,arm,n,temp;
System.out.println("Armstrong numbers between 0 to 999 are");
while(i<500)
{
n=i;
arm=0;
while(n>0)
{
a=n%10;
arm=arm+(a*a*a);
n=n/10;
}
if(arm==i)
System.out.println(i);
i++;
}
}
}
b) Explain the applet life cycle with neat diagram. 4M

Page No: 8 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Diagram-2
M and
explanation
–2M

Applet Life Cycle: An Applet has a life cycle, which describes how it starts, how it
operates and how it ends. The life cycle consists of four methods: init(), start(), stop() and
destroy().
Initialization State (The init() method):
The life cycle of an Applet is begin on that time when the applet is first loaded into the
browser and called the init() method. The init() method is called only one time in the life
cycle on an Applet. The init() method is basically called to read the “PARAM” tag in the
html file. The init () method retrieve the passed parameter through the “PARAM” tag of
html file using get Parameter() method All the initialization such as initialization of
variables and the objects like image, sound file are loaded in the init () method .After the
initialization of the init() method user can interact with the Applet and mostly applet
contains the init() method.
We may do following thing if required.
• Create objects needed by the applet
• Set up initial values
• Load images or fonts
• Set up colors
Running State (The start() method): The start method of an Applet is called after the
initialization method init(). This method may be called multiples time when the Applet
needs to be started or restarted. For Example if the user wants to return to the Applet, in
this situation the start() method of an Applet will be called by the web browser and the
user will be back on the applet. In the start method user can interact within the applet.
public void start()
{
……..
……..
}
Idle (The Stop() method): An applet becomes idle when it is stopped from running. The
stop() method stops the applet and makes it invisible. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the
stop() method explicitly. The stop() method can be called multiple times in the life cycle of
applet like the start () method or should be called at least one time. For example the stop()
method is called by the web browser on that time When the user leaves one applet to go
another applet and the start() method is called on that time when the user wants to go back
into the first program or Applet.
public void stop()
Page No: 9 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{
……..
……..
}
Dead State (The destroy() method): The destroy() method is called to terminate an
Applet. An Applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when we quit the browser. It is useful for
clean-up actions, such as releasing memory after the applet is removed, killing off threads
and closing network/database connections.
Thus this method releases all the resources that were initialized during an applet’s
initialization.
public void destroy()
{
……..
……..
}
Display State (The paint() method): The paint() method is used for applet display on the
screen.
The display includes text, images, graphics and background. This happens immediately
after the applet enters into the running state. Almost every applet will have a paint()
method and can be called several times during an applet’s life cycle. The paint() method is
called whenever a window is required to paint or repaint the applet.
public void paint(Graphics g)
{
……..
……..
}
c) Describe the package in java with suitable example. 4M

Ans • Java provides a mechanism for partitioning the class namespace into more Description-
manageable parts called package (i.e package are container for a classes). 2 M,
• The package is both naming and visibility controlled mechanism. Package can be Example -2
created by including package as the first statement in java source code. M
• Any classes declared within that file will belong to the specified package.
Syntax: package pkg;
pkg is the name of the package
eg : package mypack;
• Java uses file system directories to store packages. The class files of any classes
which are declared in a
• package must be stored in a directory which has same name as package name.
• The directory must match with the package name exactly.
• A hierarchy can be created by separating package name and sub package name by
a period(.) as pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3.
• The classes and methods of a package must be public.
• To access package In a Java source file, import statements occur immediately
following the package. statement (if it exists) and before any class definitions.
• Syntax: import pkg1[.pkg2].(classname|*);

Page No: 10 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}
Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
d) Enlist types of Byte stream class and describe input stream class and output 4M
stream class.

Ans • Byte streams class: It handles I/O operations on bytes. Type – 1 M,


• InputStream and OutputStream classes are operated on bytes for reading and Explanation
writing, respectively. -3 M
• Byte streams are used in a program to read and write 8-bit bytes.
• InputStream and OutputStream are the abstract super classes of all byte streams
that have a sequential nature.
• The stream is unidirectional; they can transmit bytes in only one direction.
• InputStream and OutputStream provide the Application program Interface (API)
and
partial implementation for input streams (streams that read bytes) and output
streams (streams that write bytes).
• Input Stream Classes: java.io.InputStream is an abstract class that contains the
basic methods for reading raw bytes of data from a stream. The InputStream class
defines methods for performing the input functions like: reading bytes, closing
streams, marking positions in streams, skipping ahead in a stream and finding the
number of bytes in a stream.
• Input stream class methods:
1. int read ()- Returns an integer representation of next available byte of input.-1 is
returned at the stream end.
2. int read (byte buffer[ ])- Read up to buffer.length bytes into buffer & returns
actual number

Page No: 11 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
of bytes that are read. At the end returns –1.
3. int read(byte buffer[ ], int offset, int numbytes)- Attempts to read up to numbytes
bytes into buffer starting at buffer[offset]. Returns actual number of bytes that are
read. At the end returns –1.
4. void close()- to close the input stream
5. void mark(int numbytes)- places a mark at current point in input stream and
remain valid till number of bytes are read.
6. void reset()- Resets pointer to previously set mark/ goes back to stream
beginning.
7. long skip(long numbytes)- skips number of bytes.
8. int available()- Returns number of bytes currently available for reading.

• Output Stream Classes:


• The java.io.OutputStream class sends raw bytes of data to a target such as the
console or a network server. Like InputStream, OutputStream is an abstract class.
• The OutputStream includes methods that perform operations like: writing bytes,
closing streams,flushing streams etc.
• Methods defines by the OutputStream class are
1. void close() - to close the OutputStream
2. void write (int b) - Writes a single byte to an output stream.
3. void write(byte buffer[ ]) - Writes a complete array of bytes to an output stream.
4. void write (byte buffer[ ], int offset, int numbytes) - Writes a sub range of
numbytes bytes
from the array buffer, beginning at buffer[offset].
5. void flush() - clears the buffer.

4. Attempt any THREE of the following: 12 M

a) Describe any four features of java. 4M

Ans 1. Compile & Interpreted: Java is a two staged system. It combines both approaches. Any four
First java compiler translates source code into byte code instruction. Byte codes are not each features
machine instructions. In the second stage java interpreter generates machine code that can -1 M each
be directly executed by machine. Thus java is both compile and interpreted language.
2. Platform independent and portable: Java programs are portable i.e. it can be easily
moved from one computer system to another. Changes in OS, Processor, system resources
won’t force any change in java programs. Java compiler generates byte code instructions
that can be implemented on any machine as well as the size of primitive data type is
machine independent.
3. Object Oriented: Almost everything in java is in the form of object. All program codes
and data reside within objects and classes. Similar to other OOP languages java also has
basic OOP properties such as encapsulation, polymorphism, data abstraction, inheritance
etc. Java comes with an extensive set of classes (default) in packages.
4. Robust & Secure: Java is a robust in the sense that it provides many safeguards to
ensure reliable codes. Java incorporates concept of exception handling which captures
errors and eliminates any risk of crashing the system. Java system not only verify all
memory access but also ensure that no viruses are communicated with an applet. It does
not use pointers by which you can gain access to memory locations without proper

Page No: 12 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
authorization.
5. Distributed: It is designed as a distributed language for creating applications on
network. It has ability to share both data and program. Java application can open and
access remote object on internet as easily as they can do in local system.
6. Multithreaded: It can handle multiple tasks simultaneously. Java makes this possible
with the feature of multithreading. This means that we need not wait for the application to
finish one task before beginning other.
7. Dynamic and Extensible: Java is capable of dynamically linking new class library’s
method and object. Java program supports function written in other languages such as C,
C++ which are called as native methods. Native methods are linked dynamically at run
time.
b) Explain any four methods of vector class with example. 4M

Ans Vector class is in java.util package of java. 1 Method – 1


Vector is dynamic array which can grow automatically according to the requirement. M
Vector does not require any fix dimension like String array and int array.
Vectors are used to store objects that do not have to be homogeneous.
Vector contains many useful methods.
Vectors are created like arrays. It has three constructor methods
Vector list = new Vector(); //declaring vector without size
Vector list = new Vector(3); //declaring vector with size
Vector list = new Vector(5,2); //create vector with initial size and whenever it
need to grows, it grows by value specified by increment capacity.

Method Name Task performed


list.firstElement() It returns the first element of the vector.
list.lastElement() It returns last element of the vector
list.addElement(item) Adds the item specified to the list at the
end.
list.elementAt(n) Gives the name of the object at nth
position
list.size() Gives the number of objects present in
vector
List.capacity() This method returns the current capacity of
the vector.
list.removeElement(item) Removes the specified item from the list.
list.removeElementAt(n) Removes the item stored in the nth
position of the list.
list.removeAllElements() Removes all the elements in the list.
list.insertElementAt(item, Inserts the item at nth position.
n)
List.contains(object This method checks whether the specified
element) element is present in the Vector. If the
element is been found it returns true else
false.
list.copyInto(array) Copies all items from list of array.

Example:
Page No: 13 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

import java.io.*;
import
java.lang.*;
import
java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new
vector(); Integer
s1=new Integer(1);
Integer s2=new
Integer(2); String
s3=new
String("fy"); String
s4=new
String("sy");
Character s5=new
Character('a'); Character
s6=new Character('b');
Float s7=new
Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s5);
v.addElement(s6);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}
c) Describe interface in java with suitable example. 4M

Ans Java does not support multiple inheritances with only classes. Java provides an alternate Interface
approach known as interface to support concept of multiple inheritance. An interface is explanation
similar to class which can define only abstract methods and final variables. – 2 M, any
Syntax: suitable
access interface InterfaceName example – 2
{ M
Variables declaration;
Methods declaration;
Page No: 14 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
Example:
interface sports
{
int sport_wt=5;
public void disp();
}
class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
result (int r, String nm, int m11,int m12)
{
super (r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
{
result r= new result(101,"abc",75,75);
r.disp();
}
}
Output :
D:\>java result
Roll no : 101
Name : abc
sub1 : 75
sub2 : 75
sport_wt : 5
Page No: 15 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
total : 155
d) Write an applet program for following graphics method. 4M

i) Drawoval ( )

ii) Drawline ( )

Ans import java.awt.*; Any correct


import java.applet.*; logic can be
public class CirSqr extends Applet considered 2
{ M for
public void paint(Graphics g) drawoval
{ and 2 M for
g.drawOval(70,30,100,100); drawline
g.drawRect(90,50,60,60);
}
}
/*<applet code="CirSqr.class" height=200 width=200>
</applet> */
Output:

e) Enlist any four methods of file input stream class and give syntax of any two 4M
methods.

Ans • Input Stream Classes: java.io.InputStream is an abstract class that contains the One method
basic methods for reading raw bytes of data from a stream. The InputStream class –1M
defines methods for performing the input functions like: reading bytes, closing
streams, marking positions in streams, skipping ahead in a stream and finding the
number of bytes in a stream.
• Input stream class methods:
1. int read ()- Returns an integer representation of next available byte of input.-1 is
returned at the stream end.
2. int read (byte buffer[ ])- Read up to buffer.length bytes into buffer & returns
actual number
of bytes that are read. At the end returns –1.
3. int read(byte buffer[ ], int offset, int numbytes)- Attempts to read up to numbytes
bytes
into buffer starting at buffer[offset]. Returns actual number of bytes that are read.
Page No: 16 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
At the
end returns –1.
4. void close()- to close the input stream
5. void mark(int numbytes)- places a mark at current point in input stream and
remain valid till
number of bytes are read.
6. void reset()- Resets pointer to previously set mark/ goes back to stream
beginning.
7. long skip(long numbytes)- skips number of bytes.
8. int available()- Returns number of bytes currently available for reading.

5. Attempt any TWO of the following: 12 M

a) Write a program to copy all elements of one array into another array. 6M

Ans public class CopyArray { 6 M for any


correct
public static void main(String[] args) program and
{ logic
int [] arr1 = new int [] {1, 2, 3, 4, 5};

int arr2[] = new int[arr1.length];

for (int i = 0; i < arr1.length; i++)


{
arr2[i] = arr1[i];
}
System.out.println("Elements of original array: ");

for (int i = 0; i < arr1.length; i++)


{
System.out.print(arr1[i] + " ");
}

System.out.println();

System.out.println("Elements of new array: ");

for (int i = 0; i < arr2.length; i++)


{
System.out.print(arr2[i] + " ");
Page No: 17 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
}
}

b) Write a program to implement the following inheritance. Refer Fig. No. 1. 6M

Interface: Exam Class : Student


Sports mark =20; Roll no, S-name

m1, m2, m3

Class: Result
display ()

Fig. No. 1

Ans interface Exam 6 M for


correct
{ program

int sports_mark=20;

class Student

String S-name;
int Roll_no, m1, m2, m3;
Student(String n, int a, int b, int c, int d)

S-name = n;

Roll_no = a;

Page No: 18 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
m1 = b;

m2 = c;

m3 = d;

void showdata()

System.out.println("Name of student :"+S-name);

System.out.println("Roll no. of the students :"+Roll_no);

System.out.println(“Marks of subject 1:”+m1);

System.out.println(“Marks of subject 2:”+m2);

System.out.println(“Marks of subject 3:”+m3);

class Result extends Student implements Exam

Result(String n, int a, int b, int c, int d)

super(n, a, b, c, d );

void dispaly()

super.showdata();

int total=(m1+m2+m3);

float result=(total+Sports_mark)/total*100;

Page No: 19 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
System.out.println(“result of student is:”+result);

class studentsDetails

public static void main(String args[])

Result r=new Result("Sachin",14, 78, 85, 97);

r.display();

}
c) Write a program to print even and odd number using two threads with delay 6M
of 1000ms after each number.

Ans class odd extends Thread 6 M for


correct
{ program
public void run()
{
for(int i=1;i<=20;i=i+2)
{
System.out.println("ODD="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");

Page No: 20 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
}
}
}
class even extends Thread
{
public void run()
{
for(int i=0;i<=20;i=i+2)
{
System.out.println("EVEN="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
class oddeven
{
public static void main(String arg[])
{
odd o=new odd();
even e=new even();

Page No: 21 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
o.start();
e.start();
}
}

6. Attempt any TWO of the following: 12 M

a) Explain thread life cycle with neat diagram. 6M

Ans 2 M for
diagram, 4
M for
explanation

Thread Life Cycle Thread has five different states throughout its life.

1) Newborn State

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

2) Runnable State

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

Page No: 22 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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

Thread should be in any one state of above and it can be move from one state to another by
different methods and ways.
b) Write a program to generate following output using drawline () method. Refer 6M
Fig. No. 2.

Fig. No. 2

Ans Using drawLine() method 6 M for


correct
import java.applet.*; program
import java.awt.*;
public class Triangle extends Applet
{
public void paint(Graphics g)
{
g.drawLine(100,200,200,100);

Page No: 23 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
g.drawLine(200,100,300,200);
g.drawLine(300,200,100,200);
}
}
/*<applet code="Triangle.class" height=300 width=200> </applet>*/
OR
Using drawPolygon() method
import java.applet.*;
import java.awt.*;
public class Triangle extends Applet
{
public void paint(Graphics g)
{
int a[]={100,200,300,100};
int b[]={200,100,200,200};
int n=4;
g.drawPolygon(a,b,n);
}
}
/*<applet code="Triangle.class" height=300 width=200> </applet>*/

c) Explain constructor with its type. Give an example of parameterized 6M


constructor.

Ans Constructor: A constructor in Java is a special method that is used to initialize objects. 2 M for
definition of
The constructor is called when an object of a class is created. It can be used to set initial constructor
values for object attributes. and types of
constructors

Types of constructors are:


Default constructor : It is constructor which is inserted by Java compiler when no 4 M for
constructor is provided in class. Every class has constructor within it. Even abstract class example (for
have default constructor. any correct
suitable
By default, Java compiler, insert the code for a zero parameter constructor. program of
parameterize
Page No: 24 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Default constructor is the no arguments constructor automatically generated unless you d
constructor)
define another constructor.
The default constructor automatically initializes all numeric members to zero and other
types to null or spaces.
class Rect
{
int length, breadth;
Rect() //constructor
{
length=4;
breadth=5;
}
public static void main(String args[])
{
Rect r = new Rect();
System.out.println(“Area : ” +(r.length*r.breadth));
}
}
Parameterized constructor: Constructor which have arguments are known as
parameterized constructor.
When constructor method is defined with parameters inside it, different value sets can be
provided to different constructor with the same name.
Example of Parameterized Constructor
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
System.out.println(“Area : ” +(r.length*r.breadth));
Page No: 25 | 26

You might also like