Java Model Answers UNIT WISE
Java Model Answers UNIT WISE
UNIT – II
UNIT – III
UNIT – IV
UNIT – V
UNIT – VI
22412
Important Instructions to examiners:
1) The answers should be examined by key words and not as word -to-word as given in the
model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may
try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give cr edit for principal components indicated in
the
figure. The figures drawn by candidate and model answer may vary. The examiner may
give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, th e assumed
constant
values may vary and there may be some difference in the candidate’s answers and model
answer.
6) In case of some questions credit may be given by judgement on part of examiner of
relevant
answer based on candidate’s understan ding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
Q.
No
. Sub
Q.N. Answer Marking
Scheme
1.
a)
Ans. Attempt any FIVE of the following:
List any eight features of Java.
Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic 10
2M
Any
eight
features
2M
b)
Ans. State use of finali ze( ) method with its syntax.
Use of finalize( ):
Sometimes an object will need to perform some action when it is 2M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 2 / 23
22412
destroyed. Eg. If an object holding some non java resources such as
file handle or window character font, then before the object is
garbage co llected these resources should be freed. To handle such
situations java provide a mechanism called finalization. In
finalization, specific actions that are to be done when an object is
garbage collected can be defined. To add finalizer to a class define
the finalize() method. The java run -time calls this method whenever it
is about to recycle an object.
Syntax:
protected void finalize() {
}
Use 1M
Syntax
1M
c)
1M for
each
method
d)
Any
four
types
½M
each
e)
Ans. Write the syntax of try -catch -finally blocks.
try{
//Statements to be monitored for any exception
} catch(ThrowableInstance1 obj) {
//Statements to execute if th is type of exception occurs
} catch(ThrowableInstance2 obj2) {
//Statements
}finally{ 2M
Correct
syntax
2M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 3 / 23
22412
//Statements which should be executed even if any exception happens
}
f)
Ans. Give the syntax of < param > tag to pass parameters to a n applet.
Syntax:
<param name=”name” value=”value”>
Example:
<param name=”color” value=”red”> 2M
Correct
syntax
2M
g)
Ans. Define stream class. List its types.
Definition of stream class:
An I/O Stream represents an input source or an output desti nation. A
stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs, and
memory arrays. Streams support many different kinds of data,
including simple bytes, primitive data types, localized charact ers, and
objects. Java’s stream based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, Writer.
Types
1M
2.
a)
Explana
tion 3M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 4 / 23
22412
byte code.
Diagr am
1M
b)
Explana
tion of
the two
types of
construc
tors 2M
Example
2M
22412
public static void main(String args[]) {
test1 t = new test1(); // default constructor is called.
[Link](t.i);
[Link](t.s);
[Link](t.b);
[Link] intln([Link]);
[Link]([Link]);
}
}
2. Constructor with no arguments: Such constructors does not have
any parameters. All the objects created using this type of constructors
has the same values for its datamembers.
Eg:
class Student {
int roll_n o;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
[Link]();
}
}
22412
name=n;
}
void display () {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
[Link]();
}
}
22412
System .[Link]("Area of First Second Rectangle : "+
([Link]*[Link] th));
}
}
c)
Ans. Explain the two ways of creating threads in Java.
Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending t he Thread class.
Thread class provide constructors and methods to create and perform
operations on a thread. This class implements the Runnable interface.
When we extend the class Thread, we need to implement the method
run(). Once we create an object, we can call the start() of the thread
class for executing the method run().
Eg:
class MyThread extends Thread {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread t = new MyThrea d();
[Link]();
}
}
a. By implementing the runnable interface.
Runnable interface has only on one method - run().
Eg:
class MyThread implements Runnable {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
[Link]();
} 4M
2M
each for
explaini
ng of
two
types
with
example
22412
}
d)
Ans. Distinguish between Input stream class and output stream class.
Java I/O (Input and Output) is used to process the input and produce
the output .
Java uses the concept of a stream to make I/O operation fast. The
[Link] package contains all the classes required for input and output
operations. A stream is a sequence of data. In Java, a stream is
composed of bytes.
Sr.
No. Input stream class Output stream class
1 Java application uses an
input stream to read data
from a source; Java application uses an output
stream to write data to a
destination;.
2 It may read from a file, an
array, peripher al device or
socket It may be a write to file, an
array, peripheral device or
socket
3 Input stream classes reads
data as bytes Output stream classes writes
data as bytes
4 Super class is the abstract
inputStream class Super class is the abstract
OutputS tream class
5 Methods:
public int read() throws
IOException
public int available()
throws IOException
public void close() throws
IOException
Methods:
public void write(int b) throws
IOException
public void write(byte[] b)
throws IOException
public void f lush() throws
IOException
public void close() throws
IOException
6 The different subclasses
of Input Stream are:
File Input stream,
Byte Array Input Stream,
Filter Input Stream,
Piped Input Stream,
Object Input Stream,
DataInputStream. The different sub classes of
Output Stream class are:
File Output Stream,
Byte Array Output Stream ,
Filter output Stream,
Piped Output Stream,
Object Output Stream,
DataOutputStream
4M
Any
four
points
for input
stream
class
and
output
stream
class 1M
each
22412
3.
a)
Correct
logic 4M
class B extends A
{
// overriding m1()
void m1() 4M
Explana
tion 2M
Example
2M
22412
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = ne w C();
22412
// calling B's version of m1()
ref.m1();
Example: [Link](10,10,50,50);
Each
method
1M
22412
(iv) getFamily ( ): The getfamily() metho d Returns the family of the
font.
String family = [Link]();
Where f is an object of Font class
d)
Ans. Write a program to count number of words from a text file using
stream classes.
(Note : Any other relevant logic shall be considered )
import [Link].*;
public class FileWordCount
{
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
if(c==(char)' ')
wc++;
}
[Link]("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
[Link]();
}
}
} 4M
Correct
program
4M
4.
a)
Ans.
Attempt any THREE of the following:
Describe instance Of and dot (.) operators in Java with suitable
example.
Instance of operator:
The java instance of operator is used to test whether the object is an
instance of the specified type (class or subclass or interface). 12
4M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 14 / 23
22412
The instance of in java is also known as type compa rison operator
because it compares the instance with type. It returns either true or
false. If we apply the instance of operator with any variable that has
null value, it returns false.
Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
[Link](s instance ofSimple1 );//true
}
}
Descript
ion and
example
of each
operator
2M
b)
Ans. Explain the four access specifiers in Java.
There are 4 types of java access modifiers:
1. private 2. default 3. Protected 4. public
Each
access
specifier
s 1M
22412
c)
Any
four
points
1M each
d)
Ans. Different iate between Java Applet and Java Application (any
four points)
Sr.
No. Java Applet Java Application
1 Applets run in web pages Applications run on stand -
alone systems.
2 Applets are not full
featured application
programs. Applications are full featured
programs.
3 Applets are the small
programs. Applications are larger
programs.
4 Applet starts execution
with its init(). Application starts execution
with its main ().
5 Parameters to the applet
are given in the HTML
file. Parameters to the application
are given at the command
prompt
6 Applet cannot access the
local file system and
resources Application can access the
local file system and
resources.
7 Applets are event driven Applications are control
driven.
4M
Any
four
points
1M each
22412
e)
Ans. Write a program to copy content of one file to another file.
class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("[Link]");
FileOutputStream out= new FileOutputStream("output .txt");
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
[Link](c);
}
[Link]("File copied to [Link]....");
}
finally
{
if(in!=null)
[Link]();
if(out!=null)
[Link]();
}
}
} 4M
Correct
logic 2M
Correct
Syntax
2M
5.
a)
Any 6
methods
with
their use
1M each
22412
boolean contains(Object elem) -Tests if the specified object is a
component in this vector.
void copyInto(Object[] anArray) -Copies the components of this
vector into the specified array.
Object firstElement() -Returns the first component (the item at
index 0) of this vector.
Object elementAt(int index) -Returns the component at the
specified index.
int indexOf(Object elem) -Searches for the first occurence of the
given argument, testing for equality using the equals method.
Object lastElement() -Returns the last component of the vector.
Object inser tElement At(Object obj,int index )-Inserts the specified
object as a component in this vector at the specified index.
Object remove(int index) -Removes the el ement at the specified
position in this vector.
void removeAllElements() -Removes all components from this
vector and sets its size to zero.
b)
Explana
tion 3M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 18 / 23
22412
/ A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]( "Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link] intln("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
Example
3M
22412
// obtain a reference of type A
A ref;
Output:
Inside A’s m1 method
Insid e B’s m1 method
Inside C’s m1 method
Explanation:
The above program creates one superclass called A and it’s two
subclasses B and C. These subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of
type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
C c = new C(); // object of type C
22412
c)
Creation
of two
threads
4M
Creating
main to
create
and start
objects
of 2
threads :
2M
6.
a)
Ans. Attempt any TWO of the following:
Explain the command lin e arguments with suitable example.
Java Command Line Argument:
The java command -line argument is an argument i.e. passed at the
time of running the java program. 12
6M
22412
The arguments passed from the console can be received in the java
program and it can be used as an input.
So, it provides a convenient way to check the behaviour of the
program for the different values. You can pass N (1,2,3 and so on)
numbers of arguments from the command prompt.
In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from
the command prompt.
class CommandLineExample
{
public static void main(String ar gs[]){
[Link]("Your first argument is: "+args[0]);
}
}
compile by > javac [Link]
run by > java CommandLineExample sonoo
4M for
explanat
ion
2M for
example
b)
Extende
d
Exceptio
n class
with
construc
tor 2M
22412
{
public static void main(String[] args) throws IOException
{
BufferedReaderbr= new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter Name of employee");
String name = [Link]();
[Link]("Enter S alary of employee");
int salary = [Link]([Link]());
Try
{
if(salary<0)
throw new NegativeSalaryException("Enter Salary amount
isnegative");
[Link]("Salary is "+salary);
}
catch (NegativeSalaryException a)
{
Syste [Link](a);
}
}
}
Acceptin
g data
1M
Throwin
g user
defining
Exceptio
n with
try catch
and
throw
3M
c)
Ans. Describe the applet life cycle in detail.
22412
start(): The start() method contains the actual code of the a pplet that
should run. The start() method executes immediately after
the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The
stop() method executes when the applet is minimized or when
moving from one tab to another in the browser.
paint(): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution
of start() method and whenever the applet or browser is resized.
The method execution sequence when an applet is executed is:
init()
start()
paint()
The method execution sequence when an applet is closed is:
stop()
destroy()
4M
descripti
on
22412
Important Instructions to examiners:
1) The answers should be examined by key words and not as word -to-word as given in the
model answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may
try
to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components i ndicated in
the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for anyequivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed
constant values may vary and th ere may be some difference in the candidate’s answers and
model answer.
6) In case of some question s credit may be given by judgement on part of examiner of
relevant
answer based on candidate’s understanding.
7) For programming language papers, credit may be giv en to any other program based on
equivalent concept.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi
and Bilingual (English + Marathi) medium is introduced at first year of AICTE diploma
Programme from academic year 2021 -2022. Hence if the students in first year (first and
second semesters) write answers in Marathi or bilingual language (English +Marathi), the
Examiner shall consider the same and assess the answer based on matching of concepts
with model answer.
Q.
No Sub
Q.N. Answer Marking
Scheme
1.
a)
Ans. Attempt any FIVE of the following:
Enlist the logical operators in Java.
&& : Logical AND
|| : Logical OR
! : Logical NOT 10
2M
1M each
Any two
operator s
b)
Ans. Give the syntax and exam ple for the following functions
i) min ( )
ii) Sqrt ( )
i) min()
Syntax: (Any one of the following)
static int min(int x, int y) Returns minimum of x and y
static long min(long x, long y) Returns minimum of x and y
static float min(float x, float y) Returns m inimum of x and y
static double min(double x, int y) Returns minimum of x and y 2M
1M for
each
functi on
with
example
22412
Example:
int y= [Link](64,45);
ii)Sqrt()
Syntax:
static double sqrt(double arg) Returns square root of arg.
Example:
double y= [Link](64);
c)
Ans. Define the interface in Java.
Interface is similar to a class.
It consist of only abstract methods and final variables.
To implement an interface a class must define each of the method
declared in the interface.
It is used to ac hieve fully abstraction and multiple inheritance in
Java. 2M
1M for
each point,
Any two
points
d)
Ans. Enlist any four inbuilt packages in Java .
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] 2M
½ M for
each
package
Any four
packages
e)
Ans. Explain any two methods of File Class
1. 1. boolean createNewFile(): It creates a new, empty file named by
this abstract pathname automatically, if and only if no file with the
same name exists.
if([Link]())
[Link]("A n ew file is successfully created.");
2M
1M for
each
method
Any two
methods
22412
4. 4. boolean isFile(): It returns True if the file denoted by the abstract
pathname is a normal fil e, and False if it is not a normal file.
[Link]("File size (bytes) : " + [Link]());
f)
Ans. Write syntax of elipse .
Syntax: void fillOval(int top, int left, int width, int height)
The filled ellipse is drawn within a bounding rectangle whose upper -
left corner is specified by top and left and whose width and height are
specified by width and height
OR
Syntax: void drawOval(int top, int left, int width, int height)
The empty ellipse is drawn within a bounding rectangle whose upper -
left corner is specified by top and left and whose width and height are
specified by width and height
2M
2M for
correct
syntax
g)
Ans. Enlist any four compile time errors .
1)Missing semicolon
2)Missing of brackets in classes and methods
3)Misspelling of variables and keywords.
4)Missing double quotes in Strings.
5)Use of undeclared variable.
6)Incompatible type of assi gnment/initialization.
7)Bad reference to object. 2M
½ M for
each error
Any four
can be
considered
22412
2.
a)
Ans. Attempt any THREE of the following:
Explain any four features of Java
[Link] Oriented:
In Java, everything is an Object. Java can be easily extended since it
is based on the Object model.
[Link] Independent:
Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code
is distributed over the web and interpreted by the Virtual Machine
(JVM) on whichever platform it is being run on.
[Link]:
Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
[Link]:
With Java's secure feature it enables to develop virus -free, tamper -
free systems. Authentication techniques are based on public -key
encryption.
[Link] -neutral:
Java compiler generates an architecture -neutral object file format,
which makes the compiled code executable on many processors, with
the presence of Java runtime system.
[Link]:
With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows
the devel opers to construct interactive applications that can run
smoothly.
1M for
each
feature
Any four
features
22412
b)
Ans. Write a Java program to copy the content of one file into another.
import [Link].*;
class filecopy
{
public static void main(String args[]) throws IOExceptio n
{
FileReader fr= new FileReader(“[Link]");
FileWriter fo= new FileWriter("[Link]");
int ch;
try
{
while((ch=[Link]())!= -1)
{
[Link](ch);
}
[Link](“file copied successfully”);
[Link]();
[Link]();
}
finally
{
if(fr!=null)
[Link]();
if(fo!=null)
[Link]();
}}}
4M
2M for
correct
logic,
2M for
code
c)
Ans. Write the difference between vectors and arrays . (any four
points)
[Link] Array Vector
1 An array is a structure
that holds multiple
values of the same
type. The Vect or is similar to array holds
multiple objects and like an array;
it contains components that can be
accessed using an integer index.
2 An array is a
homogeneous data type
where it can hold only
objects of one data type Vectors are heterogeneous. You
can h ave objects of different data
types inside a Vector. 4M
1M for
each point
Any four
points
22412
3 After creation, an array
is a fixed -length
structure The size of a Vector can grow or
shrink as needed to accommodate
adding and removing items after
the Vector has been created
4 Array can store
primitive type data
element. Vector are store non primitive type
data element.
5 Declaration of an array
int arr[] = new int [10]; Declaration of Vector:
Vector list = new Vector(3)
6 Array is the static
memory allocation. Vector is the dynamic memory
allocation
d)
catch:
Your code can catch this exception (using catch) and handle it in some
rational manner. System -generated exceptions are automatically
thrown by the Java runtime system. A catch block immediately
follows the try block. The catch block can have one or more
statements that are necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionT ype1
}
4M
1M for
each
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 7 / 26
22412
throw:
It is mainly used to throw an instance of user defined exception.
Example: throw new myException(“Invalid number”); assuming
myException as a user defined exception
finally:
finally block is a block that is used to execute importan t code such as
closing connection, stream etc. Java finally block is always executed
whether exception is handled or not. Java finally block follows try or
catch block.
Syntax:
finally
{
// block of code to be executed before try block ends
}
3.
a)
2M for
Program
logic
2M for
program
syntax
b)
Ans. Explain any four visibility controls in Java .
Four visibility control specifiers in Java are public, default, private
and protected. The visibility control in java can be seen when concept
of package is used with the java application.
1) private : The access level of a private speci fier is only within the
class. It cannot be accessed from outside the class.
2) default : When no s pecifier is used in the declaration, it is called as
default specification. Default scope for anything declared in java 4M
3M for
Explanatio
n
1M for
access
specificatio
n table
c)
Ans. Explain single and multilevel inheritance with proper example.
Single level inheritance:
In single inheritance, a single subclass extends from a single
superclass.
Example :
class A
{ 4M
1M for
each
explanatio
n
1M for
each
exampl e
22412
void display()
{
[Link](“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
[Link].p rintln(“In child class B”);
}
public static void main(String args[])
{
B b= new B();
[Link](); //super class method call
[Link](); // sub class method call
}
}
Note : any other relevant example can be considered.
Multilevel inheritance:
In multilevel inheritance, a subclass extends from a superclass and
then the same subclass acts as a superclass for another class.
Basically it appears as derived from a derived class.
Example:
class A
{
void display()
22412
{
[Link](“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
[Link](“In child class B”);
}
}
class C extends B //derived class C from B
{
public void print()
{
[Link](“In derived from derived class C”);
}
public static void main(S tring args[])
{
C c= new C();
[Link](); //super class method call
[Link](); // sub class method call
[Link](); //sub -sub class method call
}
}
Note : any other relevant example can be considered.
d)
Ans. Write a java applet to display the following output in Red color.
Refer Fig. No. 1 .
import [Link].*;
import [Link].*;
public class myapplet extends Applet 4M
2M for
correct
logic
22412
{
public void paint(Graphics g)
{
int x[]={10,200,70};
int y[]={ 10,10,100};
[Link]([Link]);
[Link] Polygon(x,y,3);
}
}
/*<applet code=myapplet height=400 width=400>
</applet>*/
2M for
correct
syntax
4.
a)
1M for
explanatio
n
switch case
statement
1M for
example
Example :
// Java Program to print day of week
// using the switch...case statement
class test1{
public static void main(String[] args) {
int number = 1;
String day;
switch (number)
{
case 1:
day = "Monday";
break;
case 2:
day= "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day= "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day= "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day= "Invalid day";
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 13 / 26
22412
[Link](day);
}
}
Note : an y other relevant example can be considered.
Conditional Operator:
The Conditional Operator is used to select one of two expressions for
evaluation, which is based on the value of the first operands. It is used
to handling simple situations in a line.
Syntax:
expression1 ? expression2:expression3;
The above syntax means that if the value given in Expression1 is true,
then Expression2 will be evaluated; otherwise, expression3 will be
evaluated.
Example
class test
{
public static void main(String[] args) {
String result ;
int a = 6, b = 12;
result = (a==b ? " equal ":"No t equal ");
[Link]("Both are "+result );
}
}
Note : any other relevant example can be considered.
1M for
explanatio
n
Conditiona
l operator
1M for
example
b)
Ans. Draw and explain life cycle of thread .
Life cycle of thread includes following states :
[Link]
2. Runnable
3. Running
4. Blocked
5. Dead
4M
22412
New – A new thread begins its life cycle in the new state. It is also
referred to as a born thread. This is the state where a thread has been
created, but it has not yet been started. A thread is started by calling
its start() meth od.
Blocked –This is the state when the thread is still alive but is currently
not eligible to run. This state can be implemented by methods such as
suspend() -resume(), wait() -notify() and sleep(time in ms).
Dead – This is the state when the thread is terminated. The thread is
in a running state and as soon as it is completed processing it is in a
“dead state”. Once a thread is in this state, th e thread cannot even run
again.
2M for
diagram
2M for
explanatio
n
c)
2M for
correct
logic
22412
{
int arr[] ={3 ,60,35,2,45,320,5};
[Link]("Array Before Bubble Sort");
for(int i=0; i<[Link]; i++)
{
[Link](arr[i] + " ");
}
[Link]();
int n = [Link];
int temp = 0;
for(int i=0; i< n; i ++)
{
for(int j=1; j < (n -i); j++)
{
if(arr[j -1] >arr[j])
{
//swap elements
temp = arr[j -1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
[Link]("Array After Bubble S ort");
for(int i=0; i<[Link]; i++)
{
[Link](arr[i] + " ");
}
}
}
2M for
correct
syntax
d)
Ans. Explain how to create a package and how to import it
To create package following steps can be taken:
1) Start the code by keyword „package ‟ followed by package name.
Example : package mypackage;
2) Complete the code with all required classes inside the package
with appropriate access modifiers.
3) Compile the code with „javac‟ to get .class file. 4M
3M
for steps to
create
22412
Example: javac [Link] to get [Link]
4) Create a folder which is same as package name and make sure
that class file of package is present inside it. If not, copy it inside
this folder.
To import the package inside any other program :
Make use of import statemen t to include package in your program.
It can be used with „*‟ to gain full access to all classes within package
or just by giving class name if just one class access is required.
Example :
import [Link];
or
importmypackage.*;
1M to
import
e)
Ans. Explain
i) drawLine
ii) drawOval
iii) drawRect
iv) drawArc
i) drawL ine(): It is a method from Graphics class and is used to draw
line between the points(x1, y1) and (x2, y2).
Syntax :
drawLine(int x1, int y1, int x2, int y 2)
1M for
each
22412
where f irst fourare x, y, width and height as in case of oval or rect.
The next two are start angle and sweep angl [Link] sweep angle is
positive, it moves in anticlockwise direction. It is given as negative, It
moves in clockwise direction .
5.
a)
package myPack;
import [Link];
public class Myclass {
//code
}
3M
Package
creation
(Note:
Code
snippet can
be used for
describing)
3M for
Example
22412
}
}
Examp le:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
[Link]("Volume is:"+(l*b*h));
}
}
Source file:
import [Link];
class volume {
public static void main(String args[])
{
Box b =new Box();
[Link]();
}}
(Note Any
other
similar
example
can be
considered
)
b)
Ans. Write a Java program in which thread A will displ ay the even
numbers between 1 to 50 and thread B will display the odd
numbers between 1 to 50. After 3 iterations thread A should go to
sleep for 500ms.
3M
Correct
program
with syntax
3M
Correct
logic
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 20 / 26
22412
c)
Ans. What is constructor? List types of constructor. Explain
parameterized constructor with suitable example.
Constructor:
A constructor is a special member whi ch 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 nume ric members to zero and other
types to null or spaces.
• Once defined, constructor is automatically called immediately after
the object is created before new operator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with no arguments or No-Arg Constructor or Non -
Parameterized constructor.
2M for
Definition
1M List
types
(Any 3 )
1M
parameteri
zed
constructor
2M
Example
(Any Other
Example
Can be
22412
public static void main(String a[])
{
Student s = new Student(20,"ABC"); // constructor
with parameters
[Link]();
}
} considere d
)
6.
a)
Ans. Attempt any TWO of the following:
Write a Java Program to count the number of words from a text
file using stream classes.
import [Link].*;
public class FileWordCount {
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;
3M
Correct
program
with syntax
3M
Correct
logic
b)
22412
Ans.
2) toUppercase():
Converts all of the characters in this String to upper case
Syntax: [Link]()
Example: String s="Sachin";
[Link]([Link]());
Output: SACHIN
3)trim ():
Returns a copy of the string, with leading and trailing whitespace
omitted.
Syntax: [Link]()
Example: String s=" Sachin ";
[Link]([Link]()); 1M each
Any 2
points
1M each
Any 4
Methods
correct
explanatio
n
22412
Output:Sachin
4)replace (): Returns a new string resulting from replacing all
occurrences of old Char in this string with new Char.
Syntax: [Link](‘x’,’y’)
Example: String s1="J ava is a programming language. Java is a
platform.";
String s2=[Link]("Java","Kava"); //replaces all occurrences of
"Java" to "Kava" [Link](s2);
Output: Kava is a programming language. Kava is a platform
5. length():
Syntax: int length()
It is used to return length of given string in integer.
Eg. String str=”INDIA”
[Link]([Link]()); // Returns 5
6. charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .
Eg. String s=”INDIA”
[Link]([Link](2) ); // returns D
7. substring():
Syntax:
String substring (int startindex)
startindex specifies the index at which the substring will [Link] will
returns a copy of the substring that begins at startindex and runs to the
end of the invoking string
Example:
[Link](("Welcome”.substring(3)); //come
(OR)
String substring(int startindex,int endindex)
Here startindex specifies the beginning index, and endindex specifies
the stopping point. The string returned all the c haracters from the
22412
beginning index, upto, but not including , the ending index.
Example :
[Link](("Welcome”.substring(3,5));//co
8. compareTo():
Syntax: int compareTo(Object o) or int compareTo(String
anotherString)
There are two variants of th is method. First method compares this
String to another Object and second method compares two strings
lexicographically.
Example. String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = [Link]( str2 );
[Link](result);
result = [Link]( str3 );
[Link](result);
c)
Ans. Write a Java applet to draw a bar cha rt for the following values .
import [Link].*;
import [Link].*;
2M for
Applet tag
2M for
22412
<param name=label4 value=2014>
<param name=Columns value=4>
</applet>
*/
setBackground(Color .yellow);
try {
int n = [Link](getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] = getParameter("label1");
label[1] = getParameter("label2");
label[2] = getParameter("label3");
label[3] = getPa rameter("label4");
value[0] = [Link](getParameter("c1"));
value[1] = [Link](getParameter("c2"));
value[2] = [Link](getParameter("c3"));
value[3] = [Link](getParameter("c4"));
}
catch(NumberFormatExcep tion e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++) {
[Link]([Link]);
[Link](label[i],20,i*50+30);
[Link]([Link]);
[Link](50,i*50+10,value[i],40);
} Syntax
2M
Correct
Logic
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2022 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 26 / 26
22412
}}
22412
21819
3 Hours / 70 Marks Seat No.
Instructions – (1) All Questions are Compulsory.
(2) Answer each next main Question on a new page.
(3) Figures to the right indicate full marks.
(4) Assume suitable data, if necessary.
(5) Use of Non-programmable Electronic Pocket
Calculator is permissible.
(6) Mobile Phone, Pager and any other Electronic
Communication devices are not permissible in
Examination Hall.
Marks
1. Attempt any FIVE of the following: 10
a) List any eight features of Java.
b) State use of finalize( ) method with its syntax.
c) Name the wrapper class methods for the following:
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
d) List the types of inheritances in Java.
e) Write the syntax of try-catch-finally blocks.
f) Give the syntax of < param > tag to pass parameters to an
applet.
g) Define stream class. List its types.
P.T.O.
22412 [ 2 ]
Marks
2. Attempt any THREE of the following: 12
a) Explain the concept of platform independence and portability
with respect to Java language.
b) Explain the types of constructors in Java with suitable example.
c) Explain the two ways of creating threads in Java.
d) Distinguish between Input stream class and output stream
class.
3. Attempt any THREE of the following: 12
a) Define a class student with int id and string name as data
members and a method void SetData ( ). Accept and display
the data for five students.
b) Explain dynamic method dispatch in Java with suitable
example.
c) Describe the use of following methods:
(i) Drawoval ( )
(ii) getFont ( )
(iii) drawRect ( )
(iv) getFamily ( )
d) Write a program to count number of words from a text file
using stream classes.
4. Attempt any THREE of the following: 12
a) Describe instance Of and dot ( . ) operators in Java with
suitable example.
b) Explain the four access specifiers in Java.
c) Differentiate between method overloading and method
overriding.
d) Differentiate between Java Applet and Java Application ( any
four points)
e) Write a program to copy content of one file to another file.
22412 [ 3 ]
Marks
5. Attempt any TWO of the following: 12
a) Describe the use of any methods of vector class with their
syntax.
b) Explain the concept of Dynamic method dispatch with suitable
example.
c) Write a program to create two threads. One thread will
display the numbers from 1 to 50 (ascending order) and other
thread will display numbers from 50 to 1 (descending order).
6. Attempt any TWO of the following: 12
a) Explain the command line arguments with suitable example.
b) Write a program to input name and salary of employee and
throw user defined exception if entered salary is negative.
c) Describe the applet life cycle in detail.
22412
Important Instructions to examiners:
1) The answers should be examined by key words and not as word -to-word as given in the
model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may
try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance
(Not applicable for subject English and Communication Skills).
4) While assessing figures, examiner may give cr edit for principal components indicated in
the
figure. The figures drawn by candidate and model answer may vary. The examiner may
give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, th e assumed
constant
values may vary and there may be some difference in the candidate’s answers and model
answer.
6) In case of some questions credit may be given by judgement on part of examiner of
relevant
answer based on candidate’s understan ding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
Q.
No
. Sub
Q.N. Answer Marking
Scheme
1.
a)
Ans. Attempt any FIVE of the following:
List any eight features of Java.
Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic 10
2M
Any
eight
features
2M
b)
Ans. State use of finali ze( ) method with its syntax.
Use of finalize( ):
Sometimes an object will need to perform some action when it is 2M
22412
destroyed. Eg. If an object holding some non java resources such as
file handle or window character font, then before the object is
garbage co llected these resources should be freed. To handle such
situations java provide a mechanism called finalization. In
finalization, specific actions that are to be done when an object is
garbage collected can be defined. To add finalizer to a class define
the finalize() method. The java run -time calls this method whenever it
is about to recycle an object.
Syntax:
protected void finalize() {
}
Use 1M
Syntax
1M
c)
Ans. Name the wrapper class methods for the following:
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
(i) To convert string objects to primitive int:
String str=”5”;
int value = [Link](str);
1M for
each
method
d)
Any
four
types
½M
each
e)
Ans. Write the syntax of try -catch -finally blocks.
try{
//Statements to be monitored for any exception
} catch(ThrowableInstance1 obj) {
//Statements to execute if th is type of exception occurs
} catch(ThrowableInstance2 obj2) {
//Statements
}finally{ 2M
Correct
syntax
2M
22412
//Statements which should be executed even if any exception happens
}
f)
Ans. Give the syntax of < param > tag to pass parameters to a n applet.
Syntax:
<param name=”name” value=”value”>
Example:
<param name=”color” value=”red”> 2M
Correct
syntax
2M
g)
Ans. Define stream class. List its types.
Definition of stream class:
An I/O Stream represents an input source or an output desti nation. A
stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs, and
memory arrays. Streams support many different kinds of data,
including simple bytes, primitive data types, localized charact ers, and
objects. Java’s stream based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, Writer.
Definitio
n 1M
Types
1M
2.
a)
22412
byte code.
Diagr am
1M
b)
Explana
tion of
the two
types of
construc
tors 2M
Example
2M
22412
public static void main(String args[]) {
test1 t = new test1(); // default constructor is called.
[Link](t.i);
[Link](t.s);
[Link](t.b);
[Link] intln([Link]);
[Link]([Link]);
}
}
2. Constructor with no arguments: Such constructors does not have
any parameters. All the objects created using this type of constructors
has the same values for its datamembers.
Eg:
class Student {
int roll_n o;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
[Link]();
}
}
22412
name=n;
}
void display () {
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
[Link]();
}
}
22412
System .[Link]("Area of First Second Rectangle : "+
([Link]*[Link] th));
}
}
c)
Ans. Explain the two ways of creating threads in Java.
Thread is a independent path of execution within a program.
There are two ways to create a thread:
1. By extending t he Thread class.
Thread class provide constructors and methods to create and perform
operations on a thread. This class implements the Runnable interface.
When we extend the class Thread, we need to implement the method
run(). Once we create an object, we can call the start() of the thread
class for executing the method run().
Eg:
class MyThread extends Thread {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread t = new MyThrea d();
[Link]();
}
}
a. By implementing the runnable interface.
Runnable interface has only on one method - run().
Eg:
class MyThread implements Runnable {
public void run() {
for(int i = 1;i<=20;i++) {
[Link](i);
}
}
public static void main(String a[]) {
MyThread m = new MyThread();
Thread t = new Thread(m);
[Link]();
} 4M
2M
each for
explaini
ng of
two
types
with
example
22412
}
d)
Ans. Distinguish between Input stream class and output stream class.
Java I/O (Input and Output) is used to process the input and produce
the output .
Java uses the concept of a stream to make I/O operation fast. The
[Link] package contains all the classes required for input and output
operations. A stream is a sequence of data. In Java, a stream is
composed of bytes.
Sr.
No. Input stream class Output stream class
1 Java application uses an
input stream to read data
from a source; Java application uses an output
stream to write data to a
destination;.
2 It may read from a file, an
array, peripher al device or
socket It may be a write to file, an
array, peripheral device or
socket
3 Input stream classes reads
data as bytes Output stream classes writes
data as bytes
4 Super class is the abstract
inputStream class Super class is the abstract
OutputS tream class
5 Methods:
public int read() throws
IOException
public int available()
throws IOException
public void close() throws
IOException
Methods:
public void write(int b) throws
IOException
public void write(byte[] b)
throws IOException
public void f lush() throws
IOException
public void close() throws
IOException
6 The different subclasses
of Input Stream are:
File Input stream,
Byte Array Input Stream,
Filter Input Stream,
Piped Input Stream,
Object Input Stream,
DataInputStream. The different sub classes of
Output Stream class are:
File Output Stream,
Byte Array Output Stream ,
Filter output Stream,
Piped Output Stream,
Object Output Stream,
DataOutputStream
4M
Any
four
points
for input
stream
class
and
output
stream
class 1M
each
22412
3.
a)
Correct
logic 4M
22412
for(i=0;i<5;i++)
{
arr[i].display();
}
}
}
b)
Ans. Explain dynamic method dispatch in Java with suitable example.
Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
When an overridden method is called through a su perclass
reference, Java determines which version (superclass/subclasses) of
that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is
made at run time.
At run -time, it depend s on the type of the object being referred to
(not the type of the reference variable) that determines which version
of an overridden method will be executed
A superclass reference variable can refer to a subclass object. This
is also known as upcasting. J ava uses this fact to resolve calls to
overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to through
a superclass reference variable, different ve rsions of the method are
executed. Here is an example that illustrates dynamic method
dispatch:
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1() 4M
Explana
tion 2M
Example
2M
class C extends A
{
// overriding m1()
void m1()
{
[Link]("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = ne w C();
22412
Example: [Link](10,10,50,50);
Each
method
1M
22412
(iv) getFamily ( ): The getfamily() metho d Returns the family of the
font.
String family = [Link]();
Where f is an object of Font class
d)
Ans. Write a program to count number of words from a text file using
stream classes.
(Note : Any other relevant logic shall be considered )
import [Link].*;
public class FileWordCount
{
public static void main(String are[]) throws IOException
{
File f1 = new File("[Link]");
int wc=0;
FileReader fr = new FileReader (f1);
int c=0;
try
{
while(c!= -1)
{
c=[Link]();
if(c==(char)' ')
wc++;
}
[Link]("Number of words :"+(wc+1));
}
finally
{
if(fr!=null)
[Link]();
}
}
} 4M
Correct
program
4M
4.
a)
Ans.
Attempt any THREE of the following:
Describe instance Of and dot (.) operators in Java with suitable
example.
Instance of operator:
The java instance of operator is used to test whether the object is an
instance of the specified type (class or subclass or interface). 12
4M
22412
The instance of in java is also known as type compa rison operator
because it compares the instance with type. It returns either true or
false. If we apply the instance of operator with any variable that has
null value, it returns false.
Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
[Link](s instance ofSimple1 );//true
}
}
Each
access
specifier
s 1M
22412
c)
Any
four
points
1M each
d)
Ans. Different iate between Java Applet and Java Application (any
four points)
Sr.
No. Java Applet Java Application
1 Applets run in web pages Applications run on stand -
alone systems.
2 Applets are not full
featured application
programs. Applications are full featured
programs.
3 Applets are the small
programs. Applications are larger
programs.
4 Applet starts execution
with its init(). Application starts execution
with its main ().
5 Parameters to the applet
are given in the HTML
file. Parameters to the application
are given at the command
prompt
6 Applet cannot access the
local file system and
resources Application can access the
local file system and
resources.
7 Applets are event driven Applications are control
driven.
4M
Any
four
points
1M each
Correct
logic 2M
Correct
Syntax
2M
5.
a)
Any 6
methods
with
their use
1M each
22412
boolean contains(Object elem) -Tests if the specified object is a
component in this vector.
void copyInto(Object[] anArray) -Copies the components of this
vector into the specified array.
Object firstElement() -Returns the first component (the item at
index 0) of this vector.
Object elementAt(int index) -Returns the component at the
specified index.
int indexOf(Object elem) -Searches for the first occurence of the
given argument, testing for equality using the equals method.
Object lastElement() -Returns the last component of the vector.
Object inser tElement At(Object obj,int index )-Inserts the specified
object as a component in this vector at the specified index.
Object remove(int index) -Removes the el ement at the specified
position in this vector.
void removeAllElements() -Removes all components from this
vector and sets its size to zero.
b)
Explana
tion 3M
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 2019 EXAMINATION
MODEL ANSWER
Subject: Java Programming Subject Code:
Page 18 / 23
22412
/ A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
[Link]( "Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
[Link] intln("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
Example
3M
22412
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
Output:
Inside A’s m1 method
Insid e B’s m1 method
Inside C’s m1 method
Explanation:
The above program creates one superclass called A and it’s two
subclasses B and C. These subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of
type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
C c = new C(); // object of type C
Creating
main to
create
and start
objects
of 2
threads :
2M
6.
a)
Ans. Attempt any TWO of the following:
Explain the command lin e arguments with suitable example.
Java Command Line Argument:
The java command -line argument is an argument i.e. passed at the
time of running the java program. 12
6M
22412
The arguments passed from the console can be received in the java
program and it can be used as an input.
So, it provides a convenient way to check the behaviour of the
program for the different values. You can pass N (1,2,3 and so on)
numbers of arguments from the command prompt.
Command Line Arguments can be used to specify configuration
inform ation while launching your application.
There is no restriction on the number of java command line
arguments.
You can specify any number of arguments
Information is passed as Strings.
They are captured into the String args of your main method
In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from
the command prompt.
class CommandLineExample
{
public static void main(String ar gs[]){
[Link]("Your first argument is: "+args[0]);
}
}
compile by > javac [Link]
run by > java CommandLineExample sonoo
4M for
explanat
ion
2M for
example
b)
Extende
d
Exceptio
n class
with
construc
tor 2M
22412
{
public static void main(String[] args) throws IOException
{
BufferedReaderbr= new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter Name of employee");
String name = [Link]();
[Link]("Enter S alary of employee");
int salary = [Link]([Link]());
Try
{
if(salary<0)
throw new NegativeSalaryException("Enter Salary amount
isnegative");
[Link]("Salary is "+salary);
}
catch (NegativeSalaryException a)
{
Syste [Link](a);
}
}
}
Acceptin
g data
1M
Throwin
g user
defining
Exceptio
n with
try catch
and
throw
3M
c)
Ans. Describe the applet life cycle in detail.
Below is the description of each applet life cycle method:
init(): The init() method is the first method to execute when the
applet is executed. Variable declaration and initialization operations 6M
2M
Diagram
22412
start(): The start() method contains the actual code of the a pplet that
should run. The start() method executes immediately after
the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The
stop() method executes when the applet is minimized or when
moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is
closed or when the tab containing the webpage is
closed. stop() metho d executes just before when destroy() method is
invoked. The destroy() method removes the applet object from
memory.
paint(): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution
of start() method and whenever the applet or browser is resized.
The method execution sequence when an applet is executed is:
init()
start()
paint()
The method execution sequence when an applet is closed is:
stop()
destroy()
4M
descripti
on
22412
11920
3 Hours / 70 Marks Seat No.
P.T.O. Instructions – (1) All Questions are Compulsory.
(2) Answer each next main Question on a new page.
(3) Illustrate your answers with neat sketches wherever
necessary.
(4) Figures to the right indicate full marks.
(5) Assume suitable data, if necessary.
(6) Mobile Phone, Pager and any other Electronic
Communication devices are not permissible in
Examination Hall.
Marks
1. Attempt any FIVE of the following: 10
a) Define constructor. List its types.
b) Define class and object.
c) List the methods of File Input Stream Class.
d) Define error. List types of error.
e) List any four Java API packages.
f) Define array. List its types.
g) List access specifiers in Java.
22412 [ 2 ]
Marks
2. Attempt any THREE of the following: 12
a) Differentiate between String and String Buffer.
b) Define a class circle having data members Pi and radius.
Initialize and display values of data members also calculate
area of circle and display it.
c) Define exception. State built-in exceptions.
d) Write a syntax and example of
(i) drawRect( )
(ii) drawoval( )
3. Attempt any THREE of the following: 12
a) Explain the following classes.
(i) Byte Stream Class
(ii) Character Stream Class
b) Explain life cycle of Applet.
c) Differentiate between class and interfaces.
d) Define type casting. Explain its types with syntax and
example.
4. Attempt any THREE of the following: 12
a) Explain life cycle of thread.
b) Describe final variable and final method.
c) Explain any two logical operators in Java with example.
d) Differentiate between array and vector.
e) List any four methods of string class and state the use of each.
22412 [ 3 ]
Marks
5. Attempt any TWO of the following: 12
a) Write a program to create vector with five elements as
(5, 15, 25, 35, 45). Insert new element at 2nd position.
Remove 1st and 4th element from vector.
b) Define packages. How to create user defined package?
Explain with example.
c) Write a program to create two threads one thread will print
even no. between 1 to 50 and other will print odd number
between 1 to 50.
6. Attempt any TWO of the following: 12
a) Explain how to pass parameter to an applet? Write an
applet to accept username in the form of parameter and
print “Hello <username>”.
b) Write a program to perform following task.
(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file.
c) Implement the following inheritance.
Interface : Salary
Basic_Salary
Basic_Sal ( )Class : Employee
Name, age
Display ( )
Class: Gross_Salary
TA, DA, HRA
Total_Sal ( )
1 | 24
Winter – 19 EXAMINATION
2 | 24
Ans Class : A class is a user defined data type which groups data
member s and its associated functions together.
Objec t: It is a basic unit of Object Oriented Programming and
represents the real life entities. A typical Java program creates
many objects, which as you know, interact by invoking methods. Definition 1
Mark each
c List the methods of File Input Stream Class. 2M
Ans • void close()
• int read()
• int read(byte[] b)
• read(byte[] b, int off, int len)
• int available() Any Two Each
for 1 Mark
d Define error. List types of error. 2M
Ans • Errors are mistakes that can m ake a program go wrong. Errors
may be logical or may be typing mistakes. An error may
produce an incorrect output or may terminate the execution of
the program abruptly or even may cause the system to crash.
Errors are broadly classified into two categorie s:
1. Compile time errors
2. Runtime errors Definition: 1m
List: 1m
e List any four Java API packages. 2M
Ans [Link]
[Link]
[Link]
[Link]
[Link]
[Link]
1/2 Marks for
one Package
f Define array. List its types. 2M
Ans An array is a homogeneous data type where it can hold only
objects of one data type.
Types of Array: Definition 1
Mark, List 1
Mark
3 | 24
1)One -Dimensional
2)Two -Dimensional
g List access specifiers in Java. 2M
Ans 1)public
2)private
3)friendly
4)protecte d
5)Private Protected Any 2, 1M for
each
Any 4 Points
4 Marks
b Define a class circle having data members pi and radius.
Initialize and display values of data members also calculate
area of circle and display it.
Ans class abc
{ correct
Program with
correct logic 4
Mark
float pi,radius;
abc(float p, float r)
{
pi=p;
radius=r;
}
void area()
{
float ar=pi*radius*radius;
[Link]("Area="+ar);
}
void display()
{
[Link]("Pi="+pi);
[Link]("Radius= "+radius);
}}
class area
{
public static void main(String args[])
{
abc a=new abc(3.14f,5.0f);
[Link]();
5 | 24
[Link]();
}
}
c Define exception. State built -in exceptions. 4M
Ans An exception is a pro blem that arises during the execution of a
program.
Java exception handling is used to handle error conditions in a
program systemati cally by taking the necessary action
Built -in exceptions:
• Arithmetic exception : Arithmetic error such as division by
zero .
• ArrayIndexOutOfBounds Exception : Array index is out
of bound
• ClassNotFoundException
• FileNotFoundException : Caused by an attempt to access
a nonexistent file .
• IO Exception : Caused by general I/O failures, such as
inability to read from a file .
• NullPointerE xception : Caused by referencing a null object .
• NumberFormatException : Caused when a conversion
between strings and number fails.
• StringIndexOutOfBoundsException : Caused when a
program attempts to access a nonexistent character position
in a string .
• OutOfMe moryException: Caused when there’s not
enough memory to allocate a new object .
• SecurityException: Caused when an applet tries to perform
an action not allowed by the browser’s security setting .
• StackOverflowException: Caused when the system runs out
of sta ck space . Definition 2
Marks, List: 2
Marks
d Write syntax and example of : 4M
6 | 24
1) drawRect()
2)drawOval()
Ans 1)drawRect() :
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: [Link](10,10,60,50);
2) drawOval( ) : Drawing Ellipses and circles: To draw an
Ellipses or circles used drawOval () me thod can b e used.
Syntax: void drawOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper -
left corner is specified by top and left and whose width and
height are specified by width and height to draw a circle o r filled
circle, specify the same width and height the following program
draws several ellipses and circle.
Example: [Link](10,10,50,50); drawRect:
2Marks,
drawOval: 2
Marks
7 | 24
8 | 24
start( ) :The start( ) method is called after init( ) .It is also called
to restart an applet after it has Been stopped. Whereas init( ) is
called once —the first time an applet is loaded —start( ) is called
each time an applet’s HTML document is displayed onscreen.
9 | 24
7)syntax
Class classname
{
Variable declaration,
Method declaration
} 7)syntax
Inteface Innterfacename
{
Final Variable declaration,
abstract Method declaration
}
d Define type casting. Explain its types with syntax and example. 4M
Ans 1. The process of converting one data type to another is called
casting or type casting.
2. If the two types are compatible, then java will perform the
conversion a utomatically.
3. It is possible to assign an int value to long variable.
4. However, if the tw o types of variables are not compatible, the
type conversions are not implicitly allowed, hence the need for
type casting.
There are two types of conversion:
[Link] type -casting:
[Link] type -casting:
10 |
24
output:
f = 3.0
Widening Conversion :
The rule is to promote the smaller type to bigger type to prevent
loss of precision, known as Widening Conversion .
2. Explicit type -casting:
• Explicit type -casting performed via a type -casting
operator in the prefix form of ( new-type) operand.
• Type -castin g forces an explicit conversion of type of a
value. Type casting is an operation which takes one
operand, operates on it and returns an equivalent value in
the specified type.
Syntax:
newValue = (typecast)value;
Example:
double f = 3.5;
int i;
i = (int)f; // it cast double value 3.5 to int 3.
Narrowing Casting: Explicit type cast is requires to Narrowing
conversion to inform the compiler that you are aware of the
possible loss of precision.
11 |
24
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.
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 sta te it can be scheduled for running
by start() or killed by stop(). If put in a queue it moves to
runnable state.
Runnable State : It means that thread is ready for execution and
is waiting for the availability of the processor i.e. the thread has
joined the queue and is waiting for execution. If all threads have
equal priority, then they are given time slots for execution in
round robin fashion. The thread that relinquishes control joins
the queue at the end and again waits for its turn. A thread can
relinqu ish the control to another before its turn comes by yield(). 2M for
diagram,2M for
explanation
12 |
24
Running State: It means that the processor has given its time to
the thread for execution. The thread runs until it relinquishes
control on its own or it is pre -empted by a higher priority thread .
Blocked state : A thread can be temporarily suspended or
blocked from entering into the runnable and running state by
using either of the following thread method.
1) suspend() : Thread can be suspended by this method. It
can be rescheduled by resume().
2) wait( ): If a thread requires to wait until some event
occurs, it can be done using wait method and can be
scheduled to run again by notify().
3) sleep(): We can put a thread to sleep for a specified time
period using sleep(time) where time is in ms. It re -enters
the runnable state as soon as period has elapsed /over
Dead State : Whenever we want to stop a thread form running
further we can call its stop().The statement causes the thread to
move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop
method may be used when the premature death is required.
b Describe final variable and final method. 4M
Ans Final method : making a method final ensures that the
functionality def ined in this method will never be altered in any
way, ie a final method cannot be overridden.
Syntax:
final void findAverage()
{
//implementation
}
Example of declaring a final method:
class A
{ 2M for
definition,2M for
example
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
13 |
24
final void show()
{
[Link](“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
[Link](“in show of B”);
}}
Final variable : the value of a final variable cannot be changed.
Final variable behaves l ike class variables and they do not take
any space on individual objects of the class.
Example of declaring final variable: final int size = 100;
c Explain any two logical operator in java with example. 4M
Ans Logical Operators: Logical operators are used when we want to
form compound conditions by combining two or more relations.
Java has three logical operators as shown in table:
Operator Meaning
&& Logical
AND
|| Logical
OR
! Logical
NOT
Program demonstrating logical Operators
public class Test 2M for each
operator with eg.
Array Vector
1) An array is a structure that
holds multiple values of the
same type. 1)The Vector is similar to
array holds multiple objects
and like an array; i t contains
components that can be
accessed using an integer
index. any four points
1m for each point
15 |
24
2) An array is a homogeneous
data type where it can hold
only objects of one data type. 2) Vectors are heterogeneous.
You can have objects of
different data types insi de a
Vector.
3) Afte r creation, an array is a
fixed -length structure . 3) The size of a Vector can
grow or shrink as needed to
accommodate adding and
removing items after the
Vector has been created.
4) Array can store primitive
type data element. 4) Vect or are store non -
prim itive type data element.
5)Declaration of an array :
int arr[] = new int [10]; 5)Declaration of Vector:
Vector list = new Vector(3);
6) Array is the static memory
allocation. 6) Vector is the dynamic
memory allocation.
e List any four methods of string class and state the use of
each. 4M
Ans The [Link] class provides a lot of methods to work on
string. By the help of these methods,
We can perform operations on string such as trimming,
concatenating, conver ting, comparing , replacing strings etc.
1) to Lowercase ( ): Converts all of the characters in this String
to lower case.
Syntax: [Link]()
Example: String s="Sachin" ;
[Link]([Link]());
Output: sachin
2)to Uppercase(): Converts all of the characters in this String to
upper case any four methods
of string class
can be
consider ed
16 |
24
Syntax: [Link]()
Example:
String s="Sachin";
[Link]([Link]());
Output: SACHIN
3) trim ( ): Returns a copy of the string, with leading and trailing
whitespace omitted.
Syntax: [Link]( )
Example:
String s=" Sachin ";
[Link]([Link]());
Output:Sachin
4) replace ( ):Returns a new string resulting from replacing all
occurrences of old Char in this string with new Char.
Syntax: [Link](‘x’,’y’)
Example:
String s1="Java is a prog ramming language. Java is a platform.";
String s2=[Link]("Java","Kava"); //replaces all occurrences
of "Java" to "Kava"
[Link](s2);
Output: Kava is a programming language. Kava is a platform.
17 |
24
Ans import [Link].*;
class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector();
[Link](new Integer(5));
[Link](new Integer(15));
[Link](new Integer(25));
[Link](new Integer(35));
[Link](new Integer(45));
[Link]("Original array elements are
");
for(int i=0;i<[Link]();i++)
{
[Link]([Link](i)) ;
}
[Link](new Integer(20),1); // insert
new element at 2nd position
[Link](0);
//remove first element
[Link](3);
//remove fourth element
[Link]("Array elements after insert
and remove operation " );
for(int i=0;i<[Link]();i++)
{
[Link]([Link](i));
}}} (Vector creation
with elements – 2
M,
Insert ne w
element – 2M,
Remove elements
2 M,
18 |
24
which classes are stored.
The syntax for defining a 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 pack ages. 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 mus t match with the
package name exactly. A hierarchy can be created by separating
package name and sub pa ckage name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as
pkg1 \pkg2 \pkg3.
Syntax:
To access package In a Java source file, import statements
occur immediately following the package statement (if
it exists) and before any class d efinitions.
Syntax:
import pkg1 [.pkg2 ].(classname |*);
Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
[Link]("Volume is:"+(l*b*h));
}
}
Source file:
import [Link];
class volume
{
Package creation
- 2M
Example - 3M
19 |
24
public static void main(String args[])
{
Box b=new Box();
[Link]();
}
}
c Write a program to create two threads one th read will print
even no. between 1 to 50 and other will print odd number
between 1 to 50. 6M
Ans import [Link].*;
class Even extends Thread
{
public void run()
{
try
{
for(int i=2;i<=50;i=i+2)
{
[Link](" \t Even thread :"+i);
sleep(500);
}
}
catch(InterruptedException e)
{[Link]("even thread interrupted");
}
}
}
class Odd extends Thread
{
public void run()
{
try
{
for(int i=1;i<50;i=i+2)
{
[Link](" \t Odd thread :"+i);
sleep(500); Creation of two
threads 4M
Creating main to
create and start
objects of 2
threads: 2M
20 |
24
}
}
catch(InterruptedException e)
{[Link]("odd thread interrupted");
}
}
}
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}
Correct Program
– 3M
21 |
24
2. Provide code in the applet to parse these parameters. The
Applet access their attributes using the getParameter method.
The sy ntax is : String getParameter(String name);
Program
import [Link].*;
import [Link].*;
public class hellouser ext ends Applet
{
String str;
public void init()
{
str = getParameter("username");
str = "Hello "+ str;
}
public void paint(Graphics g)
{
[Link](str,10,100);
}
}
<HTML>
<Applet code = [Link] width = 400 height = 400>
<PARAM NAME = "username" V ALUE = abc> </Applet>
</HTML>
(OR)
import [Link].*;
import [Link].*;
/*<Applet code = [Link] 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;
}
22 |
24
public void pain t(Graphics g)
{
[Link](str,10,100);
}
}
23 |
24
}
c Implement the following inheritance
6M
Ans interface Salary
{
double Basic Salary =10000.0;
void Basic Sal ();
}
class Employee
{
String Name;
int age;
Employee(String n, int b)
{
Name=n;
age=b;
}
void Display()
{
[Link]("Name of Employee
:"+Name);
[Link]("Age of Employee :"+age);
}
}
class Gross_Salary extends Employee implements Salary
{
double HRA,TA,DA;
Gross_Salary(String n, int b, dou ble h,double t,double d)
{
super(n,b);
HRA=h;
(Interface: 1M,
Employee class:
2M,
Gross_ Salary
class: 3M)
24 |
24
TA=t;
DA=d;
}
public void Basic_Sal()
{
[Link]("Basic Salary
:"+Basic_Salary);
}
void Total_Sal()
{
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
[Link]("Total Salary :"+Total_Sal);
}
}
class EmpDetails
{ public static void main(String args[])
{ Gross_Salary s=new
Gross_Salary("Sachin",20,1000,2000,7000);
s.Total_Sal();
}
}
(Any other logic
considered)
default (Friendly)
protected
private protected
c) Explain constructor with suitable example. 2 M
Ans Constructors are used to assign initial value to instance variable of the class.
It has the same name as class name in which it resides and it is syntactically similar
to any method.
Constructors do not have return value, not even ‘void’ because they return the instance
if
class.
Constructor called by new operator.
Example:
class Rect
{
int length, breadth;
Rect() //constructor
{
length=4; breadth=5;
}
public static void main(String args[])
{
Rect r = new Rect();
[Link](“Area : ” +([Link]*[Link]));
}
}
Output : Area : 20 1M-
Explanation
1M-
Example
d) List the types of inheritance which is supported by java. 2 M
Ans
Any two
1 M each
1M -2ways
to create
thread
f) Distinguish between Java applications and Java Applet (Any 2 points) 2 M
Ans
Applet Application
Applet does not use main()
method for initiating execution of
code Application use main() method
for initiating execution of code
Applet cannot run independently Application can run
independently
Applet cannot read from or write
to files in local com puter Application can read from or
write to files in local computer
Applet cannot communicate with
other servers on network Application can communicate
with other servers on network
Applet cannot run any program
from local computer. Application can run any program
from local computer.
Applet are restricted from using
libraries from other language
such as C or C++ Application are not restricted
from using libraries from other
language
Applets are event driven. Applications are control driven.
1 M for
each point
(any 2
Points)
g) Draw the hierarchy of stream classes. 2 M
Ans
b) Define a class employee with data members 'empid , name and salary.
Accept data for three objects and display it 4 M
Ans class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader([Link]));
[Link]("Enter Emp number : ");
empid=[Link]([Link]());
[Link]("Enter Emp Name : ");
name=[Link]();
[Link]("Enter Emp Salary : ");
salary=[Link]([Link]());
}
void show()
{
[Link]("Emp ID : " + empid);
[Link](“Name : " + name);
[Link] ntln(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3; i++)
{
e[i] = new employee(); e[i].getdata();
}
[Link](" Employee Details are : ");
for(inti=0; i<3; i++)
e[i].show();
}
}
4M (for
correct
program
and logic)
2) Runnable State
It means that thread is ready for execution and is waiting for the availability of the
processor i.e. the thread has joined the queue and is waiting for execution. If all
threads have equal priority, then they are given time slots for execution in round
robin fashion. The thread that relinquishes control joins the queue at the end and
again waits for its turn. A thread can relinquish the control to another before its turn
comes by yield().
Runnable runnable = new NewState();
Thread t = new Thread(runnable ); [Link]();
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.
bytes.
Ans
Data Type Size
Byte 1 Byte
Short 2 Byte
Int 4 Byte
Long 8 Byte
Double 8 Byte
Float 4 Byte
Char 2 Byte
boolean 1 Bit Data type
name, size
and default
value and
description
carries 1 M
b) Write a program to add 2 integer, 2 string and 2 float values in a vector.
Remove the element specified by the user and display the list. 4 M
Ans import [Link].*;
import [Link].*;
import [Link].*;
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");
Float s7=new Float(1.1f);
Float s8=new Float(1 .2f);
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
[Link](s7);
[Link](s8);
[Link](v);
[Link](s2);
[Link](4);
[Link](v);
}
} Correct
program - 4
M, stepwise
can give
marks
c) Devel op a program to create a class ‘ Book’ having data members author, title
and price. Derive a class 'Booklnfo' having data member 'stock position ’ and 4 M
[Link]();
[Link]();
}
}
OUTPUT
Book Details:
Title: Complete Reference
Author: Herbert Schildt
Publisher: ABC Publication
Price: 2359.5
Stock Available: 10
Book Details:
Title: system programming
Author: Ulman
Publisher: XYZ Publication
Price: 359.5
Stock Available: 20
Book Details:
Title: Software Engg
Author: Pressman
Publisher: Pearson Publication
Price: 879.5
Stock Available: 15
d) Mention the steps to add applet to HTML file. Give sample code. 4 M
Ans Adding Applet to the HTML file:
Steps to add an applet in HTML document
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the body section
of HTML
file.
2. Specify the name of the applet’s .class file.
3. If the .class file is not in the current directory then use the codebase parameter to
specify: -
a. the relative path if file is on the local system, or
b. the uniform resource locator(URL) of the directory containing the file if it is on a remote
computer.
4. Specify the space required for display of the applet in terms of width and height in
pixels.
5. Add any user -defined parameters using <param> tags
6. Add alternate HTML text to be displayed when a non -java browser is used.
7. Close the applet declaration with the </APPLET> tag.
Open notepad and type the following source code and save it into file nam e Steps – 2M
Example –
2M
“[Link]”
import [Link].*;
import [Link].*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
[Link]("Hello Java",10,100);
}}
Use the java compiler to compile the applet “[Link]” file.
C:\jdk> javac H [Link]
After compilation “[Link]” file will be created. Executable applet is nothing but
the .class file
of the applet, which is obtained by compiling the source code of the applet. If any error
message is
received, then check the errors, c orrect them and compile the applet again.
We must have the following files in our current directory.
o [Link]
o [Link]
o [Link]
If we use a java enabled web browser, we will be able to see the entire web page containing
the
applet.
We have included a pair of <APPLET..> and </APPLET> tags in the HTML body section.
The
<APPLET…> tag supplies the name of the applet to be loaded and tells the browser how
much space
the applet requires. The <APPLET> tag given below specifies the minimum requirements
to place the
HelloJava applet on a web page. The display area for the applet output as 300 pixels width
and 200
pixels height. CENTER tags are used to display area in the center of the screen.
<APPLET CODE = [Link] WIDTH = 400 HEIGHT = 200 > </APPLET>
Example: Adding applet to HTML file:
Create [Link] file with following code:
<HTML>
<! This page includes welcome title in the title bar and displays a welcome message. Then
it specifies
the applet to be loaded and executed.
>
<HE AD> <TITLE> Welcome to Java Applet </TITLE> </HEAD>
<BODY> <CENTER> <H1> Welcome to the world of Applets </H1> </CENTER> <BR>
<CENTER>
Sr.
No. Array Vector
1 An array is a structure that holds
multiple values of the same type. The Vector is similar to array holds
multiple objects and like an array; it
contains components that can be
accessed using an integer index.
2 An array is a homogeneous data type
where it can hold only objects of one
data type. Vectors are heterogeneous. You can
have objects of different data types
inside a Vector.
3 After creation, an array is a fixed -
length structure. The size of a Vector can grow or shrink
as needed to accommodate adding and
removing items after the Vector has
been created.
4 Array can store primitive type data
element. Vector are store non -primitive type data
element
5 Array is unsynchronized i.e.
automatically increase the size when
the initialized size will be exceed. Vector is synchronized i.e. when the
size will be exceeding at the time;
vector size will increase double of
initial size.
6 Declaration of an array :
int arr[] = new int [10]; Declaration of Vector:
Vector list = new Vector(3);
7 Array is the static memory allocation. Vector is the dynamic memory
allocation
8 Array allocates the memory for the
fixed size ,in array there is wastage of
memory. Vector allocates the memory
dynamically means according to the
requirement no wastage of memory.
9 No methods are provided for adding
and removing elements. Vector provides methods for adding and
removing elements.
10 In array wrapper classes are not used. Wrapper classes are used in vector
11 Array is not a class. Vector is a class.
elementAT( ):
The elementAt() method of Java Vector class is used to get the element at the specified
4 M for
any 4
correct
points
1 M for
elementAt()
1 M for
addElement
()
index in the vector. Or The elementAt() method returns an element at the specified index.
addElement( ):
The addElement() method of Java Vector class is used to add the specified element to the
end of this vector. Adding an element increases the vector size by one.
b) Write a program to create a class 'sa lary with data members empid', ‘name'
and ‘ basicsalary'. Write an interface 'Allowance ’ which stores rates of
calculatio n for da as 90% of basic salary, hra as 10% of basic salary and pf as
8.33% of basic salary. Include a method to calculate net salary and display i t. 6 M
Ans interface allowance
{
double da=0.9*basicsalary;
double hra=0.1*basicsalary;
double pf=0.0833*basicsalary;
void netSalary();
}
class Salary
{
int empid;
String name;
float basicsalary;
Salary(int i, String n, float b)
{
empid=I;
name=n;
basicsalary =b;
}
void display()
{
[Link]("Empid of Emplyee="+empid);
[Link]("Name of Employee="+name);
[Link]("Basic Salary of Employee="+ basicsalary);
}
}
super(i,n,b);
ta=t;
}
void disp()
{
display();
[Link]("da of Employee="+da);
}
public void netsalary()
{
double net_sal=basicsalary+ta+hra+da;
[Link]("netSalary of Employe e="+net_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
net_salary s=new net_salary(11, “abcd”, 50000);
[Link]();
[Link]();
}
}
c) Define an exception called 'No Match Exception' that is thrown when the
passward accepted is not equal to "MSBTE'. Write the program. 6 M
Ans import [Link].*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader([Link]) );
[Link]("Enter a word:");
String str= [Link]();
try
{ 6 M for
correct
program
if([Link](l)==[Link](r))
{
l++;
r--;
}
else
{
flag=0;
break;
}
}
if(flag==1)
{
[Link]("palindrome");
}
else
{
[Link]("not palindrome");
}
}
}
b) Define thread priority ? Write default priority values and the methods to set
and change them. 6 M
Ans 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.
Default priority v alues as follows 2 M for
define
Thread
priority
2 M for
2 M for
method to
set and
change
}
c) Design an applet to perform all arithmetic operations and display the result by using
labels. textboxes and buttons. 6 M
Ans import [Link].*;
import [Link].*;
public class sample extends Frame implements ActionListener {
Label l1, l2,l3;
TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;
sample() {
l1=new Lable(“First No.”);
[Link](10, 10, 50, 20);
tf1 = new TextField();
[Link](50, 50, 150, 20);
l2=new Lable(“Second No.”);
[Link](10, 60, 50, 20);
tf2 = new TextField();
[Link](50, 100, 150, 20);
l3=new Lable(“Result”);
[Link](10, 110, 150, 20);
tf3 = new TextField();
[Link](50, 150, 150, 20);
[Link]( false );
b1 = new Button("+");
[Link](50, 200, 50, 50);
b2 = new Button(" -");
[Link](120,200,50,50);
b3 = new Button("*");
[Link](220, 200, 50, 50);
b4 = new Button("/");
[Link](320,200,50,50);
[Link]( this);
[Link]( this);
[Link]( this);
[Link]( this);
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(b4); 6 M for
correct
program