Winter - 14 EXAMINATION: Important Instructions To Examiners
Winter - 14 EXAMINATION: Important Instructions To Examiners
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 1/ 27
Q.1.
1) Platform independent
Java programs are platform independent and portable. That is they can be easily
moved from one computer system to another. Changes in operating systems,
processors, system resources will not force any change in java programs. Java
compilers generate byte code instructions that can be implemented on any machine as
well as the size of primitive data type is machine independent. In this sense, Java
programs are platform independent.
Java is a two staged system. It combines both approaches. First java compiler
translates source code into byte code instructions. In the second stage java interpreter
generates machine code that can be directly executed by machine. Thus java is both
compiled and interpreted language.
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 2/ 27
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its
data can be used to recreate the object in memory.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types such as writeObject() method. This method serializes an Object and sends it to
the output stream. Similarly, the ObjectInputStream class contains method for
deserializing an object as readObject(). This method retrieves the next Object out of
the stream and deserializes it. The return value is Object, so you will need to cast it to
its appropriate data type.
For a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient.
1) min() :
Syntax: static int min(int a, int b)
Use: This method returns the smaller of two int values.
2) max() :
Syntax: static int max(int a, int b)
Use: This method returns the greater of two int values.
3) sqrt()
Syntax: static double sqrt(double a)
Use : This method returns the correctly rounded positive square root of a double
value.
4) pow() :
Syntax: static double pow(double a, double b)
Use : This method returns the value of the first argument raised to the power of the
second argument.
5) exp()
Syntax: static double exp(double a)
Use : This method returns Euler's number e raised to the power of a double value.
6) round() :
Syntax: static int round(float a)
Use : This method returns the closest int to the argument.
7) abs()
Syntax: static int abs(int a)
Use : This method returns the absolute value of an int value.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 3/ 27
(4M- for any 4 points of differences, 1M each - for any 2 methods of Vector class)
Array Vector
Array can accommodate fixed Vectors can accommodate unknown
number of elements number of elements
Arrays can hold primitive data
Vectors can hold only objects.
type & objects
All elements of array should be of
the same data type. i.e. it can The objects in a vector need not have
contain only homogeneous to be homogeneous.
elements.
Syntax :
Syntax:
Datatype[] arraname= new
Vector objectname= new Vector();
datatype[size];
For accessing elements of an
Vector class provides different
array no special methods are
methods for accessing and managing
available as it is not a class , but
Vector elements.
derived type.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 4/ 27
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 5/ 27
Eg :
class Rect
{
int length, breadth;
Rect() //constructor
{
length=4;
breadth=5;
}
public static void main(String args[])
{
Rect r = new Rect();
System.out.println(Area : +(r.length*r.breadth));
}
}
Output :
Area : 20
Parameterized constructor :
When constructor method is defined with parameters inside it, different value sets can be
provided to different constructor with the same name.
Example
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
System.out.println(Area : +(r.length*r.breadth));
System.out.println(Area : +(r1.length*r1.breadth));
}
}
Output :
Area : 20
Area : 42
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 6/ 27
Example :
abstract class A
{
abstract void disp();
void show()
{
System.out.println(show method is not abstract);
}
}
class B extends A
{
void disp()
{
System.out.println(inside class B);
}
}
class test
{
public static void main(String args[])
{
B b = new B();
b.disp();
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 7/ 27
b.show();
}
}
b) What is interface? How it is different from class? With suitable program explain the use
of interface.
(2M what is interface, 3M 3 points of differences between interface and class, 3M
example)
Interface:
Java does not support multiple inheritances with only classes. Java provides an alternate
approach known as interface to support concept of multiple inheritance.
An interface is similar to class which can define only abstract methods and final variables.
Difference between Interface and class
Class Interface
A Class is a full body entity with members, An Interface is just a set of definition that you
methods along with their definition and must implement in your Class inheriting that
implementation. Interface
A Class has both definition and an Interface has only definition. That is, it
implementation of a method contains only abstract methods.
A Class can be instantiated. An Interface cannot be instantiated
A sub class can be extended from super You can create an instance of an Object of a
class with extends. class that implements the Interface with
implements
Example:
interface sports
{
int sport_wt=5;
public void disp();
}
class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 8/ 27
Output :
D:\>java result
Roll no : 101
Name : abc
sub1 : 75
sub2 : 75
sport_wt : 5
total : 155
c) Design an applet which displays three circle one below the other and fill them red, green
and yellow color respectively.( 3M- correct logic, 2M correct use of class, packages and
<applet> tag , 3M correct syntaxes)
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g) Output :
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}}
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 9/ 27
1. indexOf():
int indexOf(int ch): Returns the index within this string of the first occurrence of the
specified character.
int indexOf(int ch, int fromIndex): Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified index.
int indexOf(String str): Returns the index within this string of the first occurrence of the
specified substring.
int indexOf(String str, int fromIndex): Returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
2. charAt():
char charAt(int index): Returns the char value at the specified index.
3. substring():
String substring(int beginIndex): Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex): Returns a new string that is a substring of
this string. The substring begins at the specified beginIndex and extends to the character
at index endIndex - 1
4. replace():
String replace(char oldChar, char newChar): Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.
import java.io.*;
class SumOfDigits
{
public static void main(String args[])
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n;
try
{
System.out.println("Enter the number");
n = Integer.parseInt(b.readLine());
int sum = 0, n1;
while (n > 0)
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 10/ 27
{
n1 = n%10;
n = n/10;
sum = sum+n1;
}
System.out.println("The sum of the digits of the number is :"+sum);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Or
class SumOfDigits
{
public static void main(String args[])
{
int n = 1234; //Student may have assumed any other number
int sum = 0, n1;
while (n > 0)
{
n1 = n%10;
n = n/10;
sum = sum+n1;
}
System.out.println("The sum of the digits of the number is :"+sum);
}
}
c) What is use of stream classes? Write any two methods FileReader class.
(2 marks for use of stream class, 2 marks for any two methods of FilReader class.)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 11/ 27
Applets are small applications that are accessed on an Internet server, transported over
the Internet, automatically installed, and run as part of a web document. The applet states
include:
Born or initialization state
Running state
Idle state
Dead or destroyed state
Initialization state: Applet enters the initialization state when it is first loaded. This is done
by calling the init() method of Applet class. At this stage the following can be done:
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colors
Initialization happens only once in the life time of an applet.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 12/ 27
e) What is final variable and methods? How it is different from abstract method?
(1 mark for explanation of final variable, 1 mark for explanation of final method. 2
marks for difference)
All variable and methods can be overridden by default in subclass. In order to prevent
this, the final modifier is used.
Final modifier can be used with variable, method or class.
final variable: the value of a final variable cannot be changed. final variable behaves like
class variables and they do not take any space on individual objects of the class.
Eg of declaring final variable: final int size = 100;
final method: making a method final ensures that the functionality defined in this method
will never be altered in any way, ie a final method cannot be overridden.
Eg of declaring a final method: final void findAverage() {
//implementation
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 13/ 27
Q.4.
a) Attempt any three of following:
a. What do mean by typecasting? When it is needed?
(Explanation of type casting with types 2 marks, need 1 mark, 1 mark for
program or code snippet)
The process of converting one data type to another is called casting or type casting. If
the two types are compatible, then java will perform the conversion automatically. It
is possible to assign an int value to long variable. However if the two types of
variables are not compatible, the type conversions are not implicitly allowed, hence
the need for type casting.
Eg: int m = 50;
byte n = (byte) m;
long count = (long) m;
Type casting is of two types: narrowing, widening.
The process of assigning a smaller type to a larger one is known as widening and the
process of assigning a larger type into a smaller one is called narrowing.
Casting is necessary when a value of one type is to be assigned to a different type of
variable. It may also be needed when a method returns a type different than the one
we require. Generic type casting helps in the retrieval of elements from a collection as
each element in a collection is considered to be an object.
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 14/ 27
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 15/ 27
3. A thread can be made to wait until a particular event occur using the wait() method,
which can be run again using the notify( ) method.
Blocked state
A thread is said to be in blocked state if it is prevented from entering into the runnable
state and so the running state.
The thread enters the blocked state when it is suspended, made to sleep or wait.
A blocked thread can enter into runnable state at any time and can resume execution.
Dead State
The running thread ends its life when it has completed executing the run() method
which is called natural dead.
The thread can also be killed at any stage by using the stop( ) method.
class FibonocciSeries
{
public static void main(String args[])
{
int num1 = 1; int num2 = 1;
System.out.println(num1);
while (num2< 100)
{
System.out.println(num2);
num2 = num1+num2;
num1 = num2-num1;
}
}
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 16/ 27
(1 mark each for each method example with syntax, 2 marks for program.
Students may write different program for each method or may include all
methods in one program.)
Eg.
import java.applet.*;
import java.awt.*;
/*
<applet code = DrawGraphics.class height = 500 width = 400></applet>
*/
public class DrawGraphics extends Applet
{
public void paint(Graphics g)
{
int x[] = {10, 170, 80};
int y[] = {20, 40, 140};
int n = 3;
g.drawPolygon(x, y, n);
g.drawRect(10, 150,100, 80);
g.drawOval(10, 250, 100, 80);
g.fillOval(10, 350, 100, 80);
}
}
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 17/ 27
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 18/ 27
b) What are different types of error? What is use of throw, throws and finally Statement?
[Type of Errors & explanation 2-marks, throw, throws & finally 2-mark each]
Errors are broadly classified into two categories:-
1. Compile time errors
2. Runtime errors
Compile time errors: All syntax errors will be detected and displayed by java
compiler and therefore these errors are known as compile time errors.
The most of common problems are:
Missing semicolon
Missing (or mismatch of) bracket in classes & methods
Misspelling of identifiers & keywords
Missing double quotes in string
Use of undeclared variables.
Bad references to objects.
Runtime errors: Sometimes a program may compile successfully creating the .class
file but may not run properly. Such programs may produce wrong results due to wrong
logic or may terminate due to errors such as stack overflow. When such errors are
encountered java typically generates an error message and aborts the program.
The most common run-time errors are:
Dividing an integer by zero
Accessing an element that is out of bounds of an array
Trying to store value into an array of an incompatible class or type
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 19/ 27
throw: If your program needs to throw an exception explicitly, it can be done using throw
statement. General form of throw statement is:
throw new Throwable subclass;
throw statement is mainly used in case there is user defined exception raised. Throwable
instance must be an object of the type Throwable or a subclass of Throwable.
The flow of exception stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception. If it does find a match, control is
transferred to that statement. If not matching catch is found, then the default exception
handler halts the program and prints the built in error message.
throws: If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that exception.
You do this by including a throws clause in the methods declaration. A throws clause
lists the types of exception that a method might throw.
General form of method declaration that includes throws clause
Type method-name (parameter list) throws exception list
{
// body of method
}
Here exception list can be separated by a comma.
finally: It can be used to handle an exception which is not caught by any of the
previous catch statements.
finally block can be used to handle any statement generated by try block. It may be added
immediately after try or after last catch block.
Syntax
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 20/ 27
c) State the use of Font class. Write syntax to create an object of Font class. Describe any
3 methods of Font class with their syntax and example of each.
Syntax to create an object of Font class: To select a new font, you must first construct a Font object
that describes that font.
Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
fontName specifies the name of the desired font. The name can be specified using either the logical or
face name. All Java environments will support the following fonts: Dialog, DialogInput, Sans Serif,
Serif, Monospaced, and Symbol. Dialog is the font used by once systems dialog boxes. Dialog is also
the default if you dont explicitly set a font. You can also use any other fonts supported by particular
environment, but be carefulthese other fonts may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR them together. For example,
Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont( ), which is defined by
Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 21/ 27
import java.applet.*;
import java.awt.*;
/*<applet code="FontD" width=350 height=60> </applet> */
public class FontD extends Applet {
Font f, f1;
String s="";
String msg="";
public void init()
{
f=new Font("Dialog", Font.BOLD,30);
s="Java Programming";
setFont(f);
msg="Is Language";
int a=f.getSize();
String b=f.getFontName();
int d=f.getStyle();
System.out.println("String Information: Size"+a);
System.out.println("Name:"+b);
System.out.println("Style:"+d);
}
public void paint(Graphics g) {
if(f.isBold()==true)
g.drawString(s,50,50);
else
g.drawString("String is not bold",400,400);
g.drawString(s,50,50);
g.drawString(msg,100,100);}}
Output:
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 22/ 27
Program-2:
A program to make use of Font class methods. To displays the name, family, size, and style of the
currently selected font:
import java.applet.*;
import java.awt.*;
/*<applet code="FontInfo" width=350 height=60> </applet>*/
public class FontInfo extends Applet {
public void paint(Graphics g) {
Font f = g.getFont();
String fontName = f.getName();
String fontFamily = f.getFamily();
int fontSize = f.getSize();
int fontStyle = f.getStyle();
String msg = "Family: " + fontName;
msg += ", Font: " + fontFamily;
msg += ", Size: " + fontSize + ", Style: ";
if((fontStyle & Font.BOLD) == Font.BOLD)
msg += "Bold ";
if((fontStyle & Font.ITALIC) == Font.ITALIC)
msg += "Italic ";
if((fontStyle & Font.PLAIN) == Font.PLAIN)
msg += "Plain ";
g.drawString(msg, 4, 16);}}
Output:
Class:Salary
Disp_sal(),hra
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 23/ 27
void gross_sal();
}
class Employee
{
String name;
float basic_sal;
Employee(String n, float b)
{
name=n;
basic_sal=b;
}
void display()
{
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+basic_sal);
}
}
class salary extends Employee implements Gross
{
float hra;
salary(String n, float b, float h)
{
super(n,b);
hra=h;
}
void disp()
{
display();
System.out.println("HRA of Employee="+hra);
}
public void gross_sal()
{
double gross_sal=basic_sal+ta+hra;
System.out.println("TA of Employee="+ta);
System.out.println("DA of Employee="+da);
System.out.println("Gross Salary of Employee="+gross_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
salary s=new salary("ABC",6000,4000);
s.disp();
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 24/ 27
s.gross_sal();
}
}
add()
1
Adds an object to the collection
clear()
2
Removes all objects from the collection
contains()
3
Returns true if a specified object is an element within the collection
isEmpty()
4
Returns true if the collection has no elements
iterator()
5 Returns an Iterator object for the collection which may be used to retrieve
an object
remove()
6
Removes a specified object from the collection
size()
7
Returns the number of elements in the collection
MAHARASHTRA STATEBOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 25/ 27
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 26/ 27
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries from Application are not restricted from using
other language such as C or C++ libraries from other language
Creating Packages: First declare name of package using package keyword followed by
package name. This must be first statement in a java source file. Here is an example:
package firstPackage; //package declaration
Winter 14 EXAMINATION
Subject Code: 17515 Model Answer Page 27/ 27
.class must be located in a directory that has same name as the package, & this directory
should be a subdirectory of the directory where classes that will import package are located.
Creating package involves following steps:
1. Declare the package at beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package & declare it public
3. Create a subdirectory under directory where main source files are stored
4. Store listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory
Case is significant & therefore subdirectory name must match package name exactly. Java
supports the concept of package hierarchy. This is done by specifying multiple names in a
package statement, separated by dots. Example: package firstPackage.secondPackage;
This approach allows us to group related classes into a package & then group related
packages into larger package. To store this package in subdirectory named
firstPackage/secondPackage.
A java package file can have more than one class definition. in such cases only one of the
classes may be declared public & that class name with .java extension is the source file name.
When a source file with more than one class definition is complied, java creates independent
.class files for these classes.
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 1/ 27
Q.1.
Byte Code
Source code
process of compilation
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 2/ 27
Byte code: Bytecode is the compiled format for Java programs. Once a
Java program has been converted to bytecode, it can be transferred across a
network and executed by Java Virtual Machine (JVM). A Bytecode file
generally has a .class extension.
b) Write any two methods of file and file input stream class each.
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 3/ 27
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 4/ 27
a) Define a class employee with data members empid, name and salary.
Accept data for five objects using Array of objects and print it.
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 5/ 27
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(Name : " + name);
System.out.println(Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[5];
for(inti=0; i<5; i++)
{
e[i] = new employee();
e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<5; i++)
e[i].show();
}
}
(Note: Any relevant logic can be considered)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 6/ 27
Example :
Interface: Sports Class: test
disp( )
Code :
interface sports
{ Class: result
int sport_wt=5;
public void disp(); disp() which displays all
} details of student along with
total including sport_wt.
class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
result(int r, String nm, int m11,int m12)
{
super(r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 7/ 27
{
result r= new result(101,"abc",75,75);
r.disp();
}
}
Wrapper Class:
Objects like vector cannot handle primitive data types like int, float, long
char and double. Wrapper classes are used to convert primitive data types
into object types. Wrapper classes are contained in the java.lang package.
The some of the wrapper classes are:
Simple type Wrapper class
boolean Boolean
int Integer
char Character
float Float
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 8/ 27
1) drawstring( )
Displaying String:
drawString() method is used to display the string in an applet window
Syntax:
voiddrawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example:
g.drawString(WELCOME, 10, 10);
2) drawRect( )
Drawing Rectangle:
The drawRect() method display an outlined rectangle. The general forms
of this method is :
void drawRect(inttop,intlept,intwidth,int height)
The upper-left corner of the Rectangle is at top and left. The dimension of
the Rectangle is specified by width and height.
Example:
g.drawRect(10,10,60,50);
3) drawOval( )
Drawing Ellipses and circles:
To draw an Ellipses or circles used drawOval() method can be used. The
general form of this method is:
Syntax:
voiddrawOval(int top, int left, int width, int height)
the ellipse is drawn within a bounding rectangle whose upper-left corner is
specified by top and left and whose width and height are specified by width
and height to draw a circle or filled circle, specify the same width and
height the following program draws several ellipses and circle.
Example:
g.drawOval(10,10,50,50);
4) drawArc( )
Drawing Arc:
It is used to draw arc
Syntax:
voiddrawArc(int x, int y, int w, int h, intstart_angle, intsweep_angle);
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 9/ 27
wherex, 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);
c) What is package? State any four system packages along with their use?
How to add class to a user defined packages?
(package 2 M, Four packages and their use 1 M each, how to add class
to package 2 M)
Package: Java provides a mechanism for partitioning the class namespace into
more manageable parts. This mechanism is the package. The package is both
naming and visibility controlled mechanism.
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 10/ 27
public class oe
{
public static void main(String key[])
{
int x=Integer.parseInt(key[0]);
if (x%2 ==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 11/ 27
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 12/ 27
try
{
f1= new File(s);
in= new FileReader(f1);
while(r!=-1)
{
r=in.read();
if(r=='\n')
c++;
if (r==' ' || r=='\n')
{
count++;
}
System.out.println("No. of words:"+count);
System.out.println("No. of lines:"+c);
in.close();
}
catch(IOException e){System.out.println(e);}
}
void display(String s)
{
int r =0;
try
{
f1= new File(s);
in = new FileReader(f1);
while(r!=-1)
{
r=in.read();
System.out.print((char)r);
}
in.close();
}
catch(IOException e){ System.out.println(e); }
}
void filecopy(String s)
{
int r =0;
try
{
f1= new File(s);
f2=new File("output.txt");
in = new FileReader(f1);
out= new FileWriter(f2);
while(r!=-1)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 13/ 27
{
r=in.read();
out.write((char)r);
}
System.out.println("File copied to output.txt...");
in.close();
out.close();
}
catch(IOException e){System.out.println(e);}
}
public static void main(String[] args)
{
filetest f= new filetest();
String filename= args[0];
f.getdata(filename);
f.filecopy(filename);
f.display(filename);
f.wordcount(filename);
}
}
d) State the use of final keyword w. r. t. a method and the variable with
suitable example.
final variable: the value of a final variable cannot be changed. final variable
behaves like class variables and they do not take any space on individual
objects of the class.
Eg of declaring final variable: final int size = 100;
final method: making a method final ensures that the functionality defined in
this method will never be altered in any way, ie a final method cannot be
overridden.
Eg of declaring a final method:
final void findAverage()
{
//implementation
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 14/ 27
a. Initialization state.
b. Running state.
c. Display state.
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
}
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 15/ 27
Q.4.
A. Attempt any THREE: 12
a) Compare string class and StringBuffer class with any four points.
(Any four points 1M each)
Sr. String StringBuffer
No.
1. String is a major class StringBuffer is a peer class of String
2. Length is fixed Length is flexible
3. Contents of object cannot be Contents of can be modified
modified
4. Object can be created by Objects can be created by calling
assigning String constants constructor of StringBuffer class using
enclosed in double quotes. new
5. Ex:- String s=abc; Ex:- StringBuffer s=new StringBuffer
(abc);
b) Explain thread priority and method to get and set priority values.
Threads in java are sub programs of main application program and share
the same memory space. They are known as light weight threads. A java
program requires at least one thread called as main thread. The main thread
is actually the main method module which is designed to create and start
other threads. Thread Priority: In java each thread is assigned a priority
which affects the order in which it is scheduled for running. Threads of
same priority are given equal treatment by the java scheduler.
The thread class defines several priority constants as: -
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 16/ 27
class reverse
{
public static void main(String args[])
{
int num = 253;
int q,r;
for (int I = 0; i<3; i++)
{
q = num / 10;
r = num % 10;
System.out.println(r);
Num = q;
}
}
}
Syntax:
long getTime( )
Returns the number of milliseconds that have elapsed since January 1,
1970.
ii. getDate()
Syntax:
public int getDate()
Returns the day of the month. This method assigns days with the values of
1 to 31.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 17/ 27
(Syntax of PARAM tag 1M, Use of tag 1m, Any suitable example 2M)
(Any suitable example may be considered)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 18/ 27
Example
import java.awt.*;
import java.applet.*;
public class hellouser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
<HTML>
<Applet code = hellouser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
class negativedemo
{
public static void main(String ar[])
{
int age=0;
String name;
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 19/ 27
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 20/ 27
1) Newborn State
2) Runnable State
3) Running State
4) Blocked State
5) Dead State
Thread should be in any one state of above and it can be move from one state
to another by different methods and ways.
1. Newborn state: When a thread object is created it is said to be in a new born state.
When the thread is in a new born state it is not scheduled running from this state it
can be scheduled for running by start() or killed by stop(). If put in a queue it moves to
runnable state.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 21/ 27
2. Runnable State: It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is waiting for
execution. If all threads have equal priority then they are given time slots for
execution in round robin fashion. The thread that relinquishes control joins the queue
at the end and again waits for its turn. A thread can relinquish the control to another
before its turn comes by yield().
3. Running State: It means that the processor has given its time to the thread for
execution. The thread runs until it relinquishes control on its own or it is pre-empted
by a higher priority thread.
wait(): If a thread requires to wait until some event occurs, it can be done using wait
method and can be scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using sleep(time)
where time is in ms. It reenters the runnable state as soon as period has elapsed /over.
5. Dead State: Whenever we want to stop a thread form running further we can call its
stop(). The statement causes the thread to move to a dead state. A thread will also
move to dead state automatically when it reaches to end of the method. The stop
method may be used when the premature death is required.
c) State the use of font class. Describe any three methods of font class with
their syntax and example of each.
(Use:- 2M, Any three method ( syntax and example), for each method -2M)
(Any other suitable example may also be considered)
Uses:-
The Font class states fonts, which are used to render text in a visible way.
It is used to set or retrieve the screen font.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 22/ 27
Sr methods description
no
4 String getFamily( ) Returns the name of the font family to which the
invoking font belongs.
5 static Font getFont(String Returns the font associated with the system
property) property specified by property. null is returned if
property does not exist.
11 int hashCode( ) Returns the hash code associated with the invoking
object.
12 boolean isBold( ) Returns true if the font includes the BOLD style
value. Otherwise, false is returned.
13 boolean isItalic( ) Returns true if the font includes the ITALIC style
value. Otherwise, false is returned.
14 boolean isPlain( ) Returns true if the font includes the PLAIN style
value. Otherwise, false is returned.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 23/ 27
example:-
{
public void paint(Graphics g)
{
Font a = new Font ("TimesRoman", Font.PLAIN, 10);
Font b = new Font ("TimesRoman", Font.PLAIN, 10);
// displays true since the objects have equivalent settings
g.drawString(""+a.equals(b),30,60);
}
}
/*<applet code=ss height=200 width=200>
</applet>*/
}
public void paint(Graphics g)
{
g.drawString("font name"+fname,60,44);
g.drawString("font family"+ffamily,60,77);
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 24/ 27
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries from Application are not restricted from using
other language such as C or C++ libraries from other language
b) Define JDK. List the tools available in JDK explain any one in detail.
(Definition 1 M, list any four tools -2M, explanation of any
component -1 M)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 25/ 27
Class: Person,
name , age
Class: employee,
emp_designation,
emp_salary
(Class and method declaration superclass1-1/2 M, class and method declaration of subclass
class person
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("name--->"+name);
System.out.println("age--->"+age);
}
}
class employee extends person
{
String emp_designation;
float emp_salary;
void accept_emp(String d,float s)
{
emp_designation=d;
emp_salary=s;
}
void emp_dis()
{
System.out.println("emp_designation-->"+emp_designation);
System.out.println("emp_salary-->"+emp_salary);
}
}
class single_demo
{
public static void main(String ar[])
{
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 26/ 27
d) Write the effect of access specifiers public, private and protected in package.
(Each specifier 2 marks)
Visibility restriction must be considered while using packages and inheritance in program
visibility restrictions are imposed by various access protection modifiers. packages acts as
container for classes and other package and classes acts as container for data and methods.
Data members and methods can be declared with the access protection modifiers such as
private, protected and public. Following table shows the access protections
Access location
Non-subclasses in yes no no no no
other packages
e) What are stream classes? List any two input stream classes from character stream.
(Definition and types- 2 M, any two input classes -2 M)
Definition: The java. Io package contain a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into two groups
based on the data type on which they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Summer 15 EXAMINATION
Subject Code: 17515 Model Answer Page 27/ 27
Character Stream Class can be used to read and write 16-bit Unicode characters. There are
two kinds of character stream classes, namely, reader stream classes and writer stream classes
Reader stream classes:--it is used to read characters from files. These classes are
functionally similar to the input stream classes, except input streams use bytes as their
fundamental unit of information while reader streams use characters
Marks
Ans:
1. Compile & Interpreted: Java is a two staged system. It combines both approaches.
First java compiler translates source code into byte code instruction. Byte codes are
not machine instructions. In the second stage java interpreter generates machine code
that can be directly executed by machine. Thus java is both compile and interpreted
language.
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 wont 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.
Page 1 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
3. Object Oriented: Almost everything in java is in the form of object. All program
codes and data reside within objects and classes. Similar to other OOP languages java
also has basic OOP properties such as encapsulation, polymorphism, data abstraction,
inheritance etc. Java comes with an extensive set of classes (default) in packages.
4. Robust & Secure: Java is a robust in the sense that it provides many safeguards to
ensure reliable codes. Java incorporates concept of exception handling which captures
errors and eliminates any risk of crashing the system. Java system not only verify all
memory access but also ensure that no viruses are communicated with an applet. It
does not use pointers by which you can gain access to memory locations without
proper 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 librarys
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.
Ans:
Page 2 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Page 3 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
}
}
}
continue:
The continue statement skips the current iteration of a for, while , or do-while loop. The
unlabeled form skips to the end of the innermost loop's body and evaluates the boolean
expression that controls the loop.
A labeled continue statement skips the current iteration of an outer loop marked with the
given label.
Example:
public class TestContinue
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
(d) What are streams? Write any two methods of character stream classes.
(Definition of Streamclass - 2 Marks, two methods of character stream class - 2 Marks)
Ans:
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information (i.e it takes the input or gives the output). A stream is
linked to a physical device by the Java I/O system. All streams behave in the same
manner, even if the actual physical devices to which they are linked differ. Thus, the
same I/O classes and methods can be applied to any type of device.
Page 4 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Character streams are defined by using two class hierarchies. At the top are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character streams.
Java has several concrete subclasses of each of these.
1) void mark(int numChars) : Places a mark at the current point in the input stream
that will remain valid until numChars characters are read.
6) boolean ready( ): Returns true if the next input request will not wait. Otherwise, it
returns false.
7) void reset( ): Resets the input pointer to the previously set mark.
8) long skip(long numChars) :- Skips over numChars characters of input, returning the
number of characters actually skipped.
9) abstract void close( ) :- Closes the input source. Further read attempts will generate
an IOException
Page 5 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Writer Class
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of error
1) abstract void close( ) : Closes the output stream. Further write attempts will generate
an IOException.
2) abstract void flush( ) : Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers.
3) void write(intch): Writes a single character to the invoking output stream. Note that
the parameter is an int, which allows you to call write with expressions without having to
cast them back to char.
4) void write(char buffer[ ]): Writes a complete array of characters to the invoking
output stream
5) abstract void write(char buffer[ ],int offset, int numChars) :- Writes a subrange of
numChars characters from the array buffer, beginning at buffer[offset] to the invoking
output stream.
7) void write(String str, int offset,int numChars): Writes a sub range of numChars
characters from the array str, beginning at the specified offset.
(a) What is package? How to create package? Explain with suitable example.
(Definition of package - 1 Mark, Package creation - 2 Marks, Example - 3 Marks)
Page 6 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Ans:
Java provides a mechanism for partitioning the class namespace into more manageable
parts called package (i.e package are container for a classes). The package is both naming
and visibility controlled mechanism. Package can be created by including package as the
first statement in java source code. Any classes declared within that file will belong to the
specified package.
The syntax for creating package is:
package pkg;
Here, pkg is the name of the package
eg : package mypack;
Packages are mirrored by directories. Java uses file system directories to store 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.
Syntax:
To access package In a Java source file, import statements occur immediately
following the package statement (if it exists) and before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}
Source file:
Page 7 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(b) State the use of super and final keyword w.r.t inheritance with example.
(super with example - 3 Marks , final with example - 3 Marks)
[**Note any relevant example can be considered]
Ans:
when you will want to create a superclass that keeps the details of its implementation to
itself (that is, that keeps its data members private). In this case, there would be no way for
a subclass to directly access or initialize these variables on its own. Whenever a subclass
needs to refer to its immediate super class, it can do so by use of the keyword super. As
constructer can not be inherited, but derived class can called base class constructer using
super ()
super has two general forms.
The first calls the super class constructor. (super() method)
The second is used to access a member of the super class that has been hidden by a
member of a subclass.
Using super () to Call Super class Constructors
A subclass can call a constructor method defined by its super class by use of the
following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the super
class. super( ) must always be the first statement executed inside a subclass constructor.
A Second Use for super
The second form of super acts somewhat like this, except that it always refers to the
super class of the subclass in which it is used. This usage has the following general form:
super.member
Page 8 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Final keywords
The keyword final has three uses. First, it can be used to create the equivalent of a named
constant.( in interface or class we use final as shared constant or constant.)
other two uses of final apply to inheritance
While method overriding is one of Javas most powerful features, there will be times
Page 9 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
As base class declared method as a final , derived class can not override the definition of
base class methods.
(a) Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10, 20).
Remove element at 3rd and 4th position. Insert new element at 3rd position. Display
the original and current size of vector.
(Vector creation with elements 2 Marks, Remove elements 1 Mark, Insert new
element 1 Mark, Show original size 1 Mark, show current size 1 Mark )
Ans:
import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(new Integer(10));
Page 10 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(b) What is meant by an interface? State its need and write syntax and features of an
interface. Give one example.
(Definition - 1 Mark syntax - 1 Mark, Any two features - 2 Marks, Any two needs - 2
Marks, Example - 2 Marks)
Ans:
Defining an Interface:
Interface is also known as kind of a class. So interface also contains methods and
variables but with major difference the interface consist of only abstract method
(i.e.methods are not defined,these are declared only ) and final fields(shared constants).
This means that interface do not specify any code to implement those methods and data
fields contains only constants. Therefore, it is the responsibility of the class that
implements an interface to define the code for implementation of these methods. An
interface is defined much like class.
Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
.
return_type method_nameN(parameter list);
type final-variable 1 = value1;
.
Page 11 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Features:
1. Variable of an interface are explicitly declared final and static (as constant) meaning
that the implementing the class cannot change them they must be initialize with a
constant value all the variable are implicitly public of the interface, itself, is declared
as a public
2. Method declaration contains only a list of methods without anybody statement and
ends with a semicolon the method are, essentially, abstract methods there can be
default implementation of any method specified within an interface each class that
include an interface must implement all of the method
Need:
1. To achieve multiple Inheritance.
2. We can implement more than one Interface in the one class.
3. Methods can be implemented by one or more class.
Example:
interface sports
{
int sport_wt=5;
public void disp();
}
class Test
{
int roll_no;
String name;
int m1,m2;
Test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class Result extends Test implements sports
{
Result (int r, String nm, int m11,int m12)
{
super (r,nm,m11,m12);
Page 12 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(ii) drawPolygon
drawPolygon() method is used to draw arbitrarily shaped figures.
Page 13 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(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);
(a) What is constructor? Describe the use of parameterized constructor with suitable
example.
(Constructor 1 Mark, use of parameterized constructor 1 Mark, example of
parameterized constructor 2 Marks)
[**Note: any relevant example can be considered]
Ans:
Page 14 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Constructor:
A constructor is a special method which initializes an object immediately upon
creation.
It has the same name as class name in which it resides and it is syntactically similar to
any method.
When a constructor is not defined, java executes a default constructor which
initializes all numeric members to zero and other types to null or spaces.
Once defined, constructor is automatically called immediately after the object is
created before new operator completes.
Constructors do not have return value, but they dont require void as implicit data
type as data type of class constructor is the class type itself.
Parameterized constructor:
It is used to pass the values while creating the objects
Example:
class Rect
{
int length, breadth;
Rect(int l, int b) // parameterized constructor
{
length=l;
breadth=b;
}
public static void main(String args[])
{
Rect r = new Rect(4,5); // constructor with parameters
Rect r1 = new Rect(6,7);
System.out.println(Area : +(r.length*r.breadth));
System.out.println(Area : +(r1.length*r1.breadth));
}
}
Page 15 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Ans:
The ternary operator?: is an operator that takes three arguments. The first argument is a
comparison argument, the second is the result upon a true comparison, and the third is the
result upon a false comparison. If it helps you can think of the operator as shortened way
of writing an if-else statement. It is often used as a way to assign variables based on the
result of an comparison. When used correctly it can help increase the readability and
reduce the amount of lines in your code
Syntax:
expression1? expression2: expression3
Expression1 can be any expression that evaluates to a Boolean value.
If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the? Operation is that of the expression evaluated.
Both expression2 and expression3 are required to return the same type, which can't
be void.
Example:
class Ternary
{
public static void main(String args[])
{
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Page 16 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(c) What is difference between array and vector? Explain elementAt( ) and
addElement( ) method.
(Any 2 Points - 2 Marks, Each Method - 1 Mark)
Ans:
Array Vector
Array can accommodate fixed number of Vectors can accommodate unknown number of
elements elements
Arrays can hold primitive data type & objects Vectors can hold only objects.
All elements of array should be of the same The objects in a vector need not have to be
data type. i.e. it can contain only homogeneous homogeneous.
elements.
Syntax : Datatype[] arrayname= new Syntax: Vector objectname= new Vector();
datatype[size];
For accessing elements of an array no special Vector class provides different methods for
methods are available as it is not a class , but accessing and managing Vector elements.
derived type.
2) addElement ( ): Adds the specified component to the end of this vector, increasing
its size by one.
Syntax: void addElement(Object element)
Example:
Vector v = new Vector();
v.addElement(new Integer(1)); //add integer object 1 to vector
Page 17 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(d) Write any two methods of File and FileInputStream class each.
(An y two methods of each class - 1 Mark)
Ans:
File Class Methods
1. int available( )- Returns the number of bytes of input currently available for reading.
2. void close( )- Closes the input source. Further read attempts will generate an
IOException.
3. void mark(int numBytes) -Places a mark at the current point in the inputstream that
will remain valid until numBytes bytes are read.
4. boolean markSupported( ) -Returns true if mark( )/reset( ) are supported by the
invoking stream.
5. int read( )- Returns an integer representation of the next available byte of input. 1 is
returned when the end of the file is encountered.
6. int read(byte buffer[ ])- Attempts to read up to buffer.length bytes into buffer and
returns the actual number of bytes that were successfully read. 1 is returned when
the end of the file is encountered.
(e) Write a program to design an applet to display three circles filled with three
different colors on screen.
(Correct logic 2 Marks, Applet tag 1 Mark, Package imported 1 Mark)
[**Note: any other relevant logic can be considered, output not necessary]
Ans:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
Page 18 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(a) Write a program to check whether the entered number is prime or not.
(Accept No. from user - 1 Mark, Prime No. logic - 3 Marks)
Ans: import java.io.*;
class PrimeNo
{
public static void main(String args[]) throws IOException
{
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number: ");
int num=Integer.parseInt(bin.readLine());
Page 19 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
int flag=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}
Page 20 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
iv. finally: It can be used to handle an exception which is not caught by any of the
previous catch statements. finally block can be used to handle any statement
generated by try block. It may be added immediately after try or after last catch block.
Syntax:
finally
{
// block of code to be executed before try block ends
}
Ans:
1) Bitwise NOT (~): called bitwise complement, the unary NOT operator, inverts all of
the bits of its operand.
e.g~ 0111 (decimal 7) = 1000 (decimal 8)
Page 21 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
3) Bitwise OR ( | ) :
the OR operator, | , combines bits such that if either of the bits in the operand is a 1, then
the resultant bit is a 1
4) Bitwise XOR ( ^ ): the XOR operator, ^, combines bits such that if exactly one
operand is 1, then the result is 1. Otherwise result is zero.
e.g0101 (decimal 5) ^ 0011 (decimal 3) = 0110 (decimal 6)
5) The Left Shift (<<): the left shift operator, <<, shifts all of the bits in a value to the
left a specified number of times specified by num
General form: value <<num
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.
7) Unsigned Right Shift (>>>) : >>> always shifts zeros into high order bit.
e.g. int a= -1
a=a>>>24
Page 22 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
a >> = 4;
Ans:
APPLET Tag: The APPLET tag is used to start an applet from both an HTML
document and from an appletviewer will execute each APPLET tag that it finds in a
separate window, while web browser will allow many applets on a single page the syntax
for the standard APPLET tag is:
<APPLET
[CODEBASE=codebaseURL]
CODE =appletfileName
[ALT=alternateText]
[NAME=applet_instance_name]
WIDTH=pixels HEIGHT=pixels
[ALIGN=aligment]
[VSPACE=pixels] [HSPACE=pixels]
>
[<PARAM NAME=attributeName1 VALUE=attributeValue>]
[<PARAM NAME=attributeName2 VALUE=attributeValue>]
</APPLET>
CODEBASE: is an optional attribute that specifies the base URL of the applet code or
the directory that will be searched for the applets executable class file.
CODE: is a required attribute that give the name of the file containing your applets
compiled class file which will be run by web browser or 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.
Page 23 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
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.
(a) Differentiate between applet and application and also write a simple applet which
display message Welcome to Java.
(Any 3 Points - 3 Marks, Correct Program - 3 Marks)
Ans:
Applet Application
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files Application can read from or write to files in
in local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries Application are not restricted from using
from other language such as C or C++ libraries from other language
Page 24 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Program:
/*<applet code= WelcomeJava width= 300 height=300></applet>*/
2. charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .
Eg. String s=INDIA
System.out.println(s.charAt(2) ); // returns D
3. compareTo():
Syntax: int compareTo(Object o)
or
Page 25 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(a) Write a program to accept password from user and throw Authentication failure
exception if password is incorrect.
(Correct logic - 5 Marks, for syntax - 3 Marks)
Ans:
import java.io.*;
class PasswordException extends Exception
{
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("EXAMW15"))
{
Page 26 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Ans:
Thread Life Cycle
Thread has five different states throughout its life.
1) Newborn State
2) Runnable State
3) Running State
4) Blocked State
5) Dead State
Thread should be in any one state of above and it can be move from one state to another
by different methods and ways.
Page 27 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
1. Newborn state: When a thread object is created it is said to be in a new born state.
When the thread is in a new born state it is not scheduled running from this state it can be
scheduled for running by start() or killed by stop(). If put in a queue it moves to runnable
state.
2. Runnable State: It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is waiting for
execution. If all threads have equal priority then they are given time slots for execution in
round robin fashion. The thread that relinquishes control joins the queue at the end and
again waits for its turn. A thread can relinquish the control to another before its turn
comes by yield().
3. Running State: It means that the processor has given its time to the thread for
execution. The thread runs until it relinquishes control on its own or it is pre-empted by a
higher priority thread.
4. Blocked state: A thread can be temporarily suspended or blocked from entering into
the runnable and running state by using either of the following thread method.
suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
wait(): If a thread requires to wait until some event occurs, it can be done using wait
method andcan be scheduled to run again by notify().
Page 28 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
5. Dead State: Whenever we want to stop a thread form running further we can call its
stop(). The statement causes the thread to move to a dead state. A thread will also move
to dead state automatically when it reaches to end of the method. The stop method may
be used when the premature death is required
(c) How can parameter be passed to an applet? Write an applet to accept user name in
the form of parameter and print Hello<username>.
(Explanation for parameter passing - 3Marks, any suitable example 5 Marks)
(Any suitable example may be considered)
Ans:
Passing Parameters to Applet
User defined parameters can be supplied to an applet using <PARAM..> tags.
PARAM tag names a parameter the Java applet needs to run, and provides a value
for that parameter.
PARAM tag can be used to allow the page designer to specify different colors, fonts,
URLs or other data to be used by the applet.
import
java.awt.*;
import
java.applet.*;
public class HelloUser extends Applet
Page 29 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
}
}
<HTML>
<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
OR
import java.awt.*;
import java.applet.*;
/*<Applet code = HelloUser.class width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>*/
public class HelloUser extends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
Page 30 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Ans:
Method Overloading means to define different methods with the same name but different
parameters lists and different definitions. It is used when objects are required to perform
similar task but using different input parameters that may vary either in number or type of
arguments. Overloaded methods may have different return types. It is a way of achieving
polymorphism in java.
int add( int a, int b) // prototype 1
int add( int a , int b , int c) // prototype 2
double add( double a, double b) // prototype 3
Example :
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2.2));
Page 31 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(b) State any four system packages along with their use.
(Any 4 four, for each listing and use - 1 Mark)
Ans:
1. java.lang - language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. They include classes for primitive
types, strings, math functions, threads and exceptions.
2. java.util language utility classes such as vectors, hash tables, random numbers, date
etc.
3. java.io input/output support classes. They provide facilities for the input and
output of data
4. java.awt set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
5. java.net classes for networking. They include classes for communicating with
local computers as well as with internet servers.
6. java.applet classes for creating and implementing applets.
(c) What is use of ArrayList Class ?State any three methods with their use from
ArrayList.
(Any one Use - 1 Mark, Any 3 methods - 1 Mark each)
Ans:
Use of ArrayList class:
1. ArrayList supports dynamic arrays that can grow as needed.
2. ArrayList is a variable-length array of object references. That is, an ArrayListcan
dynamically increase or decrease in size. Array lists are created with an initial size.
When this size is exceeded, the collection is automatically enlarged. When objects are
removed, the array may be shrunk.
Page 32 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
2. boolean add(Object o)
Appends the specified element to the end of this list.
3. boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the
order that they are returned by the specified collection's iterator. Throws
NullPointerException if the specified collection is null.
4. boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the
specified position. Throws NullPointerException if the specified collection is null.
5. void clear()
Removes all of the elements from this list.
6. Object clone()
Returns a shallow copy of this ArrayList.
7. boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if
and only if this list contains at least one element e such that (o==null ? e==null :
o.equals(e)).
8. void ensureCapacity(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.
9. Object get(int index)
Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >= size()).
10. int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if
the List does not contain this element.
11. int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if
the list does not contain this element.
12. Object remove(int index)
Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13. protected void removeRange(intfromIndex, inttoIndex)
Removes from this List all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.
14. Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element.
Throws IndexOutOfBoundsException if the specified index is is out of range (index <
0 || index >= size()).
Page 33 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
Ans:
Serialization in java is a mechanism of writing the state of an object into a
byte stream.
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object
and its data can be used to recreate the object in memory.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data
types such as writeObject() method. This method serializes an Object and sends it to
the output stream. Similarly, the ObjectInputStream class contains method for
deserializing an object as readObject(). This method retrieves the next Object out of
the stream and deserializes it. The return value is Object, so you will need to cast it to
its appropriate data type.
For a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient.
Page 34 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
WINTER-15 EXAMINATION
Model Answer Paper
(e) What is byte code? Explain any two tools available in JDK.
(Bytecode - 2 Marks, Any 2 Tools - 1 Mark each)
Ans:
Byte code: Bytecode in Java is an intermediate code generated by the compiler such as
Suns javac, that is executed by JVM. Bytecode is compiled format of Java programs it
has a .class extension.
Page 35 of 35
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
a) Describe any two relational and any two logical operators in java with simple example.
(Relational operators & example - 1 mark each; Logical operators & example - 1 mark each)
[**Note - Any relevant example can be considered**]
Ans:
Relational Operators: When comparison of two quantities is performed depending on their
relation, certain decisions are made. Java supports six relational operators as shown in table.
Operators Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal
to
== Equal to
!= Not equal to
Page 1 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Logical Operators: Logical operators are used when we want to form compound conditions by
combining two or more relations. Java has three logical operators as shown in table:
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
System.out.println(!A+(!A)); // false
System.out.println(A^B+(A^B)); // true
System.out.println((A|B)&A+((A|B)&A)); // true
}
}
Page 2 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
b) What are stream classes? List any two input stream classes from character stream.
(Definition and types - 2 marks; any two input stream classes - 2 marks)
Ans:
Definition: The java. Io package contain a large number of stream classes that provide capabilities
for processing all types of data. These classes may be categorized into two groups based on the data
type on which they operate. 1. Byte stream classes that provide support for handling I/O operations
on bytes. 2. Character stream classes that provide support for managing I/O operations on
characters.
Character Stream Class can be used to read and write 16-bit Unicode characters. There are two
kinds of character stream classes, namely, reader stream classes and writer stream classes
Reader stream classes:-it is used to read characters from files. These classes are functionally
similar to the input stream classes, except input streams use bytes as their fundamental unit of
information while reader streams use characters
Input Stream Classes
1. BufferedReader
2. CharArrayReader
3. InputStreamReader
4. FileReader
5. PushbackReader
6. FilterReader
7. PipeReader
8. StringReader
c) Write general syntax of any two decision making statements and also give its examples.
(Any two decision making statement & example - 2 marks each)
[**Note: Any relevant example can be considered**]
Ans:
Decision Making with if statement: The if statement is powerful decision making statement & is
used to control flow of execution of statements. The if statement is the simplest one in decision
statement. The if keyword is followed by test expression in parentheses.
It is basically a two way decision statement & is used in conjunction with an expression. It has
following syntax: if(test expression)
It allows computer to evaluate expression first & then depending on value of expression
(relation or condition) is true or false, it transfers control to a particular statement. The
program has two parts to follow one for if condition is true & the other for if condition is
false
Page 3 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Page 4 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
3. Nested if .. else Statement: When series of decision are involved , more than one if else
statements are used in nested. General form is
if (test condition 1)
{
if (test condition2)
{
statement block 1;
}
else
{
statement block 2;
}
else
{
statement block 3;
}
statement n;
4. The else if ladder: When multipath decision are involved either nested if or else if
ladder can be used. A multipath decision is chain of its in which statement associated with
each else is an if. General form is:
if (condition 1)
statement 1;
else if (test condition2)
statement 2;
else if (test condition3)
statement 3;
.
.
else if (test conditionn)
statement n;
else
default statement;
statement x;
Page 5 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
This construction is known as elseif ladder. The conditions are evaluated from top (of the
ladder) to downwards. As soon as true conditions are found, statement associated with it is executed
& control is transferred to statement-n (skipping the rest of the ladder). When all the n conditions
becomes false, then final else containing default statement will be executed.
Switch Statement:
Java has built-in multi way decision statement known as switch. it can be used instead of if or
nested if..else.
General form:
switch(expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
.
.
.
default:
default block;
break;
}
statement n;
The expression is an integer expression or character. value1, value2. Value n are constants
or constant expressions which must be evaluated to integral constants are known as case
labels. Each of these values should be unique within switch statement. Block1, block 2 are
statement lists & may contain zero or more statements. There is no need to put braces around
these blocks but case labels must end with colon ( : ).
When switch is executed, value of expression is successively compared against values value-
1, value-2. If case is found whose value matches with value of expression, then block
statements that follows case are executed.
The break statement at end of each block signals end of particular case & causes exit from
switch statement & transferring control to statement following switch.
The default is optional case. When present it will be executed if value of expression does not
match with any of cases values. If not present, no action takes place when all matches fail &
control goes to statement x.
The?: Operator:
Java language has an ternary operator, useful for making two-way decisions. This operator
is combination of ? &:, Takes three operand so it is called as ternary operator. This operator
Page 6 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
is popularly known as conditional operator. General form of use of conditional operator is:
conditional expression? expression 1 : expression 2
The conditional expression is evaluated first. If result is true, expression 1 is evaluated & is
returned as value of conditional expression. Otherwise, expression 2 is evaluated & its value
is returned. For example,
if (a<0)
flag = 0;
else
flag = 1;
can written as flag = (a<0) ? 0 : 1
When conditional operators is used, code becomes more concise & perhaps , more efficient.
However readability is poor. It is better to use if statements when more than single nesting
of conditional operator is required.
Ans:
Thread Life Cycle Thread has five different states throughout its life.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state to another by
different methods and ways.
Page 7 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
1. Newborn state: When a thread object is created it is said to be in a new born state. When the
thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to runnable state.
2. Runnable State: It means that thread is ready for execution and is waiting for the availability
of the processor i.e. the thread has joined the queue and is waiting for execution. If all threads
have equal priority then they are given time slots for execution in round robin fashion. The
thread that relinquishes control joins the queue at the end and again waits for its turn. A thread
can relinquish the control to another before its turn comes by yield().
3. Running State: It means that the processor has given its time to the thread for execution. The
thread runs until it relinquishes control on its own or it is pre-empted by a higher priority
thread.
4. Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
wait(): If a thread requires to wait until some event occurs, it can be done using wait method
andcan be scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time
is in ms. It reenters the runnable state as soon as period has elapsed /over
5. Dead State: Whenever we want to stop a thread form running further we can call its stop().
The statement causes the thread to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop method may be used when the
premature death is required
a) Explain following methods of string class with their syntax and suitable example.
i) substring () ii) replace ()
(Each method syntax & example - 3 marks)
[**Note - Any relevant example can be considered**]
Ans:
i) substring()
Syntax:
String substring(intstartindex)
Startindex specifies the index at which the substring will begin. It will returns a copy of the
substring that begins at startindex and runs to the end of the invoking string
String substring(intstartindex,intendindex)
Here startindex specifies the beginning index,andendindex specifies the stopping point. The
string returned all the characters from the beginning index, upto, but not including ,the ending
index.
String Str = new String("Welcome");
Page 8 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
System.out.println(Str.substring(3)); //come
System.out.println(Str.substring(3,5));//co
ii) replace()
This method returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
b) Write syntax of defining interface .Write any major two differences between interface and a class.
(Syntax - 2 marks; Difference - 2 marks [Any two relevant points])
Ans:
Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
return_type method_name2(parameter list);
type final-variable 1 = value1;
type final-variable 2 = value2;
CLASS INTERFACE
It has instance variable. It has final variable.
It has non abstract method. It has by default abstract method.
Class has the access specifiers like public, Interface has only public access specifier
private, and protected.
Classes are always extended. Interfaces are always implemented.
The memory is allocated for the classes. We are not allocating the memory for the
interfaces.
Multiple inheritance is not possible with Interface was introduced for the concept of
classes multiple inheritance
class Example { interface Example
void method1() {
Page 9 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
{ int x =5;
body void method1();
} void method2();
void method2() }
{
body
}
}
a) Write a program to implement a vector class and its method for adding and removing
elements. After remove display remaining list.
(Logic - 4 marks; Syntax - 4 marks)
[**Note - Any relevant program can be considered**]
Ans:
import java.io.*;
import java.lang.*;
import java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Character s5=new Character('a');
Character s6=new Character('b');
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s5);
v.addElement(s6);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
Page 10 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}
b) Describe with example how to achieve multiple inheritance with suitable program.
(Multiple inheritance - 2 marks; example - 6 marks)
[**Note - Any relevant example can be considered**]
Ans:
Multiple inheritances: It is a type of inheritance where a derived class may have more than one
parent class. It is not possible in case of java as you cannot have two classes at the parent level
Instead there can be one class and one interface at parent level to achieve multiple interface.
Interface is similar to classes but can contain on final variables and abstract method. Interfaces can
be implemented to a derived class.
Example:
Code :
interface Gross
{
double TA=800.0;
double DA=3500;
void gross_sal();
}
class Employee
{
String name;
double basic_sal;
Employee(String n, double b)
{
name=n;
basic_sal=b;
Page 11 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
}
void display()
{
System.out.println("Name of Employee :"+name);
System.out.println("Basic Salary of Employee :"+basic_sal);
}
}
class Salary extends Employee implements Gross
{ double HRA;
Salary(String n, double b, double h)
{
super(n,b);
HRA=h;
}
void disp_sal()
{ display();
System.out.println("HRA of Employee :"+hra);
}
public void gross_sal()
{
double gross_sal=basic_sal + TA + DA + HRA;
System.out.println("Gross salary of Employee :"+gross_sal);
}
}
class EmpDetails
{ public static void main(String args[])
{ Salary s=new Salary("Sachin",8000,3000);
s.disp_sal();
s.gross_sal();
}
}
Page 12 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
g.drawString(Concentric Circle,120,20);
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
/*<applet code=Shapes.class height=300 width=200>
</applet>*/
(OR)
HTML Source:
<html>
<applet code=Shapes.class height=300 width=200>
</applet>
</html>
Page 13 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Ans:
class PrimeNo
{
public static void main(String args[])
{
intnum=Integer.parseInt(args[0]);
int flag=0;
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}
Serialization is the process of writing the state of an object to a byte stream. This is useful when you
want to save the state of your program to a persistent storage area, such as a file. At a later time,
you may restore these objects by using the process of deserialization.
Page 14 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
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, inturn, 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.
drawRect()
The drawRect() method display an outlined rectangle
Syntax:
voiddrawRect(inttop,intleft,intwidth,int height)
This method takes four arguments, the first two represents the x and y co-ordinates of the top left
corner of the rectangle and the remaining two represent the width and height of rectangle.
Example:
g.drawRect(10,10,60,50);
drawOval()
To draw an Ellipses or circles used drawOval()method.
Syntax:
voiddrawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top and
left and whose width and height are specified by width and height to draw a circle or filled circle,
specify the same width and height the following program draws several ellipses and circle.
Example:
g.drawOval(10,10,50,50);//this is circle
g.drawOval(10,10,120,50);//this is oval
Page 15 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Ans:
Using inheritance, you can create a general class that defines traits common to a set of related items.
This class can then be inherited by other, more specific classes, each adding those things that are
unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that
does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a
superclass.
. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword
super.
Superhas two general forms. The first calls the super class constructor. The second is used to
access a member of the superclass that has been hidden by a member of a subclass.
super() is used to call base class constructer in derived class.
Super is used to call overridden method of base class or overridden data or evoked the overridden
data in derived class.
e.g use of super()
class BoxWeightextends Box
{
BowWeight(int a ,intb,int c ,int d)
{
super(a,b,c) // will call base class constructer Box(int a, int b, int c)
weight=d // will assign value to derived class member weight.
}
e.g. use of super.
Class Box
{
Box()
{
}
void show()
{
//definition of show
}
} //end of Box class
Page 16 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
{
}
void show() // method is overridden in derived
{
Super.show() // will call base class method
}
}
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked. You can use this anywhere a
reference to an object of the current class type is permitted. To better understand what this refers
to, consider the following version of Box( ): // A redundant use of this. Box(double w, double h,
double d) { this.width = w; this.height = h; this.depth = d; }
Page 17 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Continue:
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled
form skips to the end of the innermost loop's body and evaluates the boolean expression that
controls the loop.
A labeled continue statement skips the current iteration of an outer loop marked with the given
label.
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Page 18 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Throws clause
If a method is capable of causing an exception that it does not handle, it must specify this behavior
so that callers of the method can guard themselves against that exception. You do this by including
a throws clause in the methods declaration. A throws clause lists the types of exception that a
method might throw. General form of method declaration that includes throws clause
Type method-name (parameter list) throws exception list {// body of method} Here exception list
can be separated by a comma.
Eg.
class XYZ
{
XYZ();
{
// Constructer definition
}
void show() throws Exception
{
throw new Exception()
}
}
c) State syntax and describe working of for each version of for loop with one example.
(Explanation with syntax - 2 marks; example - 2 marks.)
Ans:
The For-Each Alternative to Iterators
If you wont be modifying the contents of a collection or obtaining elements in reverse order, then
the for-each version of the for loop is often a more convenient alternative to cycling through a
collection than is using an iterator. Recall that the for can cycle through any collection of objects
that implement the Iterable interface. Because all of the collection classes implement this interface,
they can all be operated upon by the for.
// Use the for-each for loop to cycle through a collection.
// Use a for-each style for loop.
Syntax:
Example
ClassForEach
{
Page 19 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Ans:
The Map Classes Several classes provide implementations of the map interfaces.
A map is an object that stores associations between keys and values, or key/value pairs. Given a
key, you can find its value. Both keys and values are objects. The keys must be unique, but the
values may be duplicated. Some maps can accept a null key and null values, others cannot.
Methods:
void clear // removes all of the mapping from map
booleancontainsKey(Object key) //Returns true if this map contains a mapping for the specified
key.
Boolean conainsValue(Object value)// Returns true if this map maps one or more keys to the
specified value
Boolean equals(Object o) //Compares the specified object with this map for equality.
Ans:
The AWT supports multiple type fonts emerged from the domain of traditional type setting to
become an important part of computer-generated documents and displays. The AWT provides
flexibility by abstracting font-manipulation operations and allowing for dynamic selection of fonts.
Page 20 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Fonts have a family name, a logical font name, and a face name. The family name is the general
name of the font, such as Courier. The logical name specifies a category of font, such as
Monospaced. The face name specifies a specific font, such as Courier Italic
To select a new font, you must first construct a Font object that describes that font. One Font
constructor has this general form:
Font(String fontName, intfontStyle, intpointSize)
To use a font that you have created, you must select it using setFont( ), which is defined by
Component.
It has this general form:
VoidsetFont(Font fontObj)
Example
importjava.applet.*;
importjava.awt.*;
importjava.awt.event.*;
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
public void init()
{
f = new Font("Dialog", Font.PLAIN, 12);
msg = "Dialog";
setFont(f);
public void paint(Graphics g)
{
g.drawString(msg, 4, 20);
}
}
Ans:
final method: making a method final ensures that the functionality defined in this method will
never be altered in any way, ie a final method cannot be overridden.
E.g.of declaring a final method:
final void findAverage() {
//implementation
}
EXAMPLE
Page 21 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
class A
{
System.out.println(in show of A);
}
}
class B extends A
{
final variable: the value of a final variable cannot be changed. final variable behaves like class
variables and they do not take any space on individual objects of the class.
E.g.of declaring final variable:
final int size = 100;
a) What is thread priority? How thread priority are set and changed? Explain with example.
(Thread Priority - 2 marks; each method - 2 marks; Any Relevant Example - 2 marks)
Ans:
Thread Priority: Threads in java are sub programs of main application program and share the
same memory space. They are known as light weight threads. A java program requires at least one
thread called as main thread. The main thread is actually the main method module which is
designed to create and start other threads in java each thread is assigned a priority which affects the
order in which it is scheduled for running. Thread priority is used to decide when to switch from
one running thread to another. Threads of same priority are given equal treatment by the java
scheduler. Thread priorities can take value from 1-10. Thread class defines default priority constant
values as
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10
1. setPriority:
Syntax:public void setPriority(int number);
Page 22 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
Page 23 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try
{
hi.t.join();
lo.t.join();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
b) Write a program to input name and age of person and throws user defined exception, if
entered age is negative.
(Declaration of class with proper members and constructor - 4 marks; statement for throwing
exception and main method - 4 marks)
[**Note: Any other relevant program can be considered**]
Ans:
import java.io.*;
class Negative extends Exception
{
Negative(String msg)
{
super(msg);
}
}
class Negativedemo
{
public static void main(String ar[])
{
int age=0;
String name;
BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in));
Page 24 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
c) Explain <applet> tag with major attributes only. State purpose of get Available Font Family
Name () method of graphics environment class.
(Syntax - 2 marks; any 4 attributes of Applet tag - 4 marks; purpose -2 marks)
Ans:
The HTML APPLET Tag and attributes
The APPLET tag is used to start an applet from both an HTML document and from an applet
viewer.
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>
1. 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.
Page 25 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
2. 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 appletviewer.
3. 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.
4. NAME is an optional attribute used to specifies a name for the applet instance.
5. WIDTH AND HEIGHT are required attributes that give the size(in pixels) of the applet
display area.
6. 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.
7. 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
8. PARAM NAME AND VALUE:
The PARAM tag allows you to specifies applet- specific arguments in an HTML page
applets access there attributes with the get Parameter()method.THE
Parameters:
l - a Localeobject that represents a particular geographical, political, or cultural region. Specifying
null is equivalent to specifying Locale.getDefault().
Or
String[] getAvailableFontFamilyNames()
It will return an array of strings that contains the names of the available font families
Page 26 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
a) Define a class item having data member code and price. Accept data for one object and
display it.
(Correct Program - 4 marks)
[**Note: Input without BufferedReader or any IOStream to be considered or argument to be
considered. **]
Ans:
import java.io.*;
class Item_details
{
int code;
float price;
Item_details()
{
code=0;
price=0;
}
Item_details(int e,float p)
{
code=e;
price=p;
}
void putdata()
{
System.out.println("Code of item :"+code);
System.out.println("Price of item:"+price);
}
public static void main(String args[]) throws IOException
{
intco;floatpr;
BufferedReaderbr=new BufferedReader (new InputStreamReader(System.in));
System.out.println("enter code and price of item");
co=Integer.parseInt(br.readLine());
pr=Float.parseFloat(br.readLine());
Item_detailsobj=new Item_details(co,pr);
obj.putdata();
}
}
Page 27 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
b) What is use of Array list class? State any two methods with their use from ArrayList.
(Use - 2 marks; any 2 methods - 1 mark each)
Ans:
Use of ArrayList class:
1. ArrayListsupports dynamic arrays that can grow as needed.
2. ArrayListis a variable-length array of object references. That is, an ArrayListcan
dynamically increase or decrease in size. Array lists are created with an initial size. When
this size is exceeded, the collection is automatically enlarged. When objects are removed,
the array may be shrunk.
Page 28 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
11. 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.
12. Object remove(int index)
Removes the element at the specified position in this list. Throws
IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13. protected void removeRange(intfromIndex, inttoIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.
14. Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >=
size()).
15. int size()
Returns the number of elements in this list.
16. Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException if the specified array is null.
17. Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime
type of the returned array is that of the specified array.
18. void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
c) Design an Applet program which displays a rectangle filled with red color and message as
Hello Third year Students in blue color.
(Correct Program - 4 marks)
Ans:
import java.awt.*;
import java.applet.*;
public class DrawRectangle extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(10,60,40,30);
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
Page 29 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
/*
<applet code="DrawRectangle.class" width="350" height="300">
</applet> */
d) Design a package containing a class which defines a method to find area of rectangle. Import
it in java application to calculate area of a rectangle.
(Package declaration - 2 marks; Usage of package - 2 marks)
Ans:
package Area;
public class Rectangle
{
doublelength,bredth;
public doublerect(float l,float b)
{
length=l;
bredth=b;
return(length*bredth);
}
}
import Area.Rectangle;
class RectArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle( );
double area=r.rect(10,5);
System.out.println(Area of rectangle= +area);
}
}
Page 30 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER-16 EXAMINATION
Model Answer
e) Define a class having one 3-digit number as a data member. Initialize and display reverse of
that number.
(Logic - 2 marks; Syntax - 2 marks)
[**Note: Any other relevant logic can be considered**]
Ans:
class reverse
{
public static void main(String args[])
{
intnum = 253;
intremainder, result=0;
while(num>0)
{
remainder = num%10;
result = result * 10 + remainder;
num = num/10;
}
System.out.println("Reverse number is : "+result);
}
}
Page 31 of 31
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Viii Distributed
We can create distributed applications in java. RMI and EJB are used fo
applications. We may access files by calling the methods from any mac
{ be
a++; consider
b++; ed - 3M
int c = 0; //local variable
c++;
System.out.println("In constructor printing a: "+a);//will be accessed (class,
System.out.println("In constructor printing b: "+b);//will be accessed instance
System.out.println("In constructor printing c: "+c);//will be accessed and
} local
public static void main(String ar[]) variable
{ s should
VariableTypes s = new VariableTypes(); be
VariableTypes s1 = new VariableTypes(); declared
VariableTypes s2 = new VariableTypes(); and
System.out.println("in main printing a: "+VariableTypes.a);//will be marked
accessed clearly
System.out.println("in main printing b: "+s.b);//will be accessed each
System.out.println("in main printing c "+s.c);//will not be accessed 1M)
because this is a local variable declared in constructor
}
}
(c) What is an exception? How it is handled? Give suitable example. 4M
(Note: Any suitable example should be considered)
Ans. An exception is an event, which occurs during the execution of a Definitio
program, that disrupts the normal flow of the program execution. n of
exceptio
An exception handler will handle the exception using the keywords n 1M
i. try
ii. catch Keyword
iii. throw s 1M
iv. throws
v. finally
Eg:
import java.io.*;
class ExceptionHandling
{
int num1, num2, answer;
void acceptValues()
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter two numbers");
num1 = Integer.parseInt(bin.readLine());
num2 = Integer.parseInt(bin.readLine()); Example
} catch(IOExceptionie)
2M
{
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(ArithmeticException ae)
{
System.out.println("Divide by zero"+ae);
}
}
public static void main(String a[])
{
ExceptionHandling e = new ExceptionHandling();
e.doArithmetic();
}
}
(d) Explain methods of map class and set class in jdk frame work. 4M
Ans. The methods declared in the interface Map are:
void clear()-Removes all of the mappings from this map (optional
operation).
Any 2
boolean containsKey(Object key)-Returns true if this map contains a methods
mapping for the specified key. of map
and any
boolean containsValue(Object value)-Returns true if this map maps
2
one or more keys to the specified value.
methods
Set<Map.Entry<K,V>> entrySet() - Returns a Set view of the of set
mappings contained in this map. 2M
each
}
int volume(int l, int w, int d)
{
return l*w*d;
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter the length, width and depth");
int l = Integer.parseInt(bin.readLine());
int w = Integer.parseInt(bin.readLine());
int h = Integer.parseInt(bin.readLine());
Box b = new Box(l,w,h);
Rectangle r = new Rectangle(l,w);
System.out.println("Area of the Rectangle is :"+r.area());
System.out.println("Area of the Box is :"+b.area());
System.out.println("volume of the Rectangle is
:"+b.volume(l,w,h));
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
(b) Write a java program. 6M
int roll_no;
double m1, m2; Correct
Student(String name, int roll_no, double m1, double m2) Syntax
{ 3M,
this.name = name; Correct
this.roll_no = roll_no; logic 3M
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);
}
}
}
2. Attempt any TWO of the following: 16
(a) Write a program to create a class Account having variable accno, 8M
accname and balance. Define deposite ( ) and withdraw( )
methods. Create one object of class and perform the operation.
Ans. import java.io.*;
class Account
{
int accno;
String accname;
double balance, new_bal; Correct
Account(int accno, String accname, double balance) logic
{ 5M,
this.accno = accno; Correct
this.accname = accname; syntax
this.balance = balance; 3M
}
void deposite(double deposit_amount)
{
balance = balance+deposit_amount;
System.out.println("Your new available balance is"+balance);
}
void withdraw(double amount)
{
if(balance > amount)
{
balance = balance-amount;
System.out.println("Your current balance"+balance);
}
else if( balance == amount)
{
System.out.println("Your current balance is "+balance+". Your
System.out.println("Exception caught"+e);
}
}
}
(b) How multiple inheritance is achieved in java? Explain with 8M
proper program.
(Note: Any proper program should be considered)
Inheritance is a mechanism in which one object acquires all the
Ans. properties and behaviors of parent object. The idea behind inheritance
in java is that new classes can be created that are built upon existing Explana
classes. tion 3M
Multiple inheritance happens when a class is derived from two or
more parent classes. Java classes cannot extend more than one parent
classes, instead it uses the concept of interface to implement the
multiple inheritance.
It contains final variables and the methods in an interface are abstract.
A sub class implements the interface. When such implementation
happens, the class which implements the interface must define all the
methods of the interface. A class can implement any number of
interfaces.
Eg:
import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2; Example
Student(String name, introll_no, double m1, double m2) 5M
{ (Correct
this.name = name;
syntax
this.roll_no = roll_no;
this.m1 = m1;
2M,
this.m2 = m2; logic
} 3M)
}
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);
}
}
}
(c) Write an applet program that accepts two input, strings using 8M
<Param> tag and concatenate the strings and display it in status
window.
Ans. import java.applet.*;
importjava.awt.*; Correct
/*<applet code = AppletProgram.class height = 400 width = 400> logic
<param name = "string1" value = "Hello"> 5M,
<param name = "string2" value = "Applet">
Correct
</applet>*/
public class AppletProgram extends Applet
Syntax
{ 3M
String str1;
public void init()
{
str1 = getParameter("string1").concat(getParameter("string2"));
}
public void paint(Graphics g)
{
showStatus(str1);
}
}
3. Attempt any FOUR of following: 16
(a) How garbage collection is done in Java? Which methods are used 4M
for it?
Ans. Garbage collection is a process in which the memory allocated to Garbage
objects, which are no longer in use can be freed for further use. Collectio
Garbage collector runs either synchronously when system is out of n
memory or asynchronously when system is idle. Explana
In Java it is performed automatically. So it provides better memory tion:2M
management.
Syntax
(ii) getFont ( ): 1M,
public static Font getFont(String nm) Use- 1M
Returns a font from the system properties list.
Parameters: getFont
nm - the property name. method
:Syntax
public static Font getFont(String nm, Font font) - 1M,
Returns the specified font from the system properties list. Use - 1,
Parameters:
nm - the property name. Any one
font - a default font to return if property 'nm' is not defined. method
(e) Write a program that will count no. of characters in a file. 4M
(Note: Any Other Logic shall be considered)
Ans. import java.io.*;
class CountChars Logic :
{ 2M,
public static void main(String args[]) Syntax :
{ 2M
try
{
FileReader fr=new FileReader("a.txt");
int ch; int c=0;
while((ch=fr.read())!=-1)
{
c++; //increase character count
}
fr.close();
System.out.println(c);
}
catch(Exception e) {}
}
}
4. (A) Attempt any THREE of following: 12
(a) In what ways does a switch statement differ from an if 4M
statements?
Ans. Sr. Switch If
No.
1 The switch statement is The if statement is used to
used to select among select among two alternatives.
multiple alternatives
(b) Write a program to find the no. and sum of all integers greater 4M
than 100 and less than 200 that are divisible by 7.
(Note: Any other Logic shall be considered)
Ans.
class SumInt
{ Logic :
public static void main(String args[]) 2M,
{ Syntax :
double sum=0; 2M
int numcnt=0;
for(int i=101;i<200;i++)
{
if(i%7==0)
{
sum=sum+i;
numcnt++;
}
}
System.out.println(" No of elements : "+numcnt);
System.out.println(" Sum of elements : "+sum);
}
}
(c) What is synchronization? When do we use it? Explain 4M
synchronization of two threads.
(Note: Any other program shall be considered)
Ans. Synchronization :-
When two or more threads need access to a shared resource, they Synchro
need some way to ensure that the resource will be used by only one nization:
thread at a time. The process by which this is achieved is called 1M
synchronization.
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
{
ob1.t.join();
ob2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted ");
}
}
}
(d) Draw the hierarchy of Writer stream classes, and hierarchy of 4M
Reader stream classes.
Ans.
Correct
Hierarc
hy of
each
Class :
2M
// ...
}
ii) resume():
syntax : public void resume()
This method resumes a thread which was suspended using suspend()
method.
iii)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.
iv)notify():
syntax: public final void notify()
Notify() method wakes up the first thread that called wait() on the
same object.
v) stop():
syntax: void stop()
Used to kill the thread. It stops thread.
vi) wait():
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.
5. Attempt any TWO of following: 16
(a) Write a thread program for implementing the Runnable 8M
interface.
Ans. //program to print even numbers from 1 to 20 using Runnable Class
Interface class mythread implements Runnable impleme
{ nting
public void run() Runnabl
{ e 2M
System.out.println("Even numbers from 1 to 20 : ");
for(int i= 1 ; i<=20; i++) Correct
{ run()
if(i%2==0) method
System.out.print(i+ " "); 2M
}
} Proper
} use of
class test Thread
{ class 2M
public static void main(String args[])
{
mythreadmt = new mythread(); Correct
Thread t1 = new Thread(mt); Logic
t1.start(); and
} Syntax
} 2M
(b) Define an exception called No match Exception that is thrown 8M
when a string is not equal to MSBTE. Write program.
Ans. //program to create user defined Exception No Match Exception
import java.io.*;
class NoMatchException extends Exception For
{ subclass
NoMatchException(String s) of
{ Exceptio
super(s); n:2M
}
}
class test1 Correct
{ use of
public static void main(String args[]) throws IOException try and
{ catch:
BufferedReader br= new BufferedReader(new 2M
InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine(); Correct
try Logic:
{ 2M
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else Correct
System.out.println("Strings are equal"); syntax :
} 2M
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}
(c) Write a program to display a string concentric circles using 8M
font Arial size as 12 and style as bold + italic and display three
concentric circles with different colors on the applet.
Ans. //program to display three concentric circles filled in three colors.
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
String str=""; Use of
public void init() proper
{ methods
Font f= new Font("Arial",Font.BOLD|Font.ITALIC,12); for
setFont(f); displayi
} ng
public void paint(Graphics g) message
{ and
g.drawString("cocentric circles",130,100); circles:
3M
// for drawing three concentric circles filled with three colors.
g.setColor(Color.red); correct
g.fillOval(150,150,100,100); Logic:
2M
g.setColor(Color.yellow);
g.fillOval(160,160,80,80); Correct
Syntax :
g.setColor(Color.green); 2M
g.fillOval(170,170,60,60);
}
}
//Applet tag Applet
/*<Applet code=myapplet width=200 height=200> tag:1M
</Applet>
*/
6. Attempt any FOUR of the following: 16
(a) What is the use of new operator? Is it necessary to be used 4M
whenever object of the class is created? Why?
Ans.
1) Use :
new operator is used to dynamically allocate memory to the object of Use 2M
the class. It is the operator which is used to create usable instance of
the class.
It is generally used along with the constructor of the class so as to get
memory allocated to the object.
2) It is necessary to use new operator whenever an object requires Necessit
memory allocation after creation. Otherwise object in the form of y : 2M
reference is created which will point to Null, i.e. with no allocated
space in memory.
//Reversing password
StringBuffer s1= new StringBuffer(passwd);
System.out.println("Reverse of entered password :");
System.out.println(s1.reverse());
"+s1.append("Welcome"));
}
}
(c) What is : 4M
(i) AddElement() &
(ii) ElementAt() command in vector
Ans.
(i) addElement() : Each
It is a method from Vector Class. method
It is used to add an object at the end of the Vector. :2M
Syntax :
addElement(Object);
Example :
If v is the Vector object ,
v.addElement(new Integer(10));
It will add Integer object with value 10 at the end of the Vector object
v.
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 polygons 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