Subject Name: Java Programming 22412
Important instructions to examiners:
1). The answers should be examined by key words and nat as ward-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 Skil.
4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn,
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
there may be some difference in the candidate's answers and model answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
candidate's understanding,
7) For programming language papers, credit may be given to any other program based on equivalent concept.
8) As per the policy decision of Maharashtra State Gavernment, 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
Q. | Sub Answer Marking
No] Q. Scheme
2 [N
1 ‘Attempt any FIVE of the following: 10M
a) | Define the terms with example. 2M
i) Class
i) Object
‘Ans [2] Class: Class is a set of object, which shares common characteristics) behavior and | 1 M forany
common properties! attributes. suitable class
definition
and 1 M for
ii) Object: It is a basic unit of Object-Oriented Programming and represents real-life | any suitable
entities. object
definition
Example
class Student
{
int id;
String name:
Page No: 1 | 26MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
‘Autonomous)
27001 - 2013 Certified)
usome
public static void main(String args{])
{
Student si=new Student(); _//ereating an object of Student
1
In this example, we have created a Student class which has two data members id and
name. We are creating the object of the Student st. by new keyword.
}) _ | Enlist any two access specifier with syntax. 2M
‘Ans | There are 5 types of java access specifier: List any 2
+ public access
+ private specifiers -
© default (Friendly) .
+ protected
+ private protected
©) _ | Give a syntax to create a package and accessing package in java. 2M
“Ans | To Create a package follow the steps given below: syntax to
create a
+ Choose the name of the package Package! M
+ Include the package command as the first line of code in your Java Source File.
accessing
+ The Source file contains the classes, interfaces, ete. you want to include in the
package
+ Compile to create the Java packages
Syntax to create a package:
package nameOfPackage:
Example:
package pl:
Accessing Package:
* Package can be accessed using keyword import.
# There are 2 ways to access java system packages:
© Package can be imported using import keyword and the wild card(*) but
drawback of this shortcut approach is that itis difficult to determine from
which package a particular member name.
Syntax: import package_name.*
package-1 M
Page No: 2 | 26MAHARASHTRA STATE HOARD OF TECHNICAL EDUCATION
‘Autonomous)
USOMEC - 27001 = 2018 Certitied)
a
Ans
°
Ans
For e.g, import java.lang.*;
‘© The package can be accessed by using dot(.) operator and can be terminated
using semicolon(;)
Syntax: import packagel.package2.classname;
Give a syntax of following thread method 2M
i) Notify)
ii) Sleep)
i) notify() Syntax of
notify( )-1 M
The notify() method of thread class is used to wake up a single thread. This method gives,
the notification for only one thread which is waiting for a particular object. and
Syntax: public final void notify(), sleep ()-I M
ii) sleep()
Sleep() causes the current thread to suspend execution fora specitied period,
Syntax: publie static void sleep(long milliseconds)
Give a syntay of (param) tag to pass parameters to an applet. 2M
User-define Parameter can be applied in applet’ using
tags. Syntax of
short —> int —> long 5 float —> double
Fore.g.
class widening
{
public static void main(String arg{])
int i= 100;
long I-1;
float
System.out.printhn(“Int value is"+i);
System.out.priniln(“Long value is");
System.out printin(“Float value is");
)
)
Narrowing (Explicit)
# The process of assigning a larger type into a smaller one is called narrowing.
+ Casting into a smaller type may result in loss of data.
+ double —> long —> int —> short —> byte
Fore.g.
class narrowing
Public static void main(String{])
Double d=100.04;
Long I-(long) d;
Int i=(int) |;
type casting-
IM
Types of
type
casting-1 M
Example-2
M
(1M for
each
example)
Page No: 5 | 26MAHARASHTRA STW
HOARD OF TECHNICAL
‘Autonomous)
7001 = 2013 Certified)
some
System.out printin(“Int value is”);
System.out printin( “Long value is”);
System.out.printin(“Float value
b) _| Differentiate between String and String Buffer Class. (any four points) 4M
“Ans String class StringBuffer class Any 4+
5 I SiringBulk Tass of Si coneet
ring isa major cass iringBufleris a pear class of String points M
Tengih is fixed (immutable) Tengih is Hexible (mutable)
Contenis of object cannot be modified — | Contents of object can be modified
‘Object can be created by Objects ean be created by calling
assigning String constants constructor of StringBuffer class using
enclosed in double quotes. “new"
Methods of string class: toLowerCase(), | Methods of StringBuffer class seiCharAtO,
toUipperCase( replace), equals), append), insert) append) reverse)
length), charAi(), concat(), substring), | delete()
compareTo()
Exs= String saber Ex SiringBuller ssnew SirimgBulfer
abe"),
©) _| Writea program fo create a user defined exception in java, aM
‘Ans | Following example shows a user defined exception as Invalid Age’, if age entered by | For any
the user is less than eighteen, Correct
import java.lang. Exception;
import java.io.*
class myException extends Exception
{
myException(String msg)
super(msg):
}
}
class agetest
public static void main(String argsf])
BufferedReader br-new BufferedReader(new InputStreamReader(System.in));
/)Scanner class is also valid
ty
{
System.out.println("enter the age :");
int n=Integer-parselnt(br.readL ine()):
ifn < 18)
throw new myException( "Invalid Age"); //user defined exception
program-4 M
Page No: 6 | 26MAHARASHTRA STATE HOARD OF TECHNICAL
(Autonomous)
dasomec “27001 «2013 Cette)
else
System.out printin("Validl age");
}
catch(myException e)
t
System.out printin(e.getMessage()):
catch(IOException ie)
uh
}
@)_ | Write a program for reading and writing character to and from the given files aM
using character stream classes.
‘Ans | import java.io.FileWriter; 4M (for any
import java.io. IOException; correct
public class 1OStreamsExample { program and
public static void main(String args(]) throws TOException { logic)
1iCreating FileReader object
File file = new File("D:/myFile.txt");
FileReader reader = new FileReader file);
char chars{] = new charf (int) fie.length]:
//Reading data from the file
reader.read(chars);
JiWriting data to another file
File out = new File("D:/CopyOfimyFile.txt");
FileWriter writer = new FileWriter(out);
J/Writing data to the file
writer.write(chars);
writer.flush();
System.out printin("Data successfully written in the specified file");
)
b
3 Attempt any THREE of the following: 12M
a) | Write a program to print all the Armstrong numbers from 0 to 999. 4M
‘Ans | import java.util. Scanner; Correct logic
class ArmstrongWhile -4M
{
public static void main(String{] arg)
{
int i-0,arm;
‘System.out printin(""Armstrong numbers between 0 to 999");
whileti=1000)
Page No: 7 | 26MAHARASHTRA STATE BOARD OF TECHNICAL
‘Autonomous)
3 Certified)
UCATION
arm=armstrongOrNot(i);
iffarm==i)
System.out.println(i);
iH;
static int armstrongOrNot(int num)
{
int x,a-0;
while(num!=0)
x=num%10;
amat(x*x*x);
num/=10;
return a
t
}
OR
class Armstrong While
{
public static void main(Stringf] arg)
int i-1a,arm.ntemp;
System.out println(”Armstrong numbers between 0 to 999 are");
while(i<500)
wi
arm=0;
while(n>0)
aan?10;
arm=arm*(a*a*a):
n=n/L0;
iffarm==i)
System.out.printIn(i);
by
Explain the applet life cycle with neat diagram.
aM
Page No: 8 | 26MAHARASHTRA STATE HOARD OF TE:
‘Autononons)
USOMEE + 27001 = 2018 Certitied)
{NICAL EDUCATION
“Ans
laestroyt)
ceaea bead >)—>
Applet Life Cycle: An Applet has a life eycle, which deseribes how it starts, how it
operates and how it ends. The life cycle consists of four methods: init(), star), stop() and
destroy().
Initialization State (The init() method)
The life cycle of an Applet is begin on that time when the applet is first loaded into the
browser and called the init() method. The init() method is called only one time in the life
eyele on an Applet. The init() method is basically called to read the “PARAM” tag in the
html file, The init () method retrieve the passed parameter through the “PARAM” tag of
html file using get Parameter() method All the initialization such as initialization of
variables and the objects like image, sound file are loaded in the init () method .After the
initialization of the init() method user can interact with the Applet and mostly applet
contains the init() method.
We may do following thing if required.
* Create objects needed by the applet
* Set up initial values
+ Load images or fonts
* Set up colors
Running State (The start() method): The start method of an Applet is called after the
initialization method init(). This method may be called multiples time when the Applet
needs to be started or restarted. For Example if the user wants to return to the Applet, in
this situation the start() method of an Applet will be called by the web browser and the
user will be back on the applet, Inthe start method user can interact within the applet.
public void star()
{
}
Idle (The Stop() method): An applet becomes idle when itis stopped from running. The
stop() method stops the applet and makes it invisible. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the
stop() method explicitly. The stop() method can be called multiple times in the life eycle of
applet like the start () method or should be called at least one time. For example the stop()
method is called by the web browser on that time When the user leaves one applet to go
another applet and the start() method is called on that time when the user wants to go back
into the first program or Applet,
public void stop()
Diagram-2
Mand
explanation
2M
Page No: 9 | 26MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
‘Autonomous)
USOMEE - 27001 = 2018 Certitied)
Dead State (The destroy() method): The destroy() method is called to terminate an
Applet, An Applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when we quit the browser, Iti useful for
clean-up actions, such as releasing memory after the applet is removed, killing off threads
and closing network/database connections,
Thus this method releases all the resources that were initialized during an applet's
initialization
public void destroy()
Display State (The paint() method): The paint() method is used for applet display on the
scree
The display includes text, images, graphics and background. This happens immediately
afier the applet enters into the running state. Almost every applet will have a paint()
method and can be called several times during an applet’ life cyele. The paint() method is
called whenever a window is required to paint or repaint the applet.
public void paint(Graphies g)
1
Describe the package in java with suitable example.
° aM
‘Ans [~~ Java provides @ mechanism for partitioning the class namespace into more | Deseription-
manageable parts called package (i.e package are container for a classes) 2M,
# The package is both naming and visibility controlled mechanism, Package can be | Example -2
created by including package as the first statement in java source code, M
+ Any classes declared within that file will belong to the specified package.
Syntax: package pkg;
pkg is the name of the package
eg : package mypack;
+ Java uses file system directories to store packages. The class
Which are declared in a
+ package must be stored in directory which has same name as package name.
+ The directory must match withthe package name exactly.
* Ahierarchy can be created by separating package name and sub package name by
period.) as pkgl.pky2.pkg3; which requires a directory structure as
pkgl\pke2\pkg3
# The classes and methods of a package must be public
+ To access package In a Java source file, import statements occur immediately
following the package. statement (if t exists) and before any class definitions
files of any classes
¢_ Syntax: import pkg I[.pkg2].(classname|*):
Page No: 10 | 26MAHARASHTRA STATE HOARD OF TECHNICAL EDUCATION
‘Autonomous)
27001 - 2013 Certied)
som
+ Example:
packagel
package package |;
public class Box
int
int b= 7;
int h= 8;
public void display()
System.out.printin( "Volume is:"+(1*b*h)):
Source file:
import packagel.Box;
class VolumeDemo
{
public static void main(String argsf)
{
Box ew Box();
badisplay0;
@) | Enlist types of Byte stream class and describe input stream class and output aM
stream class.
‘Ans [© Byte sireams class: It handles V/O operations on bytes, Type—1M,
# InputStream and OutputStream classes are operated on bytes for reading and | Explanation
\wtiting, respectively.
+ Byte streams are used in a program to read and write 8-bit bytes.
+ InputStream and OutputStream are the abstract super classes of all byte streams
that have a sequential nature,
+ The stream is unidirectional; they can transmit bytes in only one direction.
+ InputStream and OutputStream provide the Application program Interface (API)
and
partial implementation for input streams (streams that read bytes) and output
streams (streams that write bytes)
© Input Stream Classes: java.io.tnputStream is an abstract class that contains the
basic methods for reading raw bytes of data from a stream. The InputStream class
closing
streams, marking positions in streams, skipping ahead in a stream and finding the
defines methods for performing the input functions like: reading byte
number of bytes in a stream,
‘* Inputstream class methods:
1. int read ()- Returns an integer representation of next available byte of input. is,
returned at the stream end,
2. int read (byte buffer{ ])- Read up to butffer.length bytes into buffer & returns
actual number
3M
Page No: 11 | 26MAHARASHTRA STATE BOARD OF TECHNICAL
‘Autonomous)
7001-2013 Certified)
some
of bytes that are read. At the end returns —I.
3. int readbyte buffer{ J, int offset, int numbytes)- Attempts to read up to numbytes
bytes into buffer starting at bufferjofiset]. Returns actual number of bytes that are
read. At the end returns —1.
4, void close()-to close the input stream
5. void mark(int numbytes)- places a mark at current point in input stream and
remain valid tll number of bytes are read.
6. void reset()- Resets pointer to previously set mark’ goes back to stream
beginning.
7. long skip(long numbytes)- skips number of bytes.
8. int available()- Returns number of bytes currently available for reading.
Output Stream Classes:
The javaio.OutputStream class sends raw bytes of data to a target such as the
console or a network server. Like InputStream, OutputStream is an abstract class.
+ The OutputStream includes methods that perform operations like: writing bytes,
closing streams, flushing streams et.
+ Methods defines by the OutputStream class are
1. void close() - to close the OutputStream
2. void write (int b) - Writes a single byte to an output stream.
3. void write(byte buffer{ ]) - Writes a complete array of bytes to an output stream.
4. void write (byte buffer{ ], int offset, int numbytes) ~ Writes a sub range of
rnumbytes bytes
from the array bufler, beginning at bufferfofiset)
3. void flush() - clears the buter
‘Attempt any THREE of the following: 12M
a) | Describe any four features of java. aM
‘Ans | 1. Compile & Interpreted: Java is a two staged system. Tt combines both approaches. | Any four
First java compiler translates source code into byte code instruction. Byte codes are not | each features
machine instructions. In the second stage java interpreter generates machine code that can | -1 M each
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
won't force any change in java programs. Java compiler generates byte code instructions
that can be implemented on any machine as well as the size of primitive data type is
machine independent.
3. Object Oriented: Almost everything in java isin 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
ete, 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
Page No: 12 | 26MAHARASHTRA STATE HOARD OF TECHNICAL
(Autonomous)
c 27001 = 2018 Certified)
DUCATION
son
authorization,
5. Distributed: It is designed as a distributed language for creating applications on
network. It has ability to share both data and program. Java application can open and
access remote object on internet as easily as they can do in local system.
6, Multithreaded: It can handle multiple tasks simultaneously. Java makes this possible
with the feature of multithreading, This means that we need not wait for the application to
finish one task before beginning other.
7. Dynamic and Extensible: Java is capable of dynamically linking new class library's
method and object. Java program supports funetion written in other languages such as C,
C+ which are called as native methods. Native methods are linked dynamically at run
time.
b) _ | Explain any four methods of vector class with example. aM
‘Ans | Vector class is in java.util package of java. 1 Method — 1
Vector is dynamic array which can grow automatically according to the requirement. M
Vector does not require any fix dimension like String array and int array.
Vectors are used to store objects that do not have to be homogeneous
Vector contains many useful methods.
Vectors are created like arrays. It has three constructor methods
Vector list = new Vector();//declaring vector without size
Vector list = new Vector(3);/ideclaring vector with size
Vector list ~ new Vector(5,2);//ereate vector with initial size and whenever it
need to grows, it grows by value specified by inerement capacity
Method Name Task performed
list firstElement() Ttreturns the first element of the vector.
list lastElement() Tereturs last element of the vector
listaddElementfitem) | Adds the item specified to the list at the
end,
TistelementAtin) Gives the name of the object at nth
position
Tistsize) Gives the number of objects present in
vector
List.capacity) This method returns the current capacity of
the vector
Tistremovel:lemeni(item) | Removes the specified item From the list
lis.removel:lementAt(n) | Removes the item stored in the nth
position of thelist.
TistremoveATIElements) | Removes all the elements in the list
Tist.insertElementAt(item,] Inserts the item at nth position,
n)
List-contains(object This method checks whether the specified
element) element is present inthe Vector. Ifthe
element is been found it returns true else
false.
Tistcopyinto(array) Copies all tems from list of anay.
Example:~~ USOMEE - 27001 - 2018 Certitied)
import java.io.*;
import
javalang.*;
import
java.util";
class vector2
public static void main(String args{])
{
vector v=new
vector(); Integer
sl=new Integer(1);
Integer s2=new
Integer(2);String
sSenew
String("fy"); String
ew
String("sy");
Character s5=new
Character(‘a’); Character
so=new Character’);
Float s7=new
Float(1.11);
Float s8new Float( 1.21);
vaddElement(s!);
v.addElement(s2)
v.addElement(s3)
v.addElement(s4)
v.addElement(s5);
v.addElement(s6);
v.addEilement(s7);
v.addElement(s8),
System.out.printin(v);
v.removel:lement(s2);
v.removel lementAt();
System.out.printin(v);
}
° Describe i
Ans | Java does not support multiple inheritances with only classes. Java provides an alternate Interface
approach known as interface to support concept of multiple inheritance. An interface is | explanation
similar to class which can define only abstract methods and final variables. ~2M, any
Syntax: suitable
access interface Interface Name example ~ 2
M
{
Variables declaration;
Methods declaration;
Page No: 14 | 26iit MAHARASHTRA STATE HOARD OF TECHNICAL
(Autonomous)
~—— usomEe - 27001
3 Certified)
y
Example:
interface sports
{
int sport_wt=5;
public void disp();
i
class test
int roll_no;
String name;
int m1,m2;
test(intr, String nm, int mt Lint m12)
t
roll_no=t:
name=nm;
mi=ml1;
m2=m12;
}
}
class result extends test implements sports,
{
result (intr, String nm, int ml int m12)
{
super (r,nm,ml I m12):
}
public void disp()
{
System.out.printin("Roll no : "+roll_no):
System.out.printin("Name : "*name);
System.out.printin("subl : "¥ml);
System.out.println("sub2 : "4m2);
System.out.println("sport_wt : "-sport_wt}:
int t=m1-+m2+spor_wt;
System.out.priniln("total :"+t):
}
public static void main(String argsf])
1
result = new result(101,"abe",
disp);
}
}
Output
Ds\>java result
Roll no : 101
Name : abe
subl : 75
sub2 : 75
sport_wt: 5
75);
Page No: 15 | 26MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(SOMEC - 27001 - 2013 Certified)
total : 155
@) | Write an applet program for following graphics method. 4M
i) Drawoval ()
ii) Drawline ()
‘Ans | import java.awt.*; correct
import java.applet.*; logic can be
public class CirSqr extends Applet considered 2
{ M for
public void paint(Graphies g) drawoval
{ and 2M for
g.drawOval(70,30,100,100); drawline
g.drawRect(90,50,60,60);,
**/
OR
Using drawPolygon() method
import java.applet.™;
import java.awt.";
public class Triangle extends Applet
|
public void paint(Graphics g)
|
int af}={100,200,300,100};
int b[}-{200,100,200,200};
int n=4;
g.drawPolygon(a,b,n);
/**/
©) | Explain constructor with its type. Give an example of parameterized oM
constructor.
‘Ans / Constructor: A constructor in Java is @ special method that i used 0 initialize objets. | 4 2M"
. lefinition o
The constructor is called when an object of a class is created. It can be used to set initial | ‘Constructor
values for object attributes. and types of
constructors
Types of constructors are:
Default constructor : It is constructor which is inserted by Java compiler when no | 4 Mf for
constructor is provided in clas
have default constructor,
By default, Java compiler, insert the code for a zero parameter constructor
‘very class has constructor within it. Even abstract class
example (for
any correct
stitable
program of
parameterize
Page No: 24 | 26MAHARASHTRA STATE HOARD OF TECHNICAL
‘Autonomous)
USOC -27001 = 2013 Certified)
Default constructor is the no arguments constructor automatically generated unless you
define another constructor.
The default constructor automatically initializes all numeric members to zero and other
types to null or spaces.
class Rect
{
int length, breadth;
Reet) //constructor
{
length=4;
breadth=5;
+
public static void main(String args[])
{
Rect r= new Rect();
System.out.printin(“Area :" +(r.Jength*r.breadth));
}
}
Parameterized constructor: Constructor which have arguments are known as
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 of Parameterized Constructor
class Rect
int length, breadth;
Rect(int |, int b) // parameterized constructor
{
ength=1;
breadth=b;
+
public static void main(String args[])
{
Rect r=new Rect(4,5); / constructor with parameters
Rect rl = new Rect(6,7);
System.out.printIn(“Area :” +(r.length*r,breadth)):
d
constructor)
Page No: 25 | 26MAHARASHTRA STATE HOARD OF TECHNICAL
‘Autonomous)
USOMEC - 27001 -2013 Certitied)
System.out.printin(“Area :” +(rl length*r1 breadth)):
+