100% found this document useful (1 vote)
872 views

Java Sample Papers With Answers

1) Exception handling in Java is done using 5 keywords: try, catch, finally, throw, throws. The try block contains code that might throw exceptions, catch handles specific exceptions, and finally contains cleanup code. 2) An interface can extend another interface using the extends keyword, similarly to how a class extends another class. The child interface inherits the methods of the parent interface. 3) The Applet tag is used to define Java applets in HTML. It has attributes like code that specifies the applet class, width and height for display size, and param to pass arguments to the applet.

Uploaded by

Renu Deshmukh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
872 views

Java Sample Papers With Answers

1) Exception handling in Java is done using 5 keywords: try, catch, finally, throw, throws. The try block contains code that might throw exceptions, catch handles specific exceptions, and finally contains cleanup code. 2) An interface can extend another interface using the extends keyword, similarly to how a class extends another class. The child interface inherits the methods of the parent interface. 3) The Applet tag is used to define Java applets in HTML. It has attributes like code that specifies the applet class, width and height for display size, and param to pass arguments to the applet.

Uploaded by

Renu Deshmukh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

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

SUMMER – 19 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. Sub Answer Marking


No. Q. Scheme
N.
1 a Attempt any THREE of the following: 12 M
i Define Exception? How is it handled? 4M
Ans Exception: An exception is an event, which occurs during the execution of a Define-1 M ,
program, that stop the flow of the program's instructions and takes appropriate Handling: 3 M
actions if handled. .i.e. It is erroneous situation encounter during course of
execution of program.
Exceptional handling mechanism provides a means to detect errors and throw
exceptions, and then to catch exceptions by taking appropriate actions.
Java Exception handles as follow
 Find the problem (Hit the exception)
 Inform that an error has occurred ( throw the Exception)
 Receive the error information(Catch the exception)
 Take corrective action ( Handle the Exception)
Exception handling in java is done by 5 keywords as:
 try: This block applies a monitor on the statements written inside it. If
there exist any exception, the control is transferred to catch or finally
block.
 catch: This block includes the actions to be taken if a particular
exception occurs.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

 finally: finally block includes the statements which are to be executed


in any case, in case the exception is raised or not.
 throw: This keyword is generally used in case of user defined
exception, to forcefully raise the exception and take the required action.
 throws: throws keyword can be used along with the method definition
to name the list of exceptions which are likely to happen during the
execution of that method. In that case, try … catch block is not
necessary in the code.

ii WAP to check whether the given number is prime or not. 4M


Ans class PrimeNo Correct
{ Program with
public static void main(String args[]) proper logic 4
{ M
Int num=Integer.parseInt(args[0]);
int flag=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}
iii Write syntax to inherit one interface into another interface. 4M
Ans An Interface can extend another interface similarly to the way that a class can Proper
extend another class. The extends keyboard is used to extends an interface and Syntax-4 M
the child interface inherits the method of the parent interface.
Syntax:
Interface class2 extends class1
{
Body of class2
}
Example:
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Interace A
{
Int code=11;
String name=”Computer”;
}
Interface B extends A
{
Void display();
}
iv List and explain Applet attributes. 4M
Ans The HTML APPLET Tag and attributes List 1 Marks
The APPLET tag is used to start an applet from both an HTML document and and Explain 3
from an applet viewer. Marks
The syntax for the standard APPLET tag:
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]>
[< PARAM NAME = AttributeNameVALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
• CODEBASE is an optional attribute that specifies the base URL of the applet
code or the
directory that will be searched for the applet‟s executable class file.
• CODE is a required attribute that give the name of the file containing your
applet‟s compiled
class file which will be run by web browser or appletviewer.
• ALT: Alternate Text. The ALT tag is an optional attribute used to specify a
short text message that should be displayed if the browser cannot run java
applets.
• NAME is an optional attribute used to specifies a name for the applet instance.
• WIDTH AND HEIGHT are required attributes that give the size(in pixels) of
the applet display area.
• ALIGN is an optional attribute that specifies the alignment of the applet.
• The possible value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE,
BASELINE, TEXTTOP, ABSMIDDLE,
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

and ABSBOTTOM.
• VSPACE AND HSPACE attributes are optional, VSPACE specifies the
space, in pixels, about and below the applet. HSPACE VSPACE specifies the
space, in pixels, on each side of the applet
• PARAM NAME AND VALUE: The PARAM tag allows you to specifies
applet- specific
arguments in an HTML page applets access there attributes with the
getParameter()method.
b Attempt any ONE of the following: 6M
i Explain package creation with suitable example. 6M
Ans Java provides a mechanism for partitioning the class namespace into more Explanation 2
manageable parts called package (i.e. package are container for a classes). The M, Example 4
package is both naming and visibility controlled mechanism. Package can be M
created by including package as the first statement in java source code. Any
classes declared within that file will belong to the specified package.
Syntax:
package pkg;
Here, 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|*);
Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

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();
}
}
ii Explain serialization with suitable example for writing an object into file. 6M
Ans Serialization is the process of writing the state of an object to a byte stream. Explanation 3
This is useful when you want to save the state of your program to a persistent M, Example 3
storage area, such as a file. At a later time, you may restore these objects by M
using the process of deserialization.
Serialization is also needed to implement Remote Method Invocation (RMI).
RMI allows a Java object on one machine to invoke a method of a Java object
on a different machine. An object may be supplied as an argument to that
remote method. The sending machine serializes the object and transmits it. The
receiving machine deserializes it.
Example:
Assume that an object to be serialized has references to other objects, which,
in turn, have references to still more objects. This set of objects and the
relationships among them form a directed graph. There may also be circular
references within this object graph. That is, object X may contain a reference
to object Y, and object Y may contain a reference back to object X. Objects
may also contain references to themselves. The object serialization and
deserialization facilities have been designed to work correctly in these
scenarios. If you attempt to serialize an object at the top of an object graph, all
of the other referenced objects are recursively located and serialized.
Similarly, during the process of deserialization, all of these objects and their
references are correctly restored.

2 Attempt any TWO of the following: 16 M


a Explain any four methods of graphics class. 8M
Ans (i) drawOval( ) Any four
Drawing Ellipses and circles: To draw an Ellipses or circles used draw Oval() method with
method can be used.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Syntax: void drawOval(int top, int left, int width, int height); proper syntax
The ellipse is drawn within a bounding rectangle whose upper-left corner is 2 M each
specified by top and left and whose width and height are specified by width and
height to draw a circle or filled circle, specify the same width and height the
following program draws several ellipses and circle.
Example: g.drawOval(10,10,50,50);
(ii) drawPolygon
drawPolygon() method is used to draw arbitrarily shaped figures.
Syntax: void drawPolygon(int x[], int y[], int numPoints);
The polygon‟s end points are specified by the co-ordinates pairs contained
within the x and y arrays.
The number of points defines by x and y is specified by numPoints.
Example:
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);
(iii)drawArc( )
It is used to draw arc.
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle is
starting angle of arc sweep_angle is degree around the arc
Example: g.drawArc(10, 10, 30, 40, 40, 90);
(iv) drawRect()
The drawRect() method display an outlined rectangle.
Syntax: void drawRect(int top,int left,int width,int height);
The upper-left corner of the Rectangle is at top and left. The dimension of the
Rectangle is specified by width and height.
Example: g.drawRect(10,10,60,50);

(v) drawString( )
Displaying String: drawString() method is used to display the string in an applet
window
Syntax: void drawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example: g.drawString(“WELCOME”, 10, 10);
(vi) drawLine()
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

The drawLine() method is used to draw line which take two pair of coordinates,
(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);
b WAP to throw authentication failure exception if the user has entered 8M
wrong password i.e. accept the password from the user and then rechecked
if it is properly entered then valid user exception should throw.
Ans import java.io.*; Proper
class PasswordException extends Exception program with
{ correct logic 8
M
PasswordException(String msg)
{
super(msg);
}
}
class PassCheck
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("abc"))
{
System.out.println("Valid User ");
}
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

{
System.out.println(e);
}
}
}
c Explain thread life cycle with suitable diagram. 8M
Ans Diagram 2 M,
Explanation: 6
M

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

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

3 Attempt any FOUR of the following: 16 M


a Explain this keyword with suitable example. 4M
Ans This keyword: Explanation :
2M
1. Keyword 'this' in Java is a reference variable that refers to the current
object. Any 1
2. It can be used to refer current class instance variable example : 2M
3. It can be used to invoke or initiate current class constructor
4. It can be passed as an argument in the method call Any other
5. It can be passed as argument in the constructor call example also
6. It can be used to return the current class instance considered
7. "this" is a reference to the current object, whose method is being
called upon.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

8. You can use "this" keyword to avoid naming conflicts in the


method/constructor of your instance/object.

Example1

Using ‘this’ keyword to refer current class instance variables

class Test

int a;

int b;

Test(int a, int b) // Parameterized constructor

this.a = a;

this.b = b;

void display()

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

public static void main(String[] args)

Test object = new Test(10, 20);

object.display();

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

Example 2: Using ‘this’ keyword to invoke current class method

class Test {

void display()

// calling fuction show()

this.show();

System.out.println("Inside display function");

void show() {

System.out.println("Inside show funcion");

public static void main(String args[]) {

Test t1 = new Test();

t1.display();

b Write a program to add two strings using command line arguments. 4M


Ans class Concats Correct Logic
: 2M
{
Correct syntax
public static void main(String args[]) : 2M
{ (Note: Any
other logic can
String s1=args[0]; //Accept first string command line
be considered)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

String s2=args[1]; //Accept second string command line

String s3= s1+s2;

System.out.println("Concatnated String is : "+s3);

( OR )

class Concats

public static void main(String args[])

String s1=args[0]; //Accept first string command line

String s2=args[1]; //Accept second string command line

String s3=s1.concat(s2);

System.out.println("Concatnated String is : "+s3);

c Give four differences between strings and string buffer class. 4M


Ans Sr. String StringBuffer Any 4 points :
No 1M each

1 String is a major class StringBuffer is a peer class of String

2 Length is fixed Length is flexible

3 Contents of object cannot be Contents of object can be modified


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

4 Object can be created by Objects can be created by calling


assigning String constants constructor of StringBuffer class using
enclosed in double quotes. new operator.

5 String s=”MSBTE” StringBuffer s=new StringBuffer


(“MSBTE”)

d Explain thread priority and method to get and set priority values. 4M
Ans Thread Priority: In java each thread is assigned a priority which affects the Thread
order in which it is scheduled for running. Thread priority is used to decide Priority
when to switch from one running thread to another. Threads of same priority explanation
are given equal treatment by the java scheduler. Thread priorities can take :2M
value from 1-10.
Each Method
: 1M

Following are integer constants for Thread Priority:

1) MIN_PRIORITY= The minimum priority of any thread(int value of 1)


2) NORM_PRIORITY= The normal priority of any thread(int value of 5
)
3) MAX_PRIORITY= The maximum priority of any thread(int value of
10)

1. setPriority:
Syntax: public void setPriority(int number);
This method is used to assign new priority to the thread.
2. getPriority:
Syntax: public int getPriority();
It obtain the priority of the thread and returns integer value.
e Write a program to copy the contents of one file into another. 4M
Ans import java.io.*; Correct Logic
2M
class Filecopy

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


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

FileInputStream in= new FileInputStream("input.txt"); //FileReader


class can be used
Correct
FileOutputStream out= new FileOutputStream("output.txt"); Syntax 2M
//FileWriter class can be used

int c=0;

try

while(c!=-1)

c=in.read();

out.write(c);

System.out.println("File copied to output.txt....");

finally

if(in!=null)

in.close();

if(out!=null)

out.close();

}
f Give four difference between applet and application. 4M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Ans Any 4 points :


1M each
Sr.No Applet Application

1 Applet does not use Application uses main()

main() method for method for initiating


execution of code.
initiating execution of

code.

2 Applet cannot run Application can run

independently. independently.

3 Applet cannot read Application can read from or

from or write to files in write to files in local


computer.
local computer.

4 Applet cannot Application can communicate

communicate with with other servers on network.

other servers on

network

5 Applet are restricted Application are not restricted

from using libraries from using libraries from other


language.
from other language

such as C or C++.

4 a Attempt any THREE of the following: 12 M


i Explain shift right and shift left operator. 4M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Ans The Left Shift (<<): the left shift operator, <<, shifts all of the bits in a Each Bitwise
‘value’ to the left a specified number of times specified by ‘num’ operator
explanation: 1
General form : value <<num M,
e.g. x << 2 (x=12)
Each example:
0000 1100 << 2 1M
= 0011 0000 (decimal 48)
6) The Right Shift (>>): the right shift operator, >>, shifts all of the bits
in a ‘value’ to the right a specified number of times specified by ‘num’
General form: value >>num
e.g. x>> 2 (x=32)
0010 0000 >> 2
= 0000 1000 (decimal 8)
ii List the standard default values of each datatype. 4M
Ans Each ½ mark
Standard default for correct
value/range
Sr. No Datatype values

1 byte 0

2 short 0

3 int 0

4 long 0L

5 float 0.0f

6 double 0.0d

7 char

8 boolean False

iii Explain vector methods: 4M

1) addElement()

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

Ans addElement(): It is used to add an object at the end of the Vector. Each method
syntax :
Syntax : addElement(Object);
1M
Example : v.addElement(new Integer(10)); // add Integer object with value and Example
10 at the end of the Vector object ‘v’. 1M

insertElementAt( ) :Adds element to the vector at the location specified by


the index.

Syntax : void insertElementAt(Object element, int index)

Example: Vector v = new Vector( );

v.insertElementAt(“J”, 2); //insert character object in vector


nd
at 2 position.

iv Explain stream and various types of streams. 4M


Ans Stream: Stream
1. A stream in java is path along which data flows. explanation :
2. A stream is an abstraction that either produces or consumes information 2M
(i.e. it takes the input or gives the output).
3. A stream presents a uniform, easy-to-use, object oriented interface Each type :
1M
between program and input/output device.
4. It has source and destination.

Java defines two types of streams: based on the datatype on which they operate
:

1. Byte Stream: Byte streams provide a convenient means for handling


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

b Attempt any ONE of the following: 6M


i Explain dynamic method dispatch. 6M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Ans Dynamic Method Dispatch Correct


1. Dynamic method dispatch is a technique by which call to a overridden Explanation
method is resolved at runtime, rather than compile time. :4M
2. When an overridden method is called by a reference, then which version Example : 2M
of overridden method is to be called is decided at runtime according to
the type of object it refers.

3. Dynamic method dispatch is performed by JVM not compiler. (Any other


Dynamic method dispatch allows java to support overriding of methods example can
and perform runtime polymorphism. be considered)
4. It allows subclasses to have common methods and can redefine specific
implementation for them. This lets the superclass reference respond
differently to same method call depending on which object it is pointing.

Example:

