2018 Winter Model Answer Paper 1
2018 Winter Model Answer Paper 1
2018 Winter Model Answer Paper 1
(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.
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)
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)
{
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.
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
10
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
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;
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");
}
}
obj.demo();
}
}
Output:
XYZ Class Method
final class: We cannot extend a final class. Consider the below example:
final class XYZ
{
}
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
}
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)
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:
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();
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:
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.
Output:
}
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)
23