Java Sample Papers With Answers
Java Sample Papers With Answers
(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.
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.
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)
Example1
class Test
int a;
int b;
this.a = a;
this.b = b;
void display()
object.display();
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
class Test {
void display()
this.show();
void show() {
t1.display();
( OR )
class Concats
String s3=s1.concat(s2);
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
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
int c=0;
try
while(c!=-1)
c=in.read();
out.write(c);
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)
code.
independently. independently.
other servers on
network
such as C or C++.
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
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
Java defines two types of streams: based on the datatype on which they operate
:
Example:
class A {
void callme() {
class B extends A {
// override callme()
void callme() {
class C extends A {
// override callme()
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
void callme() {
class Dispatch {
r = a; // r refers to an A object
r = b; // r refers to a B object
r = c; // r refers to a C object
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)
Example :
// DEPARTMENT is a constant
salary = 1000;
Output:
(ii)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.
syntax -
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
For example
class one
int v1=10;
void method1()
void method2()
System.out.println("v1="+v1);
class singleinherit
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
Class Result
class student
String name;
int roll_no,marks;
try
name=d.readLine();
roll_no=Integer.parseInt(d.readLine());
marks=Integer.parseInt(d.readLine());
catch(Exception e)
System.out.println(" ");
System.out.println("name="+name);
System.out.println("roll no="+roll_no);
System.out.println("marks1="+marks);
int total;
super.getdata();
total=sport_wt+super.marks;
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
System.out.println("total marks="+total);
r.get_total();
r.display();
Output:
abc
11
200
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
name=abc
roll no=11
marks1=200
total marks=205
{ (Note: Any
other logic can
int n, reverse = 0; be considered
try
n=Integer.parseInt(d.readLine());
while(n != 0)
n = n/10;
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
catch(Exception e)
Output:
123
{
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
{
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>
*/
Set has various methods to add, remove clear, size, etc to enhance the
usage of this interface
A list can contain duplicate elements whereas Set contains unique elements
only.
For eg.
import java.util.*;
hash_Set.add("abc");
hash_Set.add("xyz");
hash_Set.add("abc");
hash_Set.add("java");
hash_Set.add("subject");
System.out.println(hash_Set);
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Output:
setForeground(Color.red);
g.drawArc(10,10,50,100,10,45);
g.fillArc(100,10,100,100,0,90);
}
}
Output:
Types of Array
Syntax:
Initialization
array_name[row_index][column_index] = value;
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 } };
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.
(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: 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.
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
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( )
(a) Write a java program to copy the content of the file “file1.txt” into new file 8M
“file2.txt”.
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
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)
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
}
}
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
(b) With syntax and example explain try & catch statement. 4M
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");
}}}
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
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
}
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 [],int n, int m) Read m bytes into b starting from nth byte
long skip(long n bytes) Skips over n bytes from the input stream and return
the number of bytes actually ignored.
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(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
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
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.
}
}
}
}
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
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;
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
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
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.
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))
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
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
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
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
<=- 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 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
2M for
diagram
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 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
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
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
}
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
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
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.
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.
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
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
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
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
}
}
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
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
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
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
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.
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.
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.
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
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);
}
}
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
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
}
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
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
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
1M for
Source Code Byte Code diagram
Process of Compilation
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
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.
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
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
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
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");
}
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
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
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){}
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
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.
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
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
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
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
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
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
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>
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.
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
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
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
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();
}
}
Page 32 / 32
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 1 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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)
{
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)
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)
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)
Page 6 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 7 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 8 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 9 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 10 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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)
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)
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);
Page 13 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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
Page 14 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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)
Page 16 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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.
Page 17 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Syntax:
datatype method() throws ExceptionType
{
//method body;
}
Example :
public static void main(String args[]) throws IOException
Page 18 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
}
}
(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)
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
Page 20 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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)
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)
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)
{
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)
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)
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)
*/
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);
}
}
Page 27 / 28
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 28 / 28