class A {

void callme() {

System.out.println("Inside A's callme method");

class B extends A {

// override callme()

void callme() {

System.out.println("Inside B's callme method");

class C extends A {

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

void callme() {

System.out.println("Inside C's callme method");

class Dispatch {

public static void main(String args[]) {

A a = new A(); // object of type A

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

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

A r; // obtain a reference of type A

r = a; // r refers to an A object

r.callme(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme

r = c; // r refers to a C object

r.callme(); // calls C's version of callme

The output from the program is shown here:

Inside A’s callme method

Inside B’s callme method

Inside C’s callme method

ii Explain class variable with suitable example. 6M


Ans Class variables : Explanation :
3M,
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Class variables also known as static variables are declared with the static Example : 3M
keyword in a class, but outside a method, constructor or a block.
(Note: any
other example
1. There would only be one copy of each class variable per class, can be
regardless of how many objects are created from it. considered)

2. Static variables are rarely used other than being declared as


constants. Constants are variables that are declared as
public/private, final, and static. Constant variables never change
from their initial value.

3. Static variables are stored in the static memory. It is rare to use


static variables other than declared final and used as either
public or private constants.

4. Static variables are created when the program starts and


destroyed when the program stops.

5. Default values are same as instance variables. For numbers, the


default value is 0; for Booleans, it is false; and for object
references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can
be assigned in special static initializer blocks.

6. Static variables can be accessed by calling with the class name


as ClassName.VariableName.

Example :

public class Employee {

// salary variable is a private static variable

private static double salary;


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

// DEPARTMENT is a constant

public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {

salary = 1000;

System.out.println(DEPARTMENT + "average salary:" + salary);

Output:

Development average salary:1000

5 Attempt any TWO of the following: 16 M


a Explain features: 8M
(i)Platform Independence
(ii)Robust
(iii)Dynamic
(iv)Object oriented

Ans (i)Platform Independence- 2 M for each


feature
Java is platform independent because it is different from other languages like
C, C++, etc. which are compiled into platform specific machines while Java is
a write once, run anywhere language. A platform is the hardware or software
environment in which a program runs.
Java code can be run on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere

(ii)Robust-

Robust simply means strong. Java is robust because:

 It uses strong memory management.


 There is a lack of pointers that avoids security problems.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

 There is automatic garbage collection in java which runs on the Java


Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
 There are exception handling and the type checking mechanism in
Java. All these points make Java robust.

(iii)Dynamic-
Java is a dynamic language. It supports dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

(iv)Object oriented
Java is an object-oriented programming language. Everything in Java is an
object. Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behavior.

b What is inheritance? List types of inheritance and explain single level 8M


inheritance with example.
Ans Inheritance in Java is a mechanism in which one object acquires all the Definition
properties and behaviors of a parent object. The idea behind inheritance is that 2M,Types 2M,
we can create new classes that are built upon existing classes. When we Example 4M
inherit from an existing class, we can reuse methods and fields of the parent
class.

syntax -

class Subclass-name extends Superclass-name


{
//methods and fields
}

A class which is inherited is called a parent or superclass, and the new class is
called child or subclass.

Types of inheritance
1)Single inheritance
2)Multilevel inheritance
3)Multiple inheritance
4)Hierarchical inheritance

Single level Inheritance


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

In single inheritance, subclasses inherit the features of one superclass. In


image below, the class A serves as a base class for the derived class B.

For example

class one

int v1=10;

void method1()

System.out.println("we are in method 1");

class two extends one

void method2()

System.out.println("v1="+v1);

System.out.println("we are in method 2");


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

class singleinherit

public static void main(String[] args)

two t = new two();

t.method1();

t.method2();

Output:

we are in method 1

v1=10;

we are in method 2
c WAP to implement the following inheritance: 8M
Interface : sports class : student

sport wt = 5 rollno, name, marks

Class Result

get total (), display ()


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

Ans import java.io.*; Correct Logic


: 4M
interface sport
Correct syntax
{ : 4M

int sport_wt=5 ; (Note: Any


other logic can
} be considered)

class student

String name;

int roll_no,marks;

public void getdata()

DataInputStream d=new DataInputStream(System.in);

try

System.out.println("enter the name");

name=d.readLine();

System.out.println("enter the roll_no");

roll_no=Integer.parseInt(d.readLine());

System.out.println("enter the marks");


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

marks=Integer.parseInt(d.readLine());

catch(Exception e)

System.out.println(“input output error”);

System.out.println(" ");

System.out.println("name="+name);

System.out.println("roll no="+roll_no);

System.out.println("marks1="+marks);

class result extends student implements sport

int total;

public void get_total()

super.getdata();

total=sport_wt+super.marks;

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

public void display()

System.out.println("total marks="+total);

public static void main(String args[])

result r=new result();

r.get_total();

r.display();

Output:

enter the name

abc

enter the roll_no

11

enter the marks

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

name=abc

roll no=11

marks1=200

total marks=205

6 Attempt any FOUR of the following: 16 M


a WAP to reverse a three digit number accepted from user. 4M
Ans import java.io.*;

class ReverseNumber Correct Logic


: 4M
{
Correct syntax
public static void main(String args[]) : 4M

{ (Note: Any
other logic can
int n, reverse = 0; be considered

DataInputStream d=new DataInputStream(System.in);

try

System.out.println("Enter an integer to reverse");

n=Integer.parseInt(d.readLine());

while(n != 0)

reverse = reverse * 10;

reverse = reverse + n%10;

n = n/10;

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

System.out.println("Reverse of the number is " + reverse);

catch(Exception e)

System.out.println("input output error");

Output:

Enter an integer to reverse

123

Reverse of the number is 321


b WAP to draw a triangle inside an applet. 4M
Ans Correct Logic
: 2M
//<applet code=Triangle width=500 height=500></applet>
Correct syntax
import java.applet.*; : 2M

import java.awt.*; (Note:


students can
public class Triangle extends Applet use
drawPolygon()
{ also)

public void paint(Graphics g)

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

g.drawLine(177,141,177,361);

g.drawLine(177,141,438,361);

g.drawLine(177,361,438,361);

Output

c WAP to display 3 concentric circles in a applet. 4M


Ans import java.awt.*; Correct Logic
: 2M
import java.applet.*;
Correct syntax
: 2M

public class ConcentricCircles extends Applet

public void paint(Graphics g)

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

g.setColor(Color.pink);

g.drawOval(20,20,45,45);

g.setColor(Color.red);

g.drawOval(10,10,65,65);

g.setColor(Color.green);

g.drawOval(30,30,25,25);

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

</applet>

*/

d Explain set class with example. 4M


Ans  Set is an interface which extends Collection. It is an unordered Definition
collection of objects in which duplicate values cannot be stored. 2M,Example
 Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet 2M
(sorted representation).
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

 Set has various methods to add, remove clear, size, etc to enhance the
usage of this interface

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements
only.

For eg.

// adding elements in Set

import java.util.*;

public class Set_example

public static void main(String[] args)

// Set deonstration using HashSet

Set<String> hash_Set = new HashSet<String>();

hash_Set.add("abc");

hash_Set.add("xyz");

hash_Set.add("abc");

hash_Set.add("java");

hash_Set.add("subject");

System.out.print("Set output without the duplicates");

System.out.println(hash_Set);

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

Output:

Set output without the duplicates[abc, java, subject, xyz]

we have entered a duplicate entity but it is not displayed in the output.


e Explain draw arc function with example. 4M
Ans The drawArc( ) designed to draw arcs takes six arguments. The first four are Definition
the same as the arguments for drawOval( ) method and the last two represent 2M,Example
the starting angle of the arc and the number of degrees around the arc. 2M
The fillArc( ) method draws a solid arc.
public class DrawArcExample extends Applet
{
public void paint(Graphics g)
{

setForeground(Color.red);
g.drawArc(10,10,50,100,10,45);
g.fillArc(100,10,100,100,0,90);
}
}

Output:

f Explain two dimensional array in java with example. 4M


Ans An array is a collection of similar type of elements that have a contiguous Definition 1M,
memory location. Array is an object which contains elements of a similar Syntax 1M,
data type. Example 2M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

Types of Array

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Two – dimensional array is the simplest form of a multidimensional array.

Syntax:

data_type[][] array_name = new data_type[x][y];


For example:
int[][] arr = new int[2][3];

Initialization

array_name[row_index][column_index] = value;

For example: arr[0][0] = 1;

Representation of 2D array in Tabular Format: A two – dimensional array


can be seen as a table with ‘x’ rows and ‘y’ columns where the row number
ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two –
dimensional array ‘x’ with 3 rows and 3 columns is shown below:

for eg.
class Twodarray
{
public static void main(String[] args)
{
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)


{
for (int j = 0; j < 2; j++)
{
System.out.print(arr[i][j] + " ");
}

System.out.println();
}
}
}

Output:
12
34
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 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. Sub Answers Marking


No. Q. Scheme
N.

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

(a) Define throws & finally statements with its syntax and example. 4M

Ans: 1) throws statement : throws keyword is used to declare that a method may throw (Each
one or some exceptions. The caller must catch the exceptions. statement: 2
marks)
Example :
import java.io.*;
class file1
{
public static void main(String[] args) throws IOException
{
FileWriter file = new FileWriter("Data1.txt");
file.write("These are contents of my file");
file.close();
}
}
2) finally statement : 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.
Example :

import java.io.*;
Page 1 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
class file1
{
public static void main(String[] args)
{
try
{
FileWriter file = new FileWriter("c:\\Data1.txt");
file.write("Hello");
}
catch(IOException)
{}
finally
{
file.close();
}
}
}
(b) Which are the restrictions present for static declared methods? 4M

Ans: Restrictions on static variables : (Each point:


1. Static variables become class variables. 1mark)
2. They get initialized only once in the entire life time of the program.
3. They cannot be called by the object of the class in which they are defied.
4. A static method can operate only on static variables without objects otherwise non
static variables cannot be handled by a static method without using their respective
class object.
(c) Explain any four features of java programming. 4M

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

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.

Page 2 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
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 verifies all
memory access but also ensure that no viruses are communicated with an applet. It does
not use pointers by which you can gain access to memory locations without proper
authorization.

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


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

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

7. Dynamic and Extensible: Java is capable of dynamically linking new class 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.
(d) Explain how interface is used to achieve multiple Inheritance in Java. 4M

Ans: {{**Note:-Any other example can be considered **}} (Explanatio


n: 2 marks,
Multiple inheritances is not possible in java. Multiple inheritance happens when a class is Example: 2
derived from two or more parent classes. Java classes cannot extend more than one parent marks)
classes, instead it uses the concept of interface to implement the multiple inheritance. It
contains final variables and the methods in an interface are abstract. A sub class
implements the interface. When such implementation happens, the class which
implements the interface must define all the methods of the interface. A class can
implement any number of interfaces.
Example of multiple inheritance :

import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2;
Student(String name, int roll_no, double m1, double m2)
{
this.name = name;
this.roll_no = roll_no;
Page 3 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
this.m1 = m1;
this.m2 = m2;
}
}
interface exam {
public void per_cal();
}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)
{
super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of the student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());
double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}

Page 4 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
(B) Attempt any ONE of the following: 6 Marks

(a) Write a java program to implement visibility controls such as public, private, 6M
protected access modes. Assume suitable data, if any.

Ans: {{**Note:- Any common example for all 3 access modes also can be considered **}} (Example : 2
Public access specifier : marks for
class Hello each type)
{
public int a=20;
public void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
obj.show();
}
}
private access specifier :
class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access private data
obj.show(); //Compile Time Error, you can't access private methods
}
}
protected access specifier :
// save A.java
package pack1;
public class A
{
protected void show()
Page 5 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
{
System.out.println("Hello Java");
}
}
//save B.java
package pack2;
import pack1.*;
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
}
(b) With proper syntax and example explain following graphics methods: 6M
1) SetColor( )
2) SetForeGround( )
3) getFont( )
4) setSize( )

Ans: 1) setColor() : (Explanatio


Syntax : n : 1 mark
setColor(Color c) for each
type,
where „c‟ is the Color class object.
Example :
Sets this graphics context's current color to the specified color. ½ mark for
Example : setColor(Color.RED); each type)
2) setForeGround() :
public void setForeground(Color c)
where „c‟ is Color class object
Sets the foreground color of the component.
Example : setForeground(Color.BLUE);
3) getFont() :
Syntax :
public static Font getFont(String nm)
where
nm - the property name.
Returns a font from the system properties list.
public static Font getFont(String nm, Font font)
where
nm - the property name.
font - a default font to return if property 'nm' is not defined.
Returns the specified font from the system properties list.
Example:
Font f=g.getFont();
Page 6 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
4) setSize() :
Syntax :
public void setSize(int width,int height)
where
width - the new width for this Dimension object
height - the new height for this Dimension object
Here the dimension object is generally a frame object.
Sets the size of this Dimension object to the specified width and height.
Example :Frame fm=new Frame();
fm.setSize(200,400);
2. Attempt any TWO of the following: 16Marks

(a) Write a java program to copy the content of the file “file1.txt” into new file 8M
“file2.txt”.

Ans: {{**Note :-Any other logic can be considered**}} (Correct


Logic : 4
import java.io.*; marks,
class filecopy Correct
{ Syntax : 4
public static void main(String args[]) throws IOException marks)
{
FileReader fr=new FileReader("file1.txt");
FileWriter fo=new FileWriter("file2.txt");
int ch;
try
{
while((ch=fr.read())!=-1)
{
fo.write(ch);
}
fr.close();
fo.close();
}
finally
{
if(fr!=null)
fr.close();
if(fo!=null)
fo.close();
}
}
}
Page 7 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
(b) Write a java program to implement multilevel inheritance with 4 levels of hierarchy. 8M

Ans: {{**Note:-Any other example can be considered **}} (Correct


logic:4
class emp marks,
{ Correct
int empid; syntax: 4
String ename; marks)
emp(int id, String nm)
{
empid=id;
ename=nm;
}
}
class work_profile extends emp
{
String dept;
String job;
work_profile(int id, String nm, String dpt, String j1)
{
super(id,nm);
dept=dpt;
job=j1;
}
}
class salary_details extends work_profile
{
int basic_salary;
salary_details(int id, String nm, String dpt, String j1,int bs)
{
super(id,nm,dpt,j1);
basic_salary=bs;
}
double calc()
{
double gs;
gs=basic_salary+(basic_salary*0.4)+(basic_salary*0.1);
return(gs);
}
}
class salary_calc extends salary_details
{
salary_calc(int id, String nm, String dpt, String j1,int bs)
{
super(id,nm,dpt,j1,bs);
Page 8 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
}
public static void main(String args[])
{
salary_calc e1=new salary_calc(101,"abc","Sales","clerk",5000);
double gross_salary=e1.calc();
System.out.println("Empid :"+e1.empid);
System.out.println("Emp name :"+e1.ename);
System.out.println("Department :"+e1.dept);
System.out.println("Job :"+e1.job);
System.out.println("BAsic Salary :"+e1.basic_salary);
System.out.println("Gross salary :"+gross_salary);
}
}
(c) Define applet. Write a program to create an applet to display message “Welcome to 8M
java applet”.

Ans: Java applet is a small dynamic Java program that can be transferred via the Internet and (Definition :
run by a Java-compatible Web browser. The main difference between Java-based 2 marks,
applications and applets is that applets are typically executed in an appletviewer or Java- Program :
correct logic
compatible Web browser. All applets import the java.awt package.
: 3 marks,
/*<applet code= WelcomeJava width= 300 height=300></applet>*/ Correct
syntax : 3
import java.applet.*;
marks)
import java.awt.*;
public class WelcomeJava extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to java”,25,50);
}
}
3. Attempt any FOUR of the following: 16Marks

(a) Explain any four applet tag. 4M

Ans: {{**Note: - Any 4 attributes shall be considered **}} (Any 4


attributes: 1
APPLET Tag: The APPLET tag is used to start an applet from both an HTML document mark each)
and from an appletviewer will execute each APPLET tag that it finds in a separate
window, while web browser will allow many applets on a single page the syntax for the
standard APPLET tag is:
<APPLET
[CODEBASE=codebaseURL]
CODE =appletfileName
[ALT=alternateText]
Page 9 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
[NAME=applet_instance_name]
WIDTH=pixels HEIGHT=pixels
[ALIGN=aligment]
[VSPACE=pixels] [HSPACE=pixels] >
[<PARAM NAME=attributeName1 VALUE=attributeValue>]
[<PARAM NAME=attributeName2 VALUE=attributeValue>]
</APPLET>

CODEBASE: is an optional attribute that specifies the base URL of the applet code or
the directory that will be searched for the applets executable class file.
CODE: is a required attribute that give the name of the file containing your applets
compiled class file which will be run by web browser or applet viewer.
ALT: (Alternate Text) The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.

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

WIDTH AND HEIGHT: are required attributes that give the size(in pixels) of the applet
display area.

ALIGN is an optional attribute that specifies the alignment of the applet. The possible
value is: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE, and ABSBOTTOM.

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

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

(b) Which are the ways to access package from another package? Explain with example. 4M

Ans: There are two ways to access the package from another package. (Different
1. import package.*; ways to
2. import package.classname; access
package :1
1. Using packagename.* mark &
If you use package.* then all the classes and interfaces of this package will be explanation
accessible but not subpackages. of each :
The import keyword is used to make the classes and interfaces of another package 1 ½ mark)
accessible to the current package.

Page 10 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
E.g.
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}}

import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2. Using packagename.classname
If you import packagename.classname then only declared class of this package will be
accessible.
Eg.

import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

(c) Define a class and object. Write syntax to create class and object with an example. 4M

Ans:  Java is complete object oriented programming language. All program code and data (Definition,
reside in object and class. Java classes create objects and objects will communicate syntax and
between using methods. example of
Class: each: 2
 A „class‟ is a user defined data type. Data and methods are encapsulated in class. marks)
 It is a template or a pattern which is used to define its properties.
 Java is fully object oriented language. All program code and data reside within objects
and classes.

Page 11 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
Syntax :
class classname
{
type instance-variable1;
.
.
type methodname1(parameter-list)
{ / / body of method }
}
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. An object consists of state ,behavior and identity.
Syntax:
class_name object=new class_name();

Example:
class Student{
int id; //field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student(); //creating an object of Student
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
} }

(d) With proper syntax and example explain following thread methods: 4M
(1) wait( )
(2) sleep( )
(3) resume( )
(4) notify( )
Ans: {{**Note :- Separate example for each method can also be considered **}} (Each
Method: 1
(1) wait(): mark)
syntax : public final void wait()
This method causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.

Page 12 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
(2) sleep():
syntax: public static void sleep(long millis) throws InterruptedException
We can put a thread to sleep for a specified time period using sleep(time) where time is in
ms. It reenters the runnable state as soon as period has elapsed /over.

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

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

Eg.
class sus extends Thread implements Runnable
{
static Thread th;
float rad,r;
public sus()
{
th= new Thread();
th.start();
}
public void op()
{
System.out.println("\nThis is OP");
if(rad==0)
{
System.out.println("Waiting for input radius");
try
{
wait();
}
catch(Exception ex)
{
}
}
}
public void ip()
{
System.out.println("\nThis is IP");
r=7;
rad= r;
System.out.println(rad);
System.out.println("Area = "+3.14*rad*rad);
notify();
}

Page 13 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
public static void main(String arp[])
{
try{
sus s1 = new sus();
System.out.println("\nReady to go");
Thread.sleep(2000);
System.out.println("\nI am resuming");
th.suspend();
Thread.sleep(2000);
th.resume();
System.out.println("\nI am resumed once again");
s1.op();
s1.ip();
s1.op();
}
catch(Exception e)
{}
}
}
(e) What is type casting? Explain its types with proper syntax and example. 4M

Ans: Assigning a value of one type to a variable of another type is known as Type Casting (Explanation
There are 2 types of type casting of type
1. Widening or Implicit type casting casting:1
2. Narrowing or Explicit type casting mark,
Explanation
of types: 1
1. Widening or Implicit type casting mark,
Syntax &
example:2
marks)

Implicitly Type casting take place when


 The two types are compatible
 The target type is larger than the source type
Program:

Page 14 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515

public class Test { Output:


public static void main(String args[]) {
int i = 100; Int value 100
long l = i; // no explicit type casting require Long value 100
float f = l; // no explicit type casting required Float value 100.0
System.out.println ("Int value " + i);
System.out.println ("Long value " + l);
System.out.println ("Float value " + f);
}}

2. Narrowing or Explicit type casting


 When you are assigning a larger type value to a variable of smaller type. Then you
need to perform explicit type casting.
public class Test
{ Output:
public static void main(String args[]) {
double d = 100.04; Double value 100.04
long l = (long) d; // explicit type casting Long value 100
required
Int value 100
int I = (int) l; // explicit type casting
required

System.out.println ("Double value " +


d);
System.out.println ("Logn value " + l);
System.out.println ("Int value " + I);

}
}

Page 15 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
4. (A) Attempt any THREE of the following: 12Marks

(a) State & explain scope of variable with an example. 4M

Ans: {{**Note :-Any other example can be considered **}} (Explanatio


n: 2 marks
Scope of Variable : &
 We can declare variables within any block Example:2
marks)
 One block equal to one new scope in Java thus each time you start a new block, you
are creating a new scope.
 A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
Program:

// demonstrate block scope.


class Scope {
Output:
public static void main (String args[]) {
int n1; // Visible in main
n1 = 10;
if(n1==10) { n1 and n2 ; 10 20
// start new scope n1 is 10
int n2 = 20; // visible only to this block
// n1 and n2 both visible here.
System.out.println("n1 and n2 : " + n1 + " " + n2);
}
//n2 = 100; // Error! N2 not known here
//n1 is still visible here.
System.out.println("n1 is " + n1);
}
}
 n1 is declared in main block thus it is accessible in main block.
 n2 is declared in if block thus it is only accessible inside if block
 Any attempt to access it outside block will cause compilation error.
 Nested Block can have access to its outmost block.
 If block is written inside main block thus all the variables declared inside main block
are accessible in if block

(b) With syntax and example explain try & catch statement. 4M

Ans: {{**Note :-Any other example can be considered **}}


try- Program statements that you want to monitor for exceptions are contained within a (Explanatio
try block. If an exception occurs within the try block, it is thrown. n of each
with
Page 16 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
Syntax: try syntax:1
{ mark &
// block of code to monitor for errors Example: 2
} marks)

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
}
E.g.
class DemoException {
public static void main(String args[])
{
try
{
int b=8;
int c=b/0;
System.out.println("Answer="+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}}}

(c) Explain applet life cycle with suitable diagram. 4M

Ans: (Diagram :1
mark,
explanation:
3 marks)

Page 17 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
Applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and run as part of a web document. The applet states
include:
 Born or initialization state
 Running state
 Idle state
 Dead or destroyed state

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

Initialization happens only once in the life time of an applet.


public void init()
{
//implementation
}

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

Idle or stopped state: an applet becomes idle when it is stopped from running. Stopping
occurs automatically when the user leaves the page containing the currently running
applet. stop() method may be overridden to terminate the thread used to run the applet.
public void stop()
{
//implementation
}

Dead state: an applet is dead when it is removed from memory. This occurs automatically
by invoking the destroy method when we quit the browser. Destroying stage occurs only
once in the lifetime of an applet. destroy() method may be overridden to clean up
resources like threads.
public void destroy()
{
//implementation
}
Page 18 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
Display state: applet is in the display state when it has to perform some output operations
on the screen. This happens after the applet enters the running state. paint() method is
called for this. If anything is to be displayed the paint() method is to be overridden.
public void paint(Graphics g)
{
//implementation
}

(d) Explain byte stream class in detail. 4M

Ans:  It is used for creating & manipulating streams and files for reading and writing bytes. (Explanation
 Since the steams are unidirectional, they can transmit bytes in only one direction and, of byte
therefore, java provides two kinds of byte stream classes – stream class
1. Input Stream classes : 2 marks,
2. Output Stream classes Each type:1
mark)
1. Input stream classes
 Input stream classes are used to read 8-bit bytes include a super class known as
InputStream and a number of subclasses for supporting various input-related
functions.
 The superclass InputStream is an abstract class and therefore, we cannot create
instances of this class. Rather we must use the subclasses that inherit from this class.
The InputStream includes methods that are designed to perform the following tasks:
 Reading bytes
 Closing streams
 Making position in the streams
 Finding the number of bytes in stream
 Methods of InputStream & FileInputStream class
Methods Description

int read() Read byte from Input stream /File Input Stream

int read (byte b [] ) Read an arrayof bytes into b

int read(byte b [],int n, int m) Read m bytes into b starting from nth byte

int available () Gives number of bytes available in the input

long skip(long n bytes) Skips over n bytes from the input stream and return
the number of bytes actually ignored.

void close () Closes the input stream / file Input Stream

Page 19 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
2. Output Stream classes:
 Output Stream classes are used to write 8-bit bytes
 Output Stream classes are derived from bsae class OutputStream.
 Like InputStream, the OutputStream is an abstract class and therefore we cannot
instantiate it.
 The several subclasses of the OutputStream can be used for performing the output
operations.
 The OutputStream includes methods that are designed to perform the following
task:
1. Writing bytes
2. Closing streams
3. Flushing streams
Methods of InputStream & fileInputStream class :

Methods Description

void write(int b) Write a bytes to the output stream

void write(byte b[]) Write all bytes in the array b to the output stream

void write(byte [] ),int n, int m) Write m bytes from array b starting from nth byte

void close() Closes the output stream

(B) Attempt any ONE of the following: 6 Marks

(a) Write a java program to implement following functions of string: 6M


(1) Calculate length of string
(2) Compare between strings
(3) Concatenating strings

Ans: {{**Note:- Any relevant program can be considered**}} (Each


function: 2
class StringDemo marks)
{
public static void main(String args[])
{
String str1="INDIA";
String str2="India";
String str3="My India";
String str4="India";
System.out.println("The length of string INDIA is "+str1.length()); //Length of string
System.out.println("Comparing String India and India is "+str2.equals(str4));
System.out.println("Comparing String INDIA and India is "+str1.equals(str2));
System.out.println("Comparing String INDIA and India with equalsIgnoreCase is
Page 20 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
"+str1.equalsIgnoreCase(str2));
String str5="I Love";
System.out.println("Result of concatinating of string is "+str5.concat(str3));
}
}
Output (optional)

The length of string INDIA is 5


Comparing String India and India is true
Comparing String INDIA and India is false
Comparing String INDIA and India with equalsIgnoreCase is true
Result of concatenating of string is I LoveMy India
(b) Write a java program to extend interface assuming suitable data. 6M

Ans: {{**Note: - Any other relevant program shall be considered**}} (Creation of


interface
interface A and extend
{ it: 4 marks
int x=20; &
void display(); implementin
} g into
interface B extends A class:2
{ marks)
int y=30;
void show();
}
class C implements B
{
public void display()
{
System.out.println("A's X="+x);
}
public void show()
{
System.out.println("A's X="+x);
System.out.println("B's Y="+y);
}
public static void main(String args[])
{
C obj=new C();
obj.display();
obj.show();
}
}

Page 21 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
5. Attempt any TWO of the following : 16Marks

(a) Write a java program to implement runnable interface with example. 8M

Ans: {{**Note:- Any other relevant program shall be considered **}} (Correct
logic : 4
class NewThread implements Runnable { marks,
Thread t; Syntax : 4
NewThread() { marks)
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Page 22 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
(b) Write a java program to display all the odd numbers between 1 to 30 using for loop 8M
& if statement.

Ans: class OddNum (Correct


{ logic : 4
public static void main(String args[]) marks,
{ Syntax :
for(int i=1;i<=30;i++) 4marks)
{
if(i%2 ==1)
{
System.out.print("Odd number :"+i +"\n");

}
}
}
}

(c) Explain following methods for applet with an example: 8M


(1) Passing Parameter to applet
(2) Embedding <applet> tags in java code.
Ans: {{**Note :-Any other example can be considered **}} (Method of
Passing
1)Passing parameter to applet parameter :
Parameter can be passed to applet through Param attributes of applet tag. 2marks,
[<PARAM NAME=attributeName1 VALUE=attributeValue>] Applet tag
explanation
getParameter() Method: The getParameter() method of the Applet class can be : 2 marks,
used to retrieve the parameters passed from the HTML page. Example : 4
marks)
Syntax of getParameter() method :
String getParameter(String param-name)
2)APPLET Tag: Embedding applet tag in java code by two ways.
 Adding applet tag to html file
 Adding applet tag in java source file
1. Example for embedding <applet> tag in html file.
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
Page 23 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
}
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>
2. Example for embedding <applet> tag in Java source file.
import java.awt.*;
import java.applet.*;
/*<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>*/
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
6. Attempt any FOUR of the following : 16Marks

(a) Explain following bitwise operator with an example: 4M


(1) left shift operator
(2) write shift operator
Ans: {{**Note: Any other example in program also can be considered **}} (Each
Ans: Bitwise
The Left Shift (<<): the left shift operator, <<, shifts all of the bits in a „value‟ to operator
explanation:
the left a specified number of times specified by „num‟
1 mark,
General form : value <<num Each
e.g. x << 2 (x=12) example:1
0000 1100 << 2 mark)

Page 24 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
= 0011 0000 (decimal 48)
The Right Shift (>>): the right shift operator, >>, shifts all of the bits in a „value‟
to the right a specified number of times specified by „num‟
General form: value >>num
e.g. x>> 2 (x=32)
0010 0000 >> 2
= 0000 1000 (decimal 8)
(b) State & explain types of errors in Java. 4M

Ans: Types of Error ( Two types


1) Compile Time Errors: : 2 marks
All syntax errors given by Java Compiler are called compile time errors. When program each)
is compiled java checks the syntax of each statement. If any syntax error occurs, it will
be displayed to user, and .class file will not be created.
Common compile time Errors
1) Missing semicolon
2) Missing of brackets in classes and methods
3) Misspelling of variables and keywords.
4) Missing double quotes in Strings.
5) Use of undeclared variable.
6) Incompatible type of assignment/initialization.
7) Bad reference to object.

2) Run time error:


After creating .class file, Errors which are generated, while program is running are known
as runtime errors. Results in termination of program.
Common runtime Errors
1. Dividing an integer by zero.
2. Accessing an element that is out of the bounds of an array.
3. Trying to store data at negative index value.
4. Opening file which does not exist.
5. Converting invalid string to a number.
(c) Enlist types of constructor. Explain any two with example. 4M

Ans: {{**Note :- Any other example can be considered **}} (List : 1


Types of constructors in java: mark , Any
1. Default constructor (no-arg constructor) 2
2. Parameterized constructor explanation
3. copy constructor with
example :
1 ½ mark
Page 25 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
1. Default Constructor each)
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
{}
Example:

class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
2. parameterized constructor
A constructor which has a specific number of parameters is called parameterized
constructor.
Parameterized constructor is used to provide different values to the distinct objects.
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display()
{ System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Page 26 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
3. Copy Constructor:
A copy constructor is used for copying the values of one object to another object.
Example:
class Student6{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1); //copy constructor called
s1.display();
s2.display();
}
}
(d) How to add new class to a package? Explain with an example. 4M

Ans: {{ **Note :-Any other example shall be considered **}} (Explanatio


n :2 marks,
Create a package : simply include a package command as the first statement in a Java
Any
source file.
Example: 2
Include classes:
marks)
Any classes declared within that file will belong to the specified package. The package
statement defines a name space in which classes are stored. If you omit the package
statement, the class names are put into the default package, which has no name.
Syntax: package pkg; //Here, pkg is the name of the package
public class class_name
{
//class body goes here
}

Example:
package package1;
public class Box

Page 27 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
{
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();
}
}
(e) Explain Arrary list & Iterator methods of collections with an example. 4M

Ans: Methods of ArrayList class : (Any 2


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

2. boolean add(Object o)
Appends the specified element to the end of this list.

3. boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator. Throws
NullPointerException if the specified collection is null.

4. boolean addAll(int index, Collection c)


Inserts all of the elements in the specified collection into this list, starting at the
specified position. Throws NullPointerException if the specified collection is null.

5. void clear()
Removes all of the elements from this list.

6. Object clone()
Returns a shallow copy of this ArrayList.

Page 28 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
7. boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if
and only if this list contains at least one element e such that (o==null ? e==null :
o.equals(e))

8. void ensureCapacity(int minCapacity)


Increases the capacity of this ArrayList instance, if necessary, to ensure that it can
hold at least the number of elements specified by the minimum capacity argument.

9. Object get(int index)


Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >= size()).

10. int indexOf(Object o)


Returns the index in this list of the first occurrence of the specified element, or -1 if
the List does not contain this element.

11. int lastIndexOf(Object o)


Returns the index in this list of the last occurrence of the specified element, or -1 if the
list does not contain this element.

12. Object remove(int index)


Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).

13. protected void removeRange(int fromIndex, int toIndex)


Removes from this List all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.

14. Object set(int index, Object element)


Replaces the element at the specified position in this list with the specified element.
Throws IndexOutOfBoundsException if the specified index is is out of range (index <
0 || index >= size()).

15. int size()


Returns the number of elements in this list.

16. Object[] toArray()


Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.

17. Object[] toArray(Object[] a)


Returns an array containing all of the elements in this list in the correct order; the
runtime type of the returned array is that of the specified array.

Page 29 of 30
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
___________________________________________________________________________________________________________________________
SUMMER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
18. void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
Methods of Iterator class :

1. boolean hasNext( ) :Returns true if there are more elements. Otherwise, returns
false.
2. Object next( ) :Returns the next element. Throws NoSuchElementException if
there is not a next element.
3. void remove( ): Removes the current element. Throws IllegalStateException if an
attempt is made to call remove( ) that is not preceded by a call to next( ).

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

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

Important Instructions to examiners:


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

Q.N Sub Answer Marking


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

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

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

that can violate access right to objects


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

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


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

public String getParent()


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

public boolean isAbsolute()


Tests whether this abstract pathname is absolute.

public String getAbsolutePath()


Returns the absolute pathname string of this abstract pathname.

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

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

public boolean canRead()


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

public boolean canWrite()


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

public boolean exists()


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

public boolean isDirectory()


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

public boolean isFile()


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

public boolean isHidden()


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

public long lastModified()


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

public long length()


Returns the length of the file denoted by this abstract pathname

public boolean createNewFile() throws IOException


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

public boolean delete()


Deletes the file or directory denoted by this abstract pathname

public String[] list()


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

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

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

public boolean renameTo(File dest)


Renames the file denoted by this abstract pathname.

public boolean setLastModified(long time)


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

public boolean setReadOnly()


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

public boolean setWritable(boolean writable, boolean ownerOnly)


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

public boolean equals(Object obj)


Tests this abstract pathname for equality with the given object

public String toString()


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

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

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

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

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

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


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

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

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

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

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

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

(d) What is thread? Draw thread life cycle diagram in Java. 4M


(Note: Explanation of the life cycle is not needed).
Ans. A thread is a single sequential flow of control within a program.
They are lightweight processes that exist within a process. They
share the process’s resource, including memory and are more 2M for
efficient. JVM allows an application to have multiple threads of defining a
execution running concurrently. Thread has a priority. Threads with thread
higher priority are executed in preference to threads with lower
priority.

2M for
diagram

1. (B) Attempt any ONE of the following: 1 x 6 =6


(a) What is single level inheritance? Explain with suitable example. 6M
(Note: Any appropriate program may be written).
Ans.
Single level inheritance enables a derived class to inherit properties
and behaviour from a single parent class. It allows a derived class to Explanati
inherit the properties and behaviour of a base class, thus enabling on with
code reusability as well as adding new features to the existing code. suitable
This makesthe code much more elegant and less repetitive. Single diagram
level inheritance can be represented by the following 2M

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

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

Example:
class SingleLevelInheritanceParent {
int l;
SingleLevelInheritanceParent(int l) { 4M for
this.l = l;
correct
}
void area() {
program
int a = l*l;
System.out.println("Area of square :"+a);
}

class SingleLevelInheritanceChild extends SingleLevelInheritanceParent


{
SingleLevelInheritanceChild(int l) {
super(l);
}
void volume() {
int v;
v= l*l*l;
System.out.println("Volume of the cube is "+v);
}
void area() {
int a;
a = 6*l*l;
System.out.println("Total surface area of a cube is "+a);
}
}

class SingleLevelInheritance {

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

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

public static void main(String ar[]) {


SingleLevelInheritanceChild cube = new
SingleLevelInheritanceChild(2);
cube.volume();
cube.area();
}
}
(b) What is package? State how to create and access user defined 6M
package in Java.
(Note: Code snippet can be used for describing)
Ans. Package is a name space that organizes a set of related classes and 2M for
interfaces. Conceptually, it is similar to the different folders in a definition
computer. It also provides access protection and removes name of
collision. package
Packages can be categorized into two:- built-in and user defined.
Creation of user defined package:
To create a package a physical folder by the name should be created
in the computer.
Example: we have to create a package myPack, so we create a
folder d:\myPack 2M each
The java program is to be written and saved in the folder myPack. for
To add a program to the package, the first line in the java program explanati
should be package <name>; followed by imports and the program on of
logic. creation
package myPack; and
import java.util; access of
public class Myclass { user
//code defined
} package
Access user defined package:
To access a user defined package, we need to import the package in
our program. Once we have done the import we can create the
object of the class from the package and thus through the object we
can access the instance methods.
import mypack.*;
public class MyClassExample{
public static void main(String a[]) {
Myclass c= new Myclass();
}
}

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

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

2. Attempt any TWO of the following: 2 x 8=16


(a) Write a program to add 2 integer, 2 string and 2 float objects to 8M
a vector. Remove element specified by user and display the list.
Ans. importjava.util.*;
import java.io.*;

class Vect { 4M for


public static void main(String a[]) {
correct
Vector<Object> v = new Vector<Object>();
v.addElement(new Integer(5));
syntax
v.addElement(new Integer(10));
v.addElement(new String("String 1"));
v.addElement(new String("String 2")); 4M for
v.addElement(new Float(5.0)); correct
v.addElement(new Float(6.7)); logic
int n=0;
BufferedReader b = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Following are the elements in the vector");
for(int i = 0; i <v.size();i++) {
System.out.println("Element at "+i+ "is "+v.elementAt(i));
}
System.out.println("Enter the position of the element to be removed");
try {
n = Integer.parseInt(b.readLine());
} catch(Exception e) {
System.out.println("Exception caught!"+e);
}
System.out.println("The element at "+n +"is "+v.elementAt(n)+"
will be removed");
v.removeElementAt(n);

System.out.println("The following are the elements in the


vector");

for(int i = 0; i<v.size();i++) {
System.out.println(v.elementAt(i));
}
}
}
(b) What is meant by interface? State its need and write syntax and 8M
features of interface.

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

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

Ans. Interface is the mechanism by which multiple inheritance is Definition


possible in java. It is a reference type in Java. An interface has all 2M
the methods undefined. For a java class to inherit the properties of
an interface, the interface should be implemented by the child class
using the keyword “implements”. All the methods of the interface
should be defined in the child class.
Example: program
interface MyInterface{ optional
int strength=60;
void method1();
void method2();
}
public class MyClass implements MyInterface {
int total;
MyClass(int t) {
total = t;
}
public void method1() {
int avg = total/strength;
System.out.println("Avg is "+avg);
}
public void method2() {

}
public static void main(String a[]) {
MyClass c = new MyClass(3600);
c.method1();
}
}

Need:
A java class can only have one super class. Therefore for achieving Need 2M
multiple inheritance, that is in order for a java class to get the
properties of two parents, interface is used. Interface defines a set
of common behaviours. The classes implement the interface, agree
to these behaviours and provide their own implementation to the
behaviours.

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

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

Syntax:
interface InterfaceName { Syntax
int var1 = value; 2M
int var2 = value;
public return_type methodname1(parameter_list) ;
public return_type methodname2(parameter_list) ;

Features:
Interface is defined using the keyword “interface”. Interface is Features
implicitly abstract. All the variables in the interface are by default 2M
final and static. All the methods of the interface are implicitly
public and are undefined (or implicitly abstract). It is compulsory
for the subclass to define all the methods of an interface. If all the
methods are not defined then the subclass should be declared as an
abstract class.
(c) Explain applet life cycle with suitable diagram. 8M
Ans.

3M for
diagram

Applets are small applications that are accessed on an Internet


server, transported over the Internet, automatically installed, and 5M for
run as part of a web document. The applet states include: explanati
 Born or initialization state on
 Running state
 Idle state

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

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

 Dead or destroyed state

Initialization state: applet enters the initialization state when it is


first loaded. This is done by calling the init() method of Applet
class. At this stage the following can be done:
 Create objects needed by the applet
 Set up initial values
 Load images or fonts
 Set up colours
Initialization happens only once in the life time of an applet.
public void init() {
//implementation
}
Running state: applet enters the running state when the system
calls the start() method of Applet class. This occurs automatically
after the applet is initialized. start() can also be called if the applet is
already in idle state. start() may be called more than once. start()
method may be overridden to create a thread to control the applet.
public void start() {
//implementation
}
Idle or stopped state: an applet becomes idle when it is stopped
from running. Stopping occurs automatically when the user leaves
the page containing the currently running applet. stop() method may
be overridden to terminate the thread used to run the applet.
public void stop() {
//implementation
}
Dead state: an applet is dead when it is removed from memory.
This occurs automatically by invoking the destroy method when we
quit the browser. Destroying stage occurs only once in the lifetime
of an applet. destroy() method may be overridden to clean up
resources like threads.
public void destroy() {
//implementation
}

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


some output operations on the screen. This happens after the applet

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

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

enters the running state. paint() method is called for this. If anything
is to be displayed the paint() method is to be overridden.
public void paint(Graphics g) {
//implementation
}
3. Attempt any FOUR of the following: 4 x 4 =16
(a) Explain the following methods of string class with syntax and 4M
example:
(i) substring()
(ii) replace()
(Note: Any other example can be considered)
Ans. (i) substring():
Syntax:
String substring(intstartindex)
startindex specifies the index at which the substring will begin.It Each
will returns a copy of the substring that begins at startindex and method
runs to the end of the invoking string syntax
(OR) 1M
String substring(intstartindex,intendindex) and
Here startindex specifies the beginning index,andendindex specifies example
the stopping point. The string returned all the characters from the 1M
beginning index, upto, but not including,the ending index.
Example :
System.out.println(("Welcome”.substring(3)); //come
System.out.println(("Welcome”.substring(3,5));//co

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

Syntax: String replace(char oldChar, char newChar)


Example:
String Str = new String("Welcome”);
System.out.println(Str.replace('o', 'T')); // WelcTme
(b) Write a program to find sum of digit of number entered by 4M
user.
(Note: Direct Input or User Defined Input is also allowed & Any
Other Logic also allowed)
Ans. class Sum1

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

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

{
public static void main(String args[]){
intnum = Integer.parseInt(args[0]); //takes argument as
command line Logic
int remainder, result=0; 2M
while(num>0)
{
remainder = num%10; Syntax
result = result + remainder; 2M
num = num/10;
}
System.out.println("sum of digit of number is : "+result);
}
}
OR
import java.io.*;
class Sum11{
public static void main(String args[])throws IOException{
BufferedReaderobj = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter number: ");
int num=Integer.parseInt(obj.readLine());
int remainder, result=0;
while(num>0)
{
remainder = num%10;
result = result + remainder;
num = num/10;
}
System.out.println("sum of digit of number is : "+result);
}
}
(c) What is Iterator class? Give syntax and use of any two methods 4M
of Iterator class.
Ans. Iterator enables you to cycle through a collection, obtaining or
removing elements.
Each of the collection classes provides an iterator( ) method that Definition
returns an iterator to the start of the collection. By using this iterator 1M
object, you can access each element in the collection, one element

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

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

at a time
Syntax :
Iterator iterator_variable = collection_object.iterator(); Syntax
1M
Methods:
1. Boolean hasNext( ):Returns true if there are more elements. Any 2
Otherwise, returns false. methods
2. Object next( ): Returns the next element. Throws 1M each
NoSuchElementException if there is not a next element.

3.void remove( ):Removes the current element. Throws


IllegalStateException if an attempt is made to call remove( )
that is not preceded by a call to next( ).

(d) Describe the following attributes of applet. 4M


(i) Codebase
(ii) Alt
(iii) Width
(iv) Code
Ans. (i) Codebase: Codebaseis an optional attribute that specifies the
base URL of the applet code or the directory that will be Each
searched for the applet’s executable class file. attribute
(ii) Alt: Alternate Text. The ALT tag is an optional attribute used to descriptio
specify a short text message that should be displayed if the n 1M
browser cannot run java applets.
(iii) Width: Widthis required attributes that give the width (in
pixels) of the applet display area.
(iv) Code:Codeis a required attribute that give the name of the file
containing your applet’s compiled class file which will be run
by web browser or appletviewer
(e) State three uses of final keyword. 4M
Ans. Uses of final keyword:
1. Prevent overriding of method:
To disallow a method to be overridden final can be used as a
modifier at the start of declaration. Methods written as final Prevent
cannot be overridden. overridin
e.g. g :1½M
class test
{

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

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

final void disp() //prevents overidding


{
System.out.println(“In superclass”);
}
}
class test1 extends test {
voiddisp(){ // ERROR! Can't override
System.out.println("Illegal!");
}
}
2. Prevent inheritance:
Final can be used to even disallow the inheritance, to do this a class
can be defined with final modifier, declaring a class as final Prevent
declares all its method as final inheritan
e.g. ce :1½M
final class test
{
void disp()
{
System.out.println(“In superclass”);
}
}Class test1 extends test // error as class test is final
{

}
3. Declaring final variable: Declaring
Variable declared final, it is constant which will not and can not final: 1M
change.
final int FILE_NEW = 1;
4. (A) Attempt any THREE of the following: 3 x 4 =12
(a) Write all primitive data types available in Java with their 4M
storage sizes in bytes.
Ans.
Sr. Type Keyword Width
No. (bytes) Storage
1 long integer long 8 Size of
Short integer short 2 any 4:1M
Integer int 4 each
Byte byte 1

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

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

2 Double double 8
Float float 4
3 Character char 2
4 Boolean Boolean 1 bit
(b) What is thread priority? Write default priority values and 4M
methods to change them.
Ans. Thread Priority: In java each thread is assigned a priority which Thread
affects the order in which it is scheduled for running. Thread Priority
priority is used to decide when to switch from one running thread to explanati
another. Threads of same priority are given equal treatment by the on 1M
java scheduler.
Default Priority Values:Thread priorities can take value from
1 to10.
Thread class defines default priority constant values as
Default
MIN_PRIORITY = 1
priority
NORM_PRIORITY = 5 (Default Priority) values 1M
MAX_PRIORITY = 10
1. setPriority:
Syntax:public void setPriority(int number);
This method is used to assign new priority to the thread.
Each
2. getPriority: method
Syntax:public intgetPriority(); 1M
It obtain the priority of the thread and returns integer value.
(c) Write a program to generate Fibonacci series 1 1 2 3 5 8 13 4M
21 34 55 89.
Ans. class FibonocciSeries
{ Syntax
public static void main(String args[]) 2M
{
int num1 = 1,num2=1,ans;
System.out.println(num1); Logic 2M
while (num2< 100)
{
System.out.println(num2);
ans = num1+num2;
num1 = num2;

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

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

num2=ans;
}
}
}
(d) Differentiate between Applet and Application (any 4 points). 4M
Ans. Sr. Applet Application
No.
1 Applet does not use Application usesmain()
main() method for method for initiating execution Any 4
initiating execution of of code. points 1M
code. each

2 Applet cannot run Application can run


independently. independently.
3 Applet cannot read Application can read from or
from or write to files in write to files in local computer.
local computer.
4 Applet cannot Application can communicate
communicate with with other servers on network.
other servers on
network.
5 Applet cannot run any Application can run any
program from local program from local computer.
computer.
6 Applet are restricted Application are not restricted
from using libraries from using libraries from other
from other language language.
such as C or C++.
4. (B) Attempt any ONE of the following: 1x6=6
(a) Write a program to draw a bar chart for plotting students 6M
passing percentage in last 5 years.
(Note: Any other logic can be considered)(HTML file with
separate applet tag may also be considered)
Ans.
importjava.awt.*; Applet tag
importjava.applet.*; 2M
/* <Applet code=”BarChart” width=400 height=400>
<param name=”columns” value=”5”>

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

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

<param name=”c1” value=”80”>


<param name=”c2” value=”90”> Syntax
<param name=”c3” value=”100”> 2M
<param name=”c4” value=”85”>
<param name=”c5” value=”95”>

<param name=”label1” value=”2012”> Logic


<param name=”label2” value=”2013”> 2M
<param name=”label3” value=”2014”>
<param name=”label4” value=”2015”>
<param name=”label5” value=”2016”>
</Applet>
*/
public class BarChart extends Applet
{ int n=0;
String label[];
int value[];
public void init()
{

try
{
n=Integer.parseInt(getParameter("columns"));
label=new String[n];
value=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
label[4]=getParameter("label5");

value[0]=Integer.parseInt(getParameter("c1"));
value[1]=Integer.parseInt(getParameter("c2"));
value[2]=Integer.parseInt(getParameter("c3"));
value[3]=Integer.parseInt(getParameter("c4"));
value[4]=Integer.parseInt(getParameter("c5"));
}
catch(NumberFormatException e)
{

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

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

System.out.println(e);
}
}
public void paint(Graphics g)
{
for(int i=0;i<n;i++)
{
g.setColor(Color.red);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.green);
g.fillRect(50,i*50+10,value[i],30);
}
}
}
(b) What is garbage collection in Java? Explain finalize method in 6M
Java.
(Note: Example optional)
Ans. Garbage collection:
 Garbage collection is a process in which the memory allocated to
objects, which are no longer in use can be freed for further use.
 Garbage collector runs either synchronously when system is out Garbage
of memory or asynchronously when system is idle. collection
 In Java it is performed automatically. So it provides better explanati
memory management. on 4M
 A garbage collector can be invoked explicitly by writing
statement
System.gc(); //will call garbage collector.
Example:
public class A
{
int p;
A()
{
p = 0;
}
}
class Test
{
public static void main(String args[])

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

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

{
A a1= new A();
A a2= new A();
a1=a2; // it deallocates the memory of object a1
}
}

Method used for Garbage Collection finalize:


 The java.lang.Object.finalize() is called by garbage collector on
an object when garbage collection determines that there are no Finalize
more reference to the object. method
 A subclass override the finalize method to dispose of system explanati
resources or to perform other cleanup. on
 Inside the finalize() method, the actions that are to be performed 2M
before an object is to be destroyed, can be defined. Before an
object is freed, the java run-time calls the finalize() method on
the object.
General Form :
protected void finalize()
{ // finalization code here
}
5. Attempt any TWO of the following: 2 x 8 = 16
(a) What is exception? WAP to accept a password from the user 8M
and throw “Authentication Failure” exception if the password
is incorrect.
Ans. An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program execution.
It can be handled by 5 keywords in java as follows : Exception
1) try: This block monitors the code for errors. 2M
2) catch: This block implements the code if exception is raised
due to some error in try block.
3) throw: To throw a user define exception
4) throws: Can be used with the method’s declaration which are
may have some run time errors.
5) finally: Includes the code which executes irrespective of errors
in try block.
Program :
import java.io.*;

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

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

class PasswordException extends Exception


{
PasswordException(String msg)
{
super(msg); Correct
} logic 3M
}
class PassCheck
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("abc123"))
{ Correct
System.out.println("Authenticated "); Syntax
} 3M
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
(b) Write a program to create two threads, one to print numbers in 8M
original order and other in reverse order from 1 to 10.
Ans. class thread1 extends Thread
{

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

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

public void run()


{ Correct
for(int i=1 ; i<=10;i++) Logic 4M
{
System.out.println("Thread 1 :" +i);
}
}
}
class thread2 extends Thread
{
public void run() Correct
{ syntax
for(int i=10 ; i>=1;i--) 4M
{
System.out.println("Thread 2 :" +i);
}
}
}
class test
{
public static void main(String args[])
{
thread1 t1 = new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}
(c) Explain the following methods of applet class: 8M
(i) drawRect()
(ii) drawPolygon()
(iii) drawArc()
(iv) drawRoundRect()
Ans. (i) drawRect(): Each
method
The drawRect() method displays an outlined rectangle. 2M
Syntax: void drawRect(inttop, intleft, intwidth, int height)
The upper-left corner of the Rectangle is at top and left.
The dimension of the Rectangle is specified by width and height.
Example:
Page 23 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)

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

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

(ii) drawPolygon():
drawPolygon() method is used to draw arbitrarily shaped figures.
Syntax: void drawPolygon(int x[], int y[], intnumPoints)
The 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:
intxpoints[]={30,200,30,200,30};
intypoints[]={30,30,200,200,30};
intnum=5;
g.drawPolygon(xpoints,ypoints,num);

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

(iv)drawRoundRect():
It is used to draw rectangle with rounded corners.
Syntax : drawRoundRect(int x,int y,int width,int height,int
arcWidth,int arcHeight)
Where x and y are the starting coordinates, with width and height
as the width and height of rectangle.
arcWidth and arcHeight defines by what angle the corners of
rectangle are rounded.
Example: g.drawRoundRect(25, 50, 100, 100, 25, 50);

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

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

6. Attempt any FOUR of the following: 4 x 4 = 16


(a) Write a program to implement following inheritance: 4M

Ans. interface gross


{
int ta=1000;
int da=4000;
public void gross_sal();
} Correct
class employee Logic 2M
{
String name="Abc";
int basic_sal=8000;
}
class salary extends employee implements gross Correct
{ syntax
int hra; 2M
int total=0;
salary(int h)
{
hra=h;
}
public void gross_sal()
{
total=basic_sal+ta+da+hra;
}

void disp_sal()
{
gross_sal();
System.out.println("Name :"+name);
System.out.println("Total salary :"+total);
}

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

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

public static void main(String args[])


{
salary s = new salary(3000);
s.disp_sal();
}
}
(b) What is the use of ArrayList class? State any two methods with 4M
their use from ArrayList.
Ans. Use of ArrayList class:
1. ArrayList supports dynamic arrays that can grow as needed.
2. ArrayList is a variable-length array of object references. That is,
an ArrayListcan dynamically increase or decrease in size. Array
lists are created with an initial size. When this size is exceeded, the Use 2M
collection is automatically enlarged. When objects are removed, the
array may be shrunk.

Methods of ArrayList class :


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

2.boolean add(Object o)
Appends the specified element to the end of this list.
booleanaddAll(Collection c)
Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified
collection's iterator. Throws NullPointerException if the specified
collection is null.

3. booleanaddAll(int index, Collection c)


Inserts all of the elements in the specified collection into this list,
starting at the specified position. Throws NullPointerException if
the specified collection is null.

4. void clear()
Removes all of the elements from this list. 6. Object clone()
Returns a shallow copy of this ArrayList.

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

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

5. boolean contains(Object o)
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one
element e such that (o==null ? e==null : o.equals(e)).

6. void ensureCapacity(intminCapacity)
Increases the capacity of this ArrayList instance, if necessary, to
ensure that it can hold at least the number of elements specified by
the minimum capacity argument.

7. Object get(int index)


Returns the element at the specified position in this list.
Throws IndexOutOfBoundsException if the specified index is is out
of range (index < 0 || index >= size()).

8. intindexOf(Object o)
Returns the index in this list of the first occurrence of the specified
element, or -1 if the List does not contain this element.

9. intlastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified
element, or -1 if the list does not contain this element.

10. Object remove(int index)


Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 ||
index >= size()).

11. protected void removeRange(intfromIndex, inttoIndex)


Removes from this List all of the elements whose index is between
fromIndex, inclusive and toIndex, exclusive.

12. Object set(int index, Object element)


Replaces the element at the specified position in this list with the
specified element. Throws IndexOutOfBoundsException if the
specified index is is out of range (index < 0 || index >= size()).

13. int size()

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

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

Returns the number of elements in this list.

14. Object[] toArray()


Returns an array containing all of the elements in this list in the
correct order. Throws NullPointerException if the specified array is
null.

15. Object[] toArray(Object[] a)


Returns an array containing all of the elements in this list in the
correct order; the runtime type of the returned array is that of the
specified array.

16.void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current
size.
(c) Design an applet which accepts username as a parameter for 4M
html page and display number of characters from it.
Ans. importjava.awt.*;
importjava.applet.*;
public class myapplet extends Applet
{ Correct
String str=""; Logic 2M
public void init()
{
str=getParameter("uname");
} Correct
public void paint(Graphics g) syntax
{ 2M
int n= str.length();
String s="Number of chars = "+Integer.toString(n);
g.drawString(s,100,100);
}
}

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


<param name="uname" value="student1">
</applet>*/
(d) List any four built-in packages from Java API along with their 4M
use.

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

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

Ans. 1. java.lang: Contains Language support classes which are used by


Java compiler during compilation of program Any 4
2. java.util: Contains language utility classes such as vectors, hash packages
tables, random numbers, date etc. with its
3. java.io: Contains I/O support classes which provide facility for use 1M
input and output of data. each
4. java.awt: Contains a set of classes for implementing graphical
user interface.
5. java.aplet: Contains classes for creating and implementing
applets.
6. java.sql: Contains classes for database connectivity.
7. java.net: Contains classes for networking.
(e) Write a program to accept two numbers as command line 4M
arguments and print the addition of those numbers.
Ans. class addition
{
public static void main(String args[])
{ Correct
int a,b; Logic 2M
a= Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]); Correct
int c= a+b; syntax2M
System.out.println("Addition= "+c);
}
}

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

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

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the 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. (A) Attempt any THREE of the following: 3x4=12
(a) Explain inheritance and polymorphism features of Java. 4M
Ans. Inheritance: inheritance is the process by which one object acquires
the properties of another object. It supports the concept of 2M each
hierarchical classification. Without the use of hierarchies, each object for
would need to define all the characteristics explicitly. By use of inherita
inheritance, an object need only define those qualities that make it nce and
unique within its class. It can inherit the general attributes from its polymor
parent. It is the inheritance mechanism that makes it possible for one phism
object to be a specific instance of a more general case.
For e.g.: Parrot is a classification of Bird. Therefore Parrot is a
subclass of Bird. Parrot inherits a lot many features of the class Bird
plus some additional features.
class Bird {

}
class Parrot extends Bird {
}

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

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

Polymorphism: it is a feature that allows one interface to be used for


a general class of actions. The specific action is determined by the
exact nature of the situation. By this concept it is possible to design a
generic interface to a group of related activities.
For E.g:- void add(int a, int b){
int sum = a+b;
System.out.println(sum);
}
void add(float a, float b){
float sum = a+b;
System.out.println(sum);
}
(b) Write any two methods of array list class with their syntax. 4M
Ans. booleanadd(E e): Appends the specified element to the end of this
list

void add(int index, E element) Inserts the specified element at the


specified position in this list.

void clear():Removes all of the elements from this list Any two
methods
Objectclone():Returns a shallow copy of this ArrayList instance with
proper
booleancontains(Object o): Returns true if this list contains the syntax
specified element. (return
type and
Eget(int index): Returns the element at the specified position in this paramet
list. ers)
2M each
intindexOf(Object o): Returns the index position of the element in
the list

booleanisEmpty() :Returns true if the list is empty.

intlastIndexOf(Object o): Returns the index of the last occurrence


of the object specified.

boolean remove(Object o): Removes the first occurrence of the


object from the list if it is present.

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

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

int size(): returns the number of elements in the list.


(c) Why java became platform independent language? Explain. 4M
(Note: Any other correct diagram may also 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
JVM which is the interpreter for the byte code. Byte code is not a Explana
machine specific code. Byte code is a universal code and can be tion 3M
moved anywhere 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 byte code.

Java Java Virtual


Program Compiler Machine

1M for
Source Code Byte Code diagram
Process of Compilation

Byte Code Java Machine


Interpreter Code

Virtual Machine Real Machine


Process of converting byte code into machine code

OR

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

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

(d) Write a program to input name and balance of customer and 4M


thread an user defined exception if balance less than 1500.
Ans. import java.io.*;
class MyException extends Exception{
MyException(String str) {
super(str); Correct
} logic
} 3M

class AccountDetails { Syntax


public static void main(String a[]) { 1M
try {
BufferedReaderbr = new BufferedReader(new
InputStreamReader(System.in));
String name;
int balance;
System.out.println("Enter name");
name = br.readLine();
System.out.println("Enter balance");
balance = Integer.parseInt(br.readLine());
try {
if(balance<1500) {
throw new MyException("Balance is less");

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

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

} else {
System.out.println("Everything alright");
}
} catch(MyException me) {
System.out.println("Exception caught"+me);
}
} catch(Exception e) {
System.out.println("Exception caught"+e);
}
}
}
1. (B) Attempt any ONE of the following: 1x6=6
(a) Design an applet which display equals size three rectangle one 6M
below the other and fill them with orange, white and green color
respectively.
Ans. import java.awt.*;
importjava.applet.*;
/*
<applet code = DisplayRectangle.class height = 300 width =
300></applet>
*/ Correct
public class DisplayRectangle extends Applet { logic 4M
public void init() {
setBackground(Color.PINK);
}
public void paint(Graphics g) {

g.setColor(Color.ORANGE); Correct
g.fillRect(40,40,40,30); syntax
g.setColor(Color.WHITE); 2M
g.fillRect(40,90,40,30);
g.setColor(Color.GREEN);
g.fillRect(40, 140,40,30);
}
}
OR

import java.awt.*;
importjava.applet.*;

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

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

/*
<applet code = DisplayRectangle.class height = 300 width =
300></applet>
*/
public class DisplayRectangle extends Applet {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
g.fillRect(40,40,40,30);
g.setColor(Color.BLACK);
g.drawRect(40,90,40,30);
g.setColor(Color.GREEN);
g.fillRect(40, 140,40,30);
}
}
(b) What is the multiple inheritance? Write a java program to 6M
implement multiple inheritance.
Ans. Multiple inheritance: is a feature in which a class inherits
characteristics and features from more than one super class or parent
class. Explana
tion with
diagram
2M

Java cannot have more than one super class. Therefore interface is
used to support multiple inheritance in java. Interface specifies what a
class must do but not how it is done.

Eg: interface MyInterface{


int strength=60;
void method1(); Correct
} logic 2M
class MyBaseClass {
String str;
MyBaseClass(String str) { Correct
this.str = str; syntax
} 2M

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

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

public void display() {


System.out.println("Class: "+str);
}
}
public class MyClass extends MyBaseClass implements MyInterface
{
float total;
MyClass(String str, float t) {
super(str);
total = t;
}
public void method1() {
float avg = total/strength;
System.out.println("Avg is "+avg);
}
public static void main(String a[]) {
MyClass c = new MyClass("Fifth Sem",1300.0f);
c.display();
c.method1();
}
}
2. Attempt any TWO of the following: 2x8=16
(a) Define a class person with data member as Aadharno, name, 8M
Panno implement concept of constructor overloading. Accept
data for 5 object and print it.
Ans. import java.io.*;
class Person {
intAadharno; Correct
String name; logic 5M
String Panno;
Person(intAadharno, String name, String Panno) {
this.Aadharno = Aadharno; Syntax
this.name = name; 3M
this.Panno = Panno;
}
Person(intAadharno, String name) {
this.Aadharno = Aadharno;
this.name = name;
Panno = "Not Applicable";

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

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

}
void display() {
System.out.println("Aadharno is :"+Aadharno);
System.out.println("Name is: "+name);
System.out.println("Panno is :"+Panno);
}
public static void main(String ar[]) {
BufferedReaderbr = new
BufferedReader(newInputStreamReader(System.in));
Person p, p1, p2, p3, p4;
int a;
String n, pno;
try {
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
System.out.println("Enter panno");
pno = br.readLine();
p = new Person(a,n,pno);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
System.out.println("Enter panno");
pno = br.readLine();
p1 = new Person(a,n,pno);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
p2 = new Person(a,n);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
p3 = new Person(a,n);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());

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

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

System.out.println("Enter name");
n = br.readLine();
System.out.println("Enter panno");
pno = br.readLine();
p4 = new Person(a,n,pno);
p.display();
p1.display();
p2.display();
p3.display();
p4.display();
} catch(Exception e) {
System.out.println("Exception caught"+e);
}
}
}
(b) What is package? How do we create it? Give the example to 8M
create and to access package.
Ans. Package is a name space that organizes a set of related classes and
interfaces. It also provides access protection and removes name Definitio
collision. n of
Packages can be categorized into two: - built-in and user defined. package
2M
Creation of user defined package:
To create a package a physical folder by the name of the package Creation
should be created in the computer. of
package
Example: we have to create a package myPack, so we create a folder and its
d:\myPack example
The java program is to be written and saved in the folder myPack. 3M
The first line in the java program should be package <name>;
followed by imports and the program logic.
package myPack;
importjava.util.*;
public class Myclass {
public void myMethod() {
System.out.println("Inside package");
}
}

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

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

Access user defined package:


To access a user defined package, we need to import the package in Use of
our program. Once we have done the import we can create the object package
of the class from the package and thus through the object we can and its
access the instance methods. example
3M
import myPack.*;
public class MyClassExample{
public static void main(String a[]) {
Myclass c= new Myclass();
c.myMethod();
}
}
(c) Give the syntax of following methods of graphics class. Explain 8M
their use with suitable program:
(i) drawRoundReel( )
(ii) drawPolygon( )
(iii) drawOval( )
(iv) drawstring( )
Ans. (Note: Solution is given for drawRoundRect() method)
(i) void drawRoundRect( ):
void drawRoundRect(int x, int y, int width, int height, intarcwidth,
intarcheight) 1M each
- draws an outlined round cornered rectangle.int x and y represents for
the top left corner of the rectangle. Width and height represents the syntax
length and breadth of the rectangle. The arcwidth and archeight
represents the horizontal and vertical diameter of the arc at the four
corners.

(ii) voiddrawPolygon( ):void drawPolygon(int x[], int y[], int n)-


draws a polygon with the arrays of x coordinates and y coordinates
and the number of points specified by n
OR
voiddrawPolygon(Polygon p)- draws a polygon defined by the
specified polygon object.
(iii) void drawOval( ): void drawOval(int x, int y, int width, int
height)
- draws an outline of an oval.
(iv) void drawstring( ):void drawstring(String str, int x, int y)

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

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

- draws the string specified using the coordinates specified by x and


y.
1M each
import java.awt.*; for
importjava.applet.*; program
/* OR
<applet code = MyApplet.class height = 300 width = 300></applet> 4M if
*/ one
public class MyApplet extends Applet { program
public void paint(Graphics g) { with all
g.drawRoundRect(40, 40, 40, 30, 10,10); the
int x[] = {40,80,120}; methods
int y[] = {90,100,95};
g.drawPolygon(x,y,3);
g.drawOval(40, 110,40,30);
g.drawString("My Applet",40, 160);
}
}
3. Attempt any FOUR of the following: 4x4=16
(a) Describe following string class method with example: 4M
(i) compareTo( )
(ii) equalsIgnoreCase( )
Ans. (i) compareTo( ):
Syntax: intcompareTo(Object o)
or Each
intcompareTo(String anotherString) descripti
on 1M
There are two variants of this method. First method compares this
String to another Object and second method compares two strings
lexicographically. Each
Eg. String str1 = "Strings are immutable"; syntax
String str2 = "Strings are immutable"; 1M
String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);

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

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

(ii) equalsIgnoreCase( ):
public boolean equalsIgnoreCase(String str)

This method compares the two given strings on the basis of content of
the string irrespective of case of the string.
Example:
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));//true because content an
d case both are same.
System.out.println(s1.equalsIgnoreCase(s3));//true because case is ign
ored.
System.out.println(s1.equalsIgnoreCase(s4));//false because content i
s not same.
(b) Write a program to copy contents of one file to another. Using 4M
byte stream classes.
Ans. class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("input.txt");
FileOutputStream out= new FileOutputStream("output.txt"); Correct
int c=0; logic
try 3M
{
while(c!=-1)
{ Correct
c=in.read(); syntax
out.write(c); 1M
}
System.out.println("File copied to output.txt....");
}
finally
{
if(in!=null)
in.close();
if(out!=null)

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

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

out.close();
}
}
}
(c) Explain method overriding with suitable example. 4M
(Note: Any other example shall be considered)
Ans. Method Overriding in Java:
If subclass (child class) has the same method as declared in the parent Explana
class, it is known as method overriding in java. If subclass provides tion 2M
the specific implementation of the method that has been provided by
one of its parent class, it is known as method overriding.
Method overriding is used for runtime polymorphism.

Example:
class Vehicle{
void run(){System.out.println("Vehicle is running");} Example
} 2M
class Bike2 extends Vehicle{
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}
(d) Enlist any four built in packages in java API with atleast two 4M
class name from each package.
Ans. Inbuilt packages in java:
1. java.lang - language support classes. These are classes that java List (any
compiler itself uses and therefore they are automatically 4) 2M
imported. They include classes for primitive types, strings, math
functions, threads and exceptions Any 2
classes : Thread, String , package
s class
2. java.util – language utility classes such as vectors, hash tables, list :1M
random numbers, date etc each
classes :Date,Collection,Vector

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

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

3. java.io – input/output support classes. They provide facilities for


the input and output of data
classes :FileReader, FileWriter

4. java.awt – set of classes for implementing graphical user


interface. They include classes for windows, buttons, lists,
menus and so on
classes :Button,Label

5. java.net – classes for networking. They include classes for


communicating with local computers as well as with internet
servers
classes :Socket,URL
(e) Write a program to check whether given number is prime or not. 4M
(Note: Any relevant logic shall be considered)
Ans.
import java.io.*;
class PrimeNo Accept
{ No.
public static void main(String args[]) throws IOException from
{ user 1M
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter number: ");
intnum=Integer.parseInt(bin.readLine());
Prime
int flag=0; No.
for(inti=2;i<num;i++) logic
{ 3M
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}}

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

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

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


(a) Write a program to print the following output: 4M
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
(Note: Any relevant logic shall be considered)
Ans. class Sample
{
public static void main(String args[]){ Correct
inti,j,a=1; logic 3M
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++) Correct
{ syntax
System.out.println(a+" "); 1M
}
System.out.println(“\n”);
a++;
}
}
(b) Illustrate with example the use of switch case statement. 4M
(Note: Any other example shall be considered)
Ans. Switch case statement:
1. The switch statement is used to select among multiple
alternatives Explana
2. It uses all primitive datatypes except boolean expression to tion 2M
determine which alternative should be executed.

General form:
switch(expression)
{
case value1:
block 1;
break;
case value2:
block 2;
break;

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

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

.
.
.
default:
default block;
break;
}
statement n;

Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){ Example
case 10: System.out.println("You are in 10");break; 2M
case 20: System.out.println("You are in 20");break;
case 30: System.out.println("You are in 30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
(c) Write a program to create two thread one to print odd number 4M
only and other to print even numbers.
(Note: Any other logic shall be considered)
Ans. class EvenThread extends Thread
{
EvenThread() Correct
{ program
start(); 4M
}
public void run()
{
try
{
for(inti = 0;i <= 10;i+=2)
{
System.out.println("Even Thread : "+i);
Thread.sleep(500);
}

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

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

}
catch (InterruptedExceptione){}
}
}
class OddThread implements Runnable
{
OddThread()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
try
{
for(inti = 1;i <= 10;i+=2)
{
System.out.println("Odd Thread : "+i);
Thread.sleep(1500);
}
}
catch (InterruptedExceptione){}
}
}
class Print
{
public static void main(String args[])
{
new EvenThread();
new OddThread();
}
}
(d) What is the use of try catch and finally statement give example. 4M
Ans.
i. try- Program statements that you want to monitor for exceptions
are contained within a try block. If an exception occurs within the try
block, it is thrown.
Syntax:
try

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

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

{
// block of code to monitor for errors
}
For eg. try Each try
{ 1½M
for(inti = 1;i <= 10;i+=2) ,catch 1
{ ½ M,
System.out.println("Odd Thread : "+i); finally 1
Thread.sleep(1500); M
}
}

ii.catch- Your code can catch this exception (using catch) and handle
it in some rational manner. System-generated exceptions are
automatically thrown by the Java runtime system. A catch block
immediately follows the try block. The catch block too can have one
or more statements that are necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
For eg.
catch (InterruptedExceptione){}

iii.finally: It can be used to handle an exception which is not caught


by any of the previous catch statements. finally block can be used to
handle any statement generated by try block. It may be added
immediately after try or after last catch block.
Syntax:
finally
{
// block of code to be executed before try block ends
}
For eg.
finally{System.out.println("finally block is always executed");}

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

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

4. (B) Attempt any ONE of the following: 1x6=6


(a) What is importance of super and this keyword in inheritance? 6M
Illustrate with suitable example.
(Note: Any appropriate example shall be considered)
Ans. Using inheritance, you can create a general class that defines traits
common to a set of related items. This class can then be inherited by
other, more specific classes, each adding those things that are unique
to it. In the terminology of Java, a class that is inherited is called a Inherita
superclass. The class that does the inheriting is called a subclass. nce
Therefore, a subclass is a specialized version of a superclass. definitio
Whenever a subclass needs to refer to its immediate superclass, it can n 1M
do so by use of the keyword super.

Superhas two general forms. The first calls the super class
constructor. The second is used to access a member of the superclass
that has been hidden by a member of a subclass. Super
super() is used to call base class constructer in derived class. 2M
Super is used to call overridden method of base class or overridden
data or evoked the overridden data in derived class.

E.g.: use of super()


class BoxWeightextends Box
{
BowWeight(int a ,intb,int c ,int d)
{
super(a,b,c) // will call base class constructer Box(int a, int b, int c)
weight=d // will assign value to derived class member weight.
}

E.g.: use of super.


Class Box
{
Box()
{
}
void show()
{
//definition of show
}

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

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

} //end of Box class

Class BoxWeight extends Box


{
BoxWeight()
{
}
void show() // method is overridden in derived
{
Super.show() // will call base class method
}
}

The this Keyword


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

Instance Variable Hiding


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

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

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

(b) Write a single program to implement inheritance and 6M


polymorphism in java.
Ans. class Employee {
String name;
String address;
int number;

Employee(String name, String address, int number) {


System.out.println("Constructing an Employee"); Correct
this.name = name; Logic
this.address = address; 4M
this.number = number;
}

public void mailCheck() {


System.out.println("Mailing a check to " + this.name + " " + Correct
this.address); Syntax
} 2M

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public intgetNumber() {
return number;
}
}

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

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

class Salary extends Employee {


private double salary;
Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}

public void mailCheck() {


System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}

public double getSalary() {


return salary;
}

public void setSalary(double newSalary) {


if(newSalary>= 0.0) {
salary = newSalary;
}
}

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

public class Demo {


public static void main(String [] args) {
Salary s = new Salary("RAM", "Dadar", 3, 3600.00);
Employee e = new Salary("John ", "Thane", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

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

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

5. Attempt any TWO of the following: 2x8=16


(a) What is exception? Why the exception occurred in program? 8M
Explain with suitable example.
Ans. An exception is an event, which occurs during the execution of a
program on an existence of an error, generally a run time error.
If there are some syntactical errors in the program, those can be
caught and debugged by compiler, but if there exist any logical
errors, the program may get terminated at run time.
Exception handling mechanism helps no to terminate the program at Explanati
runtime because of logical error, but it allows the program to take on 4M
some proper action and execute further.
It is achieved by 5 keywords as try, catch, throw, throws and finally.
1) try :
The code which is to be monitored is contained in try block

2) catch :
If there exists any error in try block it is caught in catch block and
action is taken. It works like a method and accepts an argument in the
form, of Exception object.

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

4) throws: It can be used with the method’s declaration which may


have some run time errors.
Example :
public static void main(String args[]) throws IOException

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

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

5) finally: it includes the code which executes irrespective of errors


in try block. A try should have at least one catch or a finally block
associated to complete the syntax.

Example (Program to raise an exception if the passwords do not


match)
import java.io.*;
classPasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
Example
class PassCheck 4M
{
public static void main(String args[]) throws IOException
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("abc123"))
{
System.out.println("Authenticated ");
}
else

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

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

{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
}
}
(b) Write a program to define two thread one to print from 1 to 100 8M
and other to print from 100 to 1. First thread transfer control to
second thread after delay of 500 ms.
Ans. class thread1 extends Thread
{
public void run()
{
int flag=0; Correct
for(inti=1; i<=10;i++) logic
{ 4M
System.out.println("thread1:"+i);
try
{
Thread.sleep(500);
flag=1; Correct
} syntaxes
catch(InterruptedException e) 4M
{}
if (flag==1)
yield();
}
}
}
class thread2 extends Thread
{
public void run()
{
int flag=0;
for(inti=10; i>=1;i--)

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

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

{
System.out.println("thread2:"+i);
try
{
Thread.sleep(500);
flag=1;
}
catch(InterruptedException e)
{}
if (flag==1)
yield();
}
}
}
class test
{
public static void main(String args[])
{
thread1 t1= new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}
(c) How to pass parameter to an applet? Write an applet to accept 8M
Account No and balance in form of parameter and print message
“low balance” if the balance is less than 500.
Ans. Passing parameters to an applet :
For passing parameters in an applet class <param> tag can be
used within <applet> tag.
<param> has two attributes as name and value.
Explana
For example : tion 4M
<applet code=applet1 width=200 height=200>
<param name=”uname” value=”abc”>
</applet>

Attribute name specifies name of the parameter as “uname” in


example and value specifies the value inside uname as “abc”.

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

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

The values of the parameter can be fetched in applet with the help
of getParameter() method as
String username=getParameter(“uname”);

Program :
importjava.awt.*;
importjava.applet.*;
public class applet1 extends Applet Progra
{ m with
String accno=""; correct
int balance=0; logic
public void init() and
{ syntax
accno=getParameter("acno"); 4M
balance=Integer.parseInt(getParameter("bal"));
}
public void paint(Graphics g)
{
if(balance<500)
g.drawString(accno+": Low balance...",100,100);
else
g.drawString(accno+":sufficient balance...",100,100);
}
}
/*<applet code=applet1 width=200 height=200>
<param name="acno" value="1001">
<param name="bal" value="200">
</applet>*/
6. Attempt any FOUR of the following: 4x4=16
(a) What is the use of wrapper classes in Java? Explain float 4M
wrapper with its methods.
Ans. Use :
Java provides several primitive data types. These include int
(integer values), char (character), double (doubles/decimal values),
and byte (single-byte values). Sometimes the primitive data type Use 2M
isn't enough and we may have to work with an integer object.

Wrapper class in java provides the mechanism to convert


primitive into object and object into primitive.

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

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

Float wrapper Class:


Float wrapper class is used to wrap primitive data type float value
in an object.
Methods :
1) floatValue( ) method: It is used to return value of calling
object as float.
2) isInfinite( ) method: True if, value of calling object is
infinite, otherwise false.
3) isNaN( ) method: True if, value of calling object is not a
number, otherwise false. Float
4) floatToIntBits( ) method: It is used to return IEEE Wrapper
compatible single precision bit pattern for n. class
5) hashCode(float value) method: It is used to find hash code with 2
of calling object. methods
6) intBitsToFloat(int bits ) method: It is used to return float 2M
of IEEE compatible single precision bit pattern for n.
7) parseFloat( ) method: It is used to return float of a number
in a string in radix 10.
8) toString(float f ) method: It is used to find the string
equivalent of a calling object.
9) valueOf(String s) method: It is used to return Float object
that has value specified by str.
10) compare(float f1, float f2) method: It is used to compare
values of two numbers. If it returns a negative value, then,
n1<n2. If it returns a positive value, then, n1>n2. If it
returns 0, then both the numbers are equal.
11) compareTo (float f1) method: It is used to check whether
two numbers are equal, or less than or greater than each
other. If the value returned is less than 0 then, calling
number is less than x. If the value returned is greater than 0
then, calling number is greater than x. If value returned is 0,
then both numbers are equal.
12) equals(Object obj) method: It is used to check whether
two objects are equal. It returns true if objects are equal,
otherwise false.
(b) Write a program to accept number from command line and print 4M
square root of the number.
Ans.

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

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

class test1
{ Correct
public static void main(String args[]) logic
{ 2M
intnum;
num= Integer.parseInt(args[0]); Correct
doublesq=Math.sqrt(num); syntax
System.out.println("square root of "+ num +" is +sq); 2M
}}
(c) Write any four methods of File Input stream class give their 4M
syntax.
Ans.
Java File Input Stream class methods:
Method Description
It is used to return the estimated number of
int available()
bytes that can be read from the input stream.
It is used to read the byte of data from the Any
int read() four
input stream.
It is used to read up to b.length bytes of data methods
int read(byte[] b) 1M each
from the input stream.
int read(byte[] b, It is used to read up to len bytes of data from
int off, intlen) the input stream.
It is used to skip over and discards x bytes of
long skip(long x)
data from the input stream.
FileChannelgetCh
It is used to return the unique FileChannel
annel()
object associated with the file input stream.
FileDescriptorget
It is used to return the FileDescriptor object.
FD()
It is used to ensure that the close method is call
protected void
when there is no more reference to the file
finalize()
input stream.
void close() It is used to closes the stream.
(d) Write a applet program to set background with red colour and 4M
fore ground with blue colour.
Ans.
import java.awt.*;
import java.applet.*; Correct
public class applet2 extends Applet logic
{ 2M

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

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

String str="java programming";


public void init()
{
setBackground(Color.red); Correct
setForeground(Color.blue); syntax
} 2M
public void paint(Graphics g)
{
g.drawString("welcome",100,100);
}
}
/*<applet code=applet2 width=200 height=200>
</applet>*/

(e) Describe access control specifiers with example. 4M


Ans. There are 4 types of java access modifiers:
1. private
2. default 4 access
3. protected control
4. public specifier
s 1M
1) private access modifier: each
The private access modifier is accessible only within class.
Example:
class test
{
private int data=40;
private void show()
{
System.out.println("Hello java");
}
}

public class test1{


public static void main(String args[]){
testobj=new test();
System.out.println(obj.data);//Compile Time Error
obj.show();//Compile Time Error
}

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

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

}.
In this example, we have created two classes test and test1. test
class contains private data member and private method. We are
accessing these private members from outside the class, so there is
compile time error

2) default access specifier:


If you don’t specify any access control specifier, it is default, i.e. it
becomes implicit public and it is accessible within the program
anywhere.\
Example :
class test
{
int data=40; //default access
void show() // default access
{
System.out.println("Hello java");
}
}

public class test1{


public static void main(String args[]){
testobj=new test();
System.out.println(obj.data);
obj.show();
}
}

3) protected access specifier:


The protected access specifier is accessible within package and
outside the package but through inheritance only.
Example :
test.java
packagemypack;
public class test
{
protected void show()
{
System.out.println("Hello java");

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

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

}
}
test1.java
importmypack.test;
class test1 extends test
{
public static void main(String args[])
{
test1obj=new test1();
obj.show();
}
}

4) public access specifier:


The public access specifier is accessible everywhere. It has the
widest scope among all other modifiers.
Example :
test.java
packagemypack;
public class test
{
public void show()
{
System.out.println("Hello java");
}
}
test1.java
importmypack.test;
class test1 ///inheritance not required
{
public static void main(String args[])
{
test1obj=new test1();
obj.show();
}
}

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

Important Instructions to examiners:


1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the 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. a) Attempt any THREE of the following: 12
(i) Describe any four features of Java. 4M
(Note: Any four features shall be considered)
Ans. Features of Java:
i. Java is an object oriented language:- It follows all the principles of
object oriented programming namely inheritance, polymorphism
and abstraction. Multiple inheritance is possible with the concept
of interface
ii. Java is both compiled and interpreted:- Most of the programming Any
languages either uses a compiler or an interpreter. Java programs four
are to be compiled to get an intermediate byte code (a .class file) features
and then interpreted making it more secure and platform 1M each
independent.
iii. Java is secure:
 Java does not use pointer.
 Java programs run inside a virtual machine
 Classloader adds security by separating the package for the
classes of the local file system from those that are imported

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

from network sources


 Bytecode Verifier checks the code fragments for illegal code
that can violate access right to objects
 Security Manager determines what resources a class can access
such as reading and writing to the local disk
iv. Robust: Java uses strong memory management. The lack of
pointers avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking
mechanism in java
v. Architecture-neutral: There is no implementation dependent
features e.g. size of primitive types is fixed
vi. Platform independent and Portable: java byte code can be carried
to any platform
vii. Distributed: Distributed applications can be created in java. RMI
and EJB are used for creating distributed applications. We may
access files by calling the methods from any machine on the
internet
viii. Multithreaded: A thread is like a separate program, executing
concurrently. We can write Java programs that deal with many
tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-
media, Web applications etc.
(ii) Describe file output stream class with one example. 4M
Ans. A file output stream is an output stream for writing data to a File.
FileOutputStream class is used to write bytes of data into a file.
Constructor: (Any one) Descript
FileOutputStream(File file) ion 1M
This creates a file output stream to write to the file represented by the
specified File object.
FileOutputStream(String name)
This creates an output file stream to write to the file with the
specified name.

Example:
import java.io.*; Example
class FileoutputstreamExample 3M
{
public static void main(String a[]) throws IOException

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

{
File fin = new File("in.txt");
File fout = new File("out.txt");
FileInputStreamfis = null;
FileOutputStreamfos = null;
try {
fis =new FileInputStream(fin);
fos = new FileOutputStream(fout);
intch;
while((ch=fis.read())!=-1)
{
fos.write(ch);
}
} catch(Exception e)
{
}
finally{
if(fis != null)
{
fis.close();
}
if(fos != null)
{
fos.close();
}
}
}
}
(iii) Enlist all mathematical function and write a program based on 4M
pow( ) function.
Ans. Methods of Math class:
static double abs(double a) -returns absolute value of a double value Any
static float abs(float a) – returns absolute value of float value four List
static int abs(int a)-returns absolute value of an int value of
static long abs(long a)-returns absolute value of a long value methods
static double exp(double a)- returns Euler‟s number e raised to the -
power of a double value function
static double max(double a, double b)- returns greater of two double 2M
values.

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

static int max(int a, int b)- returns greater of two integer values.
static float max(float a, float b)- returns greater of two float values.
static long max(long a, long b)- returns greater of two long values.
static double min(double a, double b)- returns smallest of two double
values.
static int min(int a, int b)- returns smallest of two integer values.
static float min(float a, float b)- returns smallest of two float values.
static long min(long a, long b)- returns smallest of two long values.
static double pow(double a, double b)- returns the value of the first
argument raised to the power of second argument.

pow() example:
import java.io.*;
class PowEg {
double findPow(double a, double b) { Program
double val = java.lang.Math.pow(a,b); 2M
return val;
}
public static void main(String ar[]) {
double a,b, ans = 0.0;
PowEg p = new PowEg();
try {
BufferedReaderbr = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a value");
a = Double.parseDouble(br.readLine());
System.out.println("Enter a value");
b = Double.parseDouble(br.readLine());
ans=p.findPow(a,b);
} catch(Exception e) {
System.out.println("Exception caught"+e);
}
System.out.println("Ans is "+ans);
}
}
(iv) Explain try – catch statement with one example. 4M
Ans. An exception is an event which occurs during the execution of a
program and disrupts the normal execution of the program. When an Explana
exception occurs in a method, it creates an exception object and tion 1M
hands it to the run time system. The object contains information about

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

the exception. The exception can be handled using try-catch block.


The code that may create an exception should be enclosed in a try
block. If an exception occurs within the try block, an exception object
is created of the specific type, and is thrown. That exception is
handled by an exception handler associated with it. To associate an
exception handler with a try block, a catch block is specified after try
block. A try block can have any number of catch.

Example:
import java.io.*;
class ExceptionHandling {
int num1, num2, answer;
void acceptValues() { Example
BufferedReader bin = new BufferedReader(new 3M
InputStreamReader(System.in));
try {
System.out.println("Enter two numbers");
num1 = Integer.parseInt(bin.readLine());
num2 = Integer.parseInt(bin.readLine());
} catch(IOExceptionie) {
System.out.println("Caught IOException"+ie);
} catch(Exception e) {
System.out.println("Caught the exception "+e);
}
}
void doArithmetic() {
acceptValues();
try {
answer = num1/num2;
System.out.println("Answer is: "+answer);
} catch(ArithmeticExceptionae) {
System.out.println("Divide by zero"+ae);
}
}
public static void main(String a[]) {
ExceptionHandling e = new ExceptionHandling();
e.doArithmetic();
}

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

1. b) Attempt any ONE of the following: 6


(i) Explain constructor with its type, Give example of parameterized 6M
constructor.
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 two differences, constructor has the same name as
that of the class and it does not return any value. The types of Definitio
constructors are: n and
1. Default constructor: when the constructor is not defined in the explanat
program, the java compiler creates a constructor. Such a ion of
constructor is called a default constructor. the types
2. Parametrized constructor: Such constructor are defined in the of
construc
program and consists of parameters. Such constructors can be
tors 4M
used to create different objects with data members having
different values.
class Student
{
int roll_no;
String name;
Student(int r, String n) Example
{ 2M
roll_no = r;
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();
}
}
3. No argument constructor- when the defined constructor in the

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

program does not contain any arguments, then it is called no


argument constructor.
(ii) Enlist Build-in packages of java, explain any four in details with 6M
example.
Ans. Package in Java is a mechanism to encapsulate a group of classes, Definitio
sub packages and interfaces. There are two types of packages. n of
package
1. Built in packages 1M
2. User defined packages- are packages defined by user.
Built in packages are part of java API. Some of the built in packages List
in java are: package
java.io-this package contains classes and interfaces for performing s 1M
input and output operations and also serialization.
Eg of classes/interfaces:
BufferedReader, BufferedWriter, Serializable, InputStream,
OutputStream
java.util-contains utility classes/interfaces for implementing data
structures, and other utility class like Date. Any 4
Eg: Vector, Scanner, ArrayList, Date explanat
java.net-this package consists of classes that support networking ion 1M
operations. each
Eg: URL, URLConnection, Socket,ServerSocket
java.awt-this package contains a large number of classes used for
GUI.
Eg: Graphics, Panel, Container
java.applet-this package contains classes/interfaces that are used to
create and use applets
Eg: Applet,AppletContext,AudioClip
java.lang-this package is automatically imported and contains
language support classes like String, Thread,Math

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

2. Attempt any TWO of the following: 16


a) Write a program to implement following inheritance. Refer 8M
Figure No.1

Ans. import java.io.*;


class Bank{
String bank_name;
String address;
void getData(String b, String a){
bank_name = b;
address = a;
}
}
class Customer extends Bank{ Correct
int acc_no; logic 6M
String name;
void input(String b, String a, int no, String n) {
getData(b,a);
acc_no = no; Correct
name=n;} syntax
} 2M

class Passbook extends Customer{


void display() {
System.out.println("Bank name is "+bank_name);
System.out.println("Bank address is "+address);
System.out.println("Account no of customer is "+acc_no);

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

System.out.println("Customer name is "+name);


}
public static void main(String ar[]) {
try {
String b,a,n;
int no;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter bank name");
b = br.readLine();
System.out.println("Enter address");
a = br.readLine();
System.out.println("Enter customer name");
n = br.readLine();
System.out.println("Enter acc no");
no = Integer.parseInt(br.readLine());
Passbook p = new Passbook();
p.input(b,a,no,n);
p.display();
} catch(Exception e) {
System.out.println("Exception caught"+e);}
}
}
b) Write a java program for following Figure No.2 8M

Ans. import java.io.*;


interface Exam {
int sportsmark=20;
}
class Student {
int rollno;
String sname;

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

int m1, m2, m3;


Student(int r, String s, int m1, int m2, int m3) {
rollno = r;
sname=s; Correct
this.m1=m1; logic 6M
this.m2=m2;
this.m3=m3;
}
}
class Result extends Student implements Exam {
Result(int r, String s, int m1, int m2, int m3) {
super(r,s,m1,m2,m3);
} Correct
void display() { syntax
int total = m1+m2+m3; 2M
double per = total/3;
if(per <=80) {
per = per+sportsmark;
} else {
double markstoadd = 100.00-per;
per = per + markstoadd;
}
System.out.println("Roll No "+rollno);
System.out.println("Name "+sname);
System.out.println("Percentage "+per);
}
public static void main(String ar[]){
try {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Student name");
String n = br.readLine();
System.out.println("Enter roll no");
int no = Integer.parseInt(br.readLine());
System.out.println("Enter Mark 1");
int m1 = Integer.parseInt(br.readLine());
System.out.println("Enter mark 2");
int m2 = Integer.parseInt(br.readLine());
System.out.println("Enter mark 3");

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

int m3 = Integer.parseInt(br.readLine());
Result r = new Result(no,n,m1,m2,m3);
r.display();
} catch(Exception e) {
System.out.println("Exception caught"+e);
}
}
}
c) Write an applet program that accepts string as a input using 8M
<param> tag and reverse the string and display it on status
window.
Ans. import java.applet.*;
import java.awt.*;
/*<applet code = Question2c.class height = 400 width = 400>
<param name = "string1" value = "Hello">
</applet>*/
public class Question2c extends Applet { Correct
String str1; logic 6M
public void init() {
str1 = new
StringBuffer(getParameter("string1")).reverse().toString();
} Correct
public void paint(Graphics g) { syntax
showStatus(str1); 2M
}
}
OR
import java.applet.*;
import java.awt.*;
/*<applet code = ReverseStringApplet.class height = 400 width =
400>
<param name = "string1" value = "Hello">
</applet>*/
public class ReverseStringApplet extends Applet {
String str1;
String rev="";
public void init() {
String str = getParameter("string1");
char ch[]=str.toCharArray();

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
}
public void paint(Graphics g) {
showStatus(rev);
}
}
3. Attempt any FOUR of the following: 16
a) State any four methods of wrapper class. 4M
Ans. Four methods of Wrapper classes:
1) valueOf()
2) xxxValue()
3) parseXxx()
4) toString()
Method Use
valueOf() Every wrapper class except Character class
contains a static valueOf() method to create
Wrapper class object for given String. Any
Integer i=Integer.valueOf(“10”); four
xxxValue() xxxValue() methods are used to get the primitive methods
for the given Wrapper Object. Every number type list 1M
Wrapper class( Byte, Short, Integer, Long, Float, each
Double) contains the following 6 methods to get
primitive for the given Wrapper object:
syntax :
public static datatype parseXxx(String s);
1. public byte byteValue()
2. public short shortValue()
3. public int intValue()
4. public long longValue()
5. public float floatValue()
6. public float doubleValue()
Any one method can be described out of 6
parseXxx() parseXxx() methods can be used to convert String
to primitive. Xxx contains data type as follows:
parseInt(String str)
parseFloat(String str)

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

parseLong(Strung str)
parseDouble(String str)
Any one method can be described out of 4
toString() Every Wrapper class contains the following
toString() method to convert primitive to String.
Syntax:
public String toString();
for eg: Integer.toString(5);

b) Write a program to find out whether entered no. is prime or not. 4M


(Note: Any other logic shall be considered)
Ans. import java.util.*;
class prime
{
public static void main(String args[])
{
int flag=0; Correct
Scanner sc=new Scanner(System.in); logic 2M
System.out.println("Enter a number :");
int n=sc.nextInt();
for(int i=2;i<n;i++) Correct
{ syntax
if(n%i==0) 2M
{
flag=1;
break;
}
}
if(flag==0)
System.out.println(n +" is prime");
else
System.out.println(n +" is not prime");
}
}
c) Write a program to copy contents of one file to another file using 4M
character stream classes.
(Note: Any other logic shall be considered)

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

Ans.
import java.io.*;
class FileCopyExample {
public static void main(String[] args) throws IOException
{ Correct
FileReaderfr = new FileReader("input.txt"); logic 2M
FileWriterfw = new FileWriter("output.txt");
int c=0;
while(c!=-1) Correct
{ syntax
c=fr.read(); 2M
fw.write(c);
}
fr.close();
fw.close();
System.out.println("file copied");
}
}
d) Explain Life-cycle of an applet. 4M
Ans. Java applet inherits features from the class Applet. Thus, whenever an
applet is created, it undergoes a series of changes from initialization
to destruction. Various stages of an applet life cycle are depicted in
the figure below:

Diagram
1M

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.

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

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
} Explana
tion 3M
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 stop()
{
//Action to be performed
}

Dead State: An applet is in dead state when it has been removed


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

It's general form is:


public void destroy( )
{
//Action to be performed
}

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

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

the graphics class. To use The graphics, it imports the package


java.awt.Graphics
e) Compare between string and string buffer class. 4M
Ans. Sr. String String buffer class
No.
1 String is a major class StringBuffer is a peer class of
String
2 The length of the String The length of the StringBuffer
object is fixed. object is flexible.(can be
changed)
3 String object is StringBuffer object is mutable. Any
immutable. four
4 It is slower during It is faster during concatenation. points
concatenation. 1M each
5 String object cannot be StringBuffer object contents can
modified. be modified.
6 String object can be StringBuffer object needs
created without calling a constructor to initialize created
constructor of String object.
class. Eg: StringBuffer str=new
Eg: String str=”abc”; StringBuffer(“abc”);

4. a) Attempt any THREE of the following: 12


(i) Explain robust and secure feature of java. 4M
Ans. Robust: Robust simply means strong. Java is robust because:
 It uses strong memory management.
 It is portable across many operating systems
 There is a lack of pointers that avoids security problems. Robust
 There is automatic garbage collection in java which runs on the 2M
Java Virtual Machine to get rid of objects which are not being
used by a Java application anymore.
 There are exception handling and the type checking mechanism in
Java. All these points make Java robust.

Secure: Unlike C, there are no pointers in Java. The basic use of


Pointers is to refer to the actual memory location where the value is Secure
stored, and hence enabling the programmer to further modify the 2M

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

actual value.

As java does not consist of pointers, there is no way one can refer to
the actual value, and hence the value remains protected or unaltered.

Due to these reasons, Java is known as a Secure language.

(ii) Explain the following terms w.r.t exception handling: 4M


(1) Try-catch
(2) Throw
(3) Throws
(4) Finally
Ans. (1) Try-catch: Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs within
the try block, it is thrown. 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: Each
try term 1M
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
(2) 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

(3) Throws: This keyword can be used along with method


declaration with any exception so that each statement from that
method is monitored for the errors and if there is any errors, then the
system shows its own error message. Throws does not require
separate try catch block to monitor the errors.

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

Syntax:
datatype method() throws ExceptionType
{
//method body;
}
Example :
public static void main(String args[]) throws IOException

(4) 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
}
(iii) Explain the use of ternary (?:) operator with example. 4M
Ans. Java ternary operator is the only conditional operator that takes three
operands. Java ternary operator is a one liner replacement for if-then-
else statement and used a lot in java programming.
The first operand in java ternary operator should be a boolean or a Explana
statement with boolean result. If the first operand is true then java tion 2M
ternary operator returns second operand else it returns third operand.
Syntax of java ternary operator is:
result = testStatement ? value1:value2;
If testStatement is true then value1 is assigned to result variable else
value2 is assigned to result variable. java ternary operator can be used
to avoid if-then-else and switch case statements. This way we can
reduce the number of lines of code in java program.
Example:
class test
{
public static void main(String args[]) Example
{ 2M
int a=5;
String result=””;
result = (a>0 ?”positive” : ”negative”);
System.out.println(result);

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

}
}
(iv) Explain following thread methods with suitable example. 4M
(1) setpriority (int max)
(2) getpriority( )
Ans. (1) setpriority (int max):
The setPriority() method of thread class is used to change the
thread's priority. Every thread has a priority which is represented by
the integer number between 1 to 10.
Thread class provides 3 constant properties:
1. public static int MIN_PRIORITY: It is the minimum priority of
a thread. The value of it is 1.
2. public static int NORM_PRIORITY: It is the normal priority of
setPriori
a thread. The value of it is 5.
ty (int
3. public static int MAX_PRIORITY: It is the maximum priority max)
of a thread. The value of it is 10. 2M
We can also set the priority of thread between 1 to 10. This priority is
known as custom priority or user defined priority.
Syntax:
public final void setPriority(int a)
(2) getpriority( ):
The getPriority() method of thread class is used to check the priority
of the thread. When we create a thread, it has some priority assigned
to it. Priority of thread can either be assigned by the JVM or by the
getPriori
programmer explicitly while creating the thread.
ty ( ) 2M
The thread's priority is in the range of 1 to 10. The default priority of
a thread is 5.

Syntax:
public final int getPriority()

Example:
public class PriorityExample extends Thread
{
public void run()
{
System.out.println("Priority of thread is: "+Thread.currentThread().g

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

etPriority());
}
public static void main(String args[])
{
PriorityExample t1=new PriorityExample ();
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
}
}
4. b) Attempt any ONE of the following: 6
(i) Write a program to generate following output using drawLine( ) 6M
method. Refer Figure No.3

Ans. import java.awt.*;


import java.applet.*;
public class triangle extends Applet Correct
{ logic 2M
public void paint(Graphics g)
{
g.drawLine(35,10,50,100); Use of
g.drawLine(25,100,50,100); drawLin
g.drawLine(25,100,35,10); e( ) 3M
}
} Applet
/*<applet code=triangle width=100 height=100> tag 1M
</applet>*/
(ii) Explain in detail garbage collection mechanism in java. 6M
Ans. Java garbage collection is the process by which Java programs
perform automatic memory management. Java programs compile to
bytecode that can be run on a Java Virtual Machine. When Java
programs run on the JVM, objects are created on the heap, which is a Need
portion of memory dedicated to the program. Eventually, some 2M
objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory. Java garbage
collection is an automatic process.

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

In C/C++, programmer is responsible for both creation and


destruction of objects. Usually programmer neglects destruction of
useless objects. Due to this negligence, at certain point, for creation Working
of new objects, sufficient memory may not be available and entire 3M
program will terminate abnormally causing OutOfMemoryErrors.
But in Java, the programmer need not to care for all those objects
which are no longer in use. Garbage collector destroys these objects.
Main objective of Garbage Collector is to free heap memory by Finalize
destroying unreachableobjects. ( ) 1M
Just before destroying an object, Garbage Collector
calls finalize() method on the object to perform cleanup activities.
Once finalize() method completes, Garbage Collector destroys that
object.

Syntax :
protected void finalize() throws Throwable
{
//code ;
}
Based on our requirement, we can override finalize() method for
perform our cleanup activities like closing connection from database.
5. Attempt any TWO of the following: 16
a) How synchronization is achieved in multi threading? Explain 8M
with suitable example.
Ans. Synchronization: When two or more threads need access to a shared
resource, they need some way to ensure that the resource will be used
by only one thread at a time. The process by which this is achieved is Descript
called synchronization. ion 3M
Synchronization is used when we want to maintain consistency if
multiple threads require an access to an object.

Example:
class Callme
{
void call(String msg) Example
{ 5M
System.out.print("[" +msg);
try
{

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
System.out.print("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callmetarg,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target)
{
target.call(msg);
}
}
}

class Synch
{
public static void main(String args[])
{
Callme target=new Callme();
Caller ob1=new Caller(target,"Hello");
Caller ob2=new Caller(target,"Synchronized");
try
{

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

ob1.t.join();
ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}
b) Write a program to create user defined exception “Minimum 8M
Balance” if the account balance is less than Rs.1000/-.
Ans. import java.io.*;
class MinimumBalance extends Exception
{ Creation
MinimumBalance(String s) of user
{ defined
super(s); exceptio
} n
} 4M
class Minbal
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); Throw
String name; and
int bal; Catch
void getdata() throws MinimumBalance Exceptio
{ n
try 4M
{
System.out.println("Enter name");
name=br.readLine();
System.out.println("Enter Balance");
bal = Integer.parseInt(br.readLine());
if(bal<10000)
{
throw new MinimumBalance("Account balance is less than Minimum
Balance");
}
else

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

{
System.out.println("Successfully received data ");
}
}
catch(Exception ex)
{
System.out.println("Exception occured: "+ex);
}
}
public static void main(String are[])
{
Minbal m = new Minbal();
try
{
m.getdata();
}
catch(Exception e)
{}
}
}
c) Write an applet program to draw a rectangle filled with different 8M
colors randomly on the applet window.
Ans. import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*; Creating
import java.lang.Math; applet
import java.util.Random; for
drawing
public class rectangle extends Applet { rectangl
public void init() e 5M
{
// set size
setSize(400, 400);
repaint(); Logic
} for
// paint the applet random
public void paint(Graphics g) color
{ filling
// set Color for rectangle 3M

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

Random rand = new Random();


int red, green, blue;
red = rand.nextInt(256);
green = rand.nextInt(256);
blue = rand.nextInt(256);
g.setColor(new Color(red, green, blue));
// draw a rectangle
g.fillRect(100, 100, 200, 200);
}
}
6. Attempt any FOUR of the following: 16
a) How command line argument passed to the java program, 4M
explain with suitable example.
Ans. Command line arguments is a methodology which user will give
inputs through the console using commands. Command Line
Argument is information passed to the program when you run the Descript
program. The passed information is stored as a string array in the ion 2M
main method. Later, you can use the command line arguments in your
program.
Example While running a class Demo, you can specify command line
arguments as
java Demo arg1 arg2 arg3 …

Example
class Demo{
public static void main(String b[]){
System.out.println("Argument one = "+b[0]); Example
System.out.println("Argument two = "+b[1]); 2M
}
}

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

b) Give the difference between Buffered Reader and Buffered 4M


Writer class.
Ans.

Sr. Buffered Reader Buffered Writer


No.
1 It extends from the reader It extends from the writer class. Any
class. four
2 Its key constructor Its key constructor arguments differen
arguments are Reader. are Writer ces 1M
3 It provides the read() and It provides the close(), flush(), each
readLine() methods. newLine(), and write()
methods.
4 It implements the mark() It does not implement the
and reset() methods. mark() and reset() methods.

c) Write an applet program for each of the following graphics 4M


method:
(i) drawOval ( )
(ii) drawLine( )
Ans. import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class DrawOval extends Applet{
public void paint(Graphics g){

setForeground(Color.red);
g.drawOval(10,10,50,100);
}
} drawOv
/* al
<applet code="DrawOval.class" width=500 height=500> Program
</applet> 2M
*/
Program for DrawLine: drawLin
/* e
<applet code="DrawLine.class" width=200 height=200> Program
</applet> 2M

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

*/
import java.applet.Applet;
import java.awt.Graphics;
public class DrawLine extends Applet{
public void paint(Graphics g){
g.drawLine(10,10,50,50);
g.drawLine(10,50,10,100);
g.drawLine(10,10,50,10);
}
}

d) Design a package containing a class which defines a method to 4M


find area of circle. Import it in java application to calculate area
of circle.
Ans.
File 1:
package pack; Creating
public class A_circle user
{ defined
public void areaofcircle(int r) package
{ for area
System.out.println(3.14*r*r); calculati
} on 2M
}
Using
File 2: user
import pack.A_circle; defined
import java.io.*; package
class aoc 2M
{
public static void main(String are[])
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int r;
try
{
System.out.println("Enter a radius of circle");
r = Integer.parseInt(br.readLine());

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

WINTER – 2019 EXAMINATION


MODEL ANSWER
Subject: Java Programming Subject Code: 17515

A_circle c = new A_circle();


c.areaofcircle(r);
}
catch(Exception ex)
{}
}
}
e) Write a program to find out sum of even and odd numbers. Use 4M
suitable range.
Ans. class sum
{
public static void main(String are[])
{
int i,j,osum=0,esum=0;
for(i=0;i<=10;i++)
{
if((i%2)==0) Logic
{ for
esum=esum+i; computi
} ng sum
} of even
for(j=0;j<=10;j++) number
{ and odd
if((j%2)==1) numbers
{ 2M
osum=osum+j; respectiv
} ely
}
System.out.println("Sum of odd number is " + osum);
System.out.println("Sum of even number is " + esum);
}
}

Page 28 / 28

You might also like