Ilovepdf Merged
Ilovepdf Merged
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
WINTER– 18 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 17515
Important Instructions to examiners:
1) The answers should be examined by key words and not as word-to-word as given in the model
answer scheme.
2) The model answer and the answer written by candidate may vary but the examiner may try to
assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more
Importance (Not applicable for subject English and Communication Skills.
4) While assessing figures, examiner may give credit for principal components indicated in the
figure. The figures drawn by candidate and model answer may vary. The examiner may give
credit for any equivalent figure drawn.
5) Credits may be given step wise for numerical problems. In some cases, the assumed constant
values may vary and there may be some difference in the candidate’s answers and model
answer.
6) In case of some questions credit may be given by judgement on part of examiner of relevant
answer based on candidate’s understanding.
7) For programming language papers, credit may be given to any other program based on
equivalent concept.
Q. S. Answer Marking
No. Q. Scheme
No.
1 A Attempt any three of the following. 3x4=12
a) Explain following terms related to Java features. 4
i) Object Oriented ii) Complied and interpreted.
Ans: i) Object Oriented: 2 Marks for
Almost everything in java is in the form of object. each)
All program codes and data reside within objects and classes.
Similar to other OOP languages java also has basic OOP properties
such as encapsulation, polymorphism, data abstraction, inheritance
etc.
Java comes with an extensive set of classes (default) in packages.
Example:
public class Test
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output:
a && b = false
a || b = true
!(a && b) = true
d) Describe life cycle of thread. 4
Ans: 1 Mark for
correct
diagram,
3 M for
proper
explanation
Thread Life Cycle Thread has five different states throughout its life.
2
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state
to another by different methods and ways.
1. Newborn state: When a thread object is created it is said to be in a new
born state. When the thread is in a new born state it is not scheduled running
from this state it can be scheduled for running by start() or killed by stop(). If
put in a queue it moves to runnable state.
2. Runnable State: It means that thread is ready for execution and is waiting
for the availability of the processor i.e. the thread has joined the queue and is
waiting for execution. If all threads have equal priority, then they are given
time slots for execution in round robin fashion. The thread that relinquishes
control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
3. Running State: It means that the processor has given its time to the thread
for execution. The thread runs until it relinquishes control on its own or it is
pre-empted by a higher priority thread.
4 Blocked State: A thread can be temporarily suspended or blocked from
entering into the runnable and running state by using either of the following
thread method.
suspend() : Thread can be suspended by this method. It can be rescheduled
by resume().
wait(): If a thread requires to wait until some event occurs, it can be done
using wait method and can be scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using
sleep(time) where time is in ms. It reenters the runnable state as soon as
period has elapsed /over.
5 Dead State: Whenever we want to stop a thread form running further we
can call its stop(). The statement causes the thread to move to a dead state. A
thread will also move to dead state automatically when it reaches to end of
the method. The stop method may be used when the premature death is
required
1 B Attempt any One of the following. 1x6=6
a) Define a class ‘Book’ with data members bookid, bookname and price. 6
Accept data for seven objects using Array of objects and display it.
Ans: import java.lang.*; Correct
import java.io.*; program
class Book with proper
{ logic 4
String bookname; Marks
int bookid;
int price;
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
void getdata()
{
3
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
try
{
System.out.println("Enter Book ID=");
bookid=Integer.parseInt(br.readLine());
System.out.println("Enter Book Name=");
bookname=br.readLine();
System.out.println("Enter Price=");
price=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Error");
}
}
void display()
{
System.out.println("Book ID="+bookid);
System.out.println("Book Name="+bookname);
System.out.println("Price="+price);
}
}
class bookdata
{
public static void main(String args[])
{
Book b[]=new Book[7];
for(int i=0;i<7;i++)
{
b[i]=new Book();
}
for(int i=0;i<7;i++)
{
b[i].getdata();
}
for(int i=0;i<7;i++)
{
b[i].display();
}
}
}
b) What is interface? Describe its syntax and features. 6
Ans: Definition: Java does not support multiple inheritances with only classes. Definition:
Java provides an alternate approach known as interface to support concept of 1 Mark,
multiple inheritance. An interface is similar to class which can define only 1 Mark for
abstract methods and final variables. syntax and
Syntax: 2 Marks for
access interface InterfaceName Features
{
Variables declaration;
4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Methods declaration;
}
Features:
The interfaces are used in java to implementing the concept of
multiple inheritance.
The members of an interface are always declared as constant i.e. their
values are final.
The methods in an interface are abstract in nature. I.e. there is no code
associated with them.
It is defined by the class that implements the interface.
Interface contains no executable code.
We are not allocating the memory for the interfaces.
We can‘t create object of interface.
Interface cannot be used to declare objects. It can only be inherited by
a class.
Interface can only use the public access specifier.
An interface does not contain any constructor.
Interfaces are always implemented.
Interfaces can extend one or more other interfaces.
2 Attempt any Two of following 2x8=16
a) Write a program to create a vector with seven elements as 8
rd th
(10,30,50,20,40,10,20). Remove elements 3 and 4 position. Insert new
elements at 3rd position. Display original and current size of vector.
Ans: import java.util.*; (Correct
public class VectorDemo Program
{ with
public static void main(String args[]) Correct
{ logic 8
Vector v = new Vector(); marks
v.addElement(new Integer(10)); Creation of
v.addElement(new Integer(30)); vector:
v.addElement(new Integer(50)); 3Marks,
v.addElement(new Integer(20)); removing
v.addElement(new Integer(40)); elements 2
v.addElement(new Integer(10)); Marks
v.addElement(new Integer(20)); inserting
System.out println(v.size()); // display original size element 1
v.removeElementAt(2); // remove 3rd element Mark
v.removeElementAt(3); // remove 4th element Display
v.insertElementAt(11,2) // new element inserted at 3rd position original size
System.out.println("Size of vector after insert delete operations: " + v.size()); : 1 Mark
} and
} Current
size:
1Mark)
Program:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}
Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
c) Write syntax and example of 8
i)Draw Poly ii)Draw Rect iii)Filloval iv)Draw Arc()
Ans: i) Draw Poly: drawPoly() method is used to draw arbitrarily shaped figures. (Each one
Syntax: void drawPoly(int x[], int y[], int numPoints) for 2 Mark)
The polygon‟s end points are specified by the co-ordinates pairs contained
within the x and y arrays.
The number of points define by x and y is specified by numPoints.
Example:
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPoly(xpoints,ypoints,num);
6
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
{
DataInputStream dr=new DataInputStream(System.in);
int l,w;
System.out.println(“Enter length and width:”);
l=Integer.parseInt(dr.readLine());
w=Integer.parseInt(dr.readLine());
int a=l*w;
System.out.println(“Area is=”+a);
int p=2(l+w);
System.out.println(“Area is=”+p);
}
}
c) Explain fileinputstream class to read the content of a file. 4
Ans: Java FileInputStream class obtains input bytes from a file. It is used for 4m for
reading byte-oriented data (streams of raw bytes) such as image data, audio, proper
video etc. You can also read character-stream data. But, for reading streams explanation
of characters, it is recommended to use File Reader class.
Java FileInputStream class methods
Method Description
It is used to return the estimated number of bytes that
int available()
can be read from the input stream.
It is used to read the byte of data from the input
int read()
stream.
It is used to read up to b.length bytes of data from the
int read(byte[] b)
input stream.
int read(byte[] b, int It is used to read up to len bytes of data from the input
off, int len) stream.
It is used to skip over and discards x bytes of data
long skip(long x)
from the input stream.
FileChannel It is used to return the unique FileChannel object
getChannel() associated with the file input stream.
FileDescriptor
It is used to return the FileDescriptor object.
getFD()
protected void It is used to ensure that the close method is call when
finalize() there is no more reference to the file input stream.
void close() It is used to closes the stream.
8
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
{
System.out.println(dr.readLine());
}
dr.close();
}
}
d) Explain applet life cycle with suitable diagram. 4
Ans: Java applet inherits features from the class Applet. Thus, whenever an applet 1m for
is created, it undergoes a series of changes from initialization to destruction. diagram
Various stages of an applet life cycle are depicted in the figure below: and
3 marks for
explanation
10
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Example:
Final Variable: The final variable can be assigned only once. The value of a
final variable can never be changed.
final float PI=3.14;
The above program would throw a compilation error, however we can use the
parent class final method in sub class without any issues.
class XYZ
{
final void demo(){
System.out.println("XYZ Class Method");
}
}
obj.demo();
}
}
Output:
XYZ Class Method
final class: We cannot extend a final class. Consider the below example:
final class XYZ
{
}
The expression to the right of the “=“ operator is solved first and the result is
stored in x. The int value is automatically promoted to the higher data type
float (float has a larger range than int) and then, the expression is evaluated.
The resulting expression is of float data type. This value is then assigned to x,
which is a double (larger range than float) and therefore, the result is a
double.
Java automatically promotes values to a higher data type, to prevent any loss
of information.
Example: int x=5.5/2
In above expression the right evaluates to a decimal value and the expression
on left is an integer and cannot hold a fraction. Compiler will give you
following error.
“Incompatible type for declaration, Explicit vast needed to convert double to
int.”
This is because data can be lost when it is converted from a higher data type
to a lower data type. The compiler requires that you typecast the assignment.
Solution: int x=(int)5.5/2;
b) Explain following clause w.r.t. exception handling 4
i) try ii) catch iii) throw iv) finally
Ans: try: Program statements that you want to monitor for exceptions are 1m for each
contained within a try block. If an exception occurs within the try block, it is term
thrown.
Syntax: try
{
// block of code to monitor for errors
}
catch: Your code can catch this exception (using catch) and handle it in
some rational manner. System-generated exceptions are automatically thrown
by the Java runtime system. A catch block immediately follows the try block.
The catch block can have one or more statements that are necessary to
process the exception.
Syntax: catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
finally: finally block is a block that is used to execute important code such as
closing connection, stream etc. Java finally block is always executed whether
exception is handled or not. Java finally block follows try or catch block.
Syntax:
finally
{
// block of code to be executed before try block ends
13
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
g.setColor(Color.GREEN);
g.fillRect(50,120,100,50);
g.setColor(Color.YELLOW);
int x1[]={50, 100, 150, 50};
int y1[]={250, 200, 250, 250};
int n1=4;
g.fillPolygon(x1, y1, n1);
}
}
Output:
given equal treatment by the java scheduler. The Thread class defines several priority=4m
priority constants as Explanation
MIN_PRIORITY=1 of Types of
NORM_PRIORITY=5 Exception=
MAX_PRIORITY=10 4m
Thread priorities can take values from 1 to 10.
To set the priority Thread class provides setPriority() method as
Thread.setPriority(priority value);
Eg: If t1 is a Thread class object then
T1.setPriority(Thread.MAX_PRIORITY);
To see the priority value of a thread the method available is getPrioriy() as
int Thread.getPriority();
eg : int p= Thread.getPriority();
getParameter() method to collect the value of parameter sent from <param> explanation
tag to applet. getParameter() takes one String argument representing name of : 2M,
the parameter and returns the value of the same. In program
Syntax: : correct
<Param name=”variable-name” value=”value of the variable> logic 3M,
String getParameter(“variable-name”); correct
Program: syntaxes :
import java.awt.*; 3M
import java.applet.*;
public class myapplet extends Applet
{
String uname="";
public void paint(Graphics g)
{
uname=getParameter("username");
g.drawString("Hello "+uname,100,100);
}
}
/*<applet code=myapplet height=300 width=300>
<param name="username" value="ABC">
</applet>*/
Output:
void display()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
}
class test extends overridetest
{
int z;
test(int a,int b,int c)
{
super(a,b);
z=c;
}
void display() //method overridden
{
super.display(); //call to super class display()
System.out.println("z="+z);
}
public static void main(String args[])
{
test t= new test(4,5,6);
t.display();
}
}
b) Write any two methods of file and file input stream class each. 4
Ans: File class methods: Any two
boolean canExecute() : Tests whether the application can execute the file methods
denoted by this abstract pathname. from file
boolean canRead() : Tests whether the application can read the file denoted class=2m
by this abstract pathname. Any two
boolean canWrite() : Tests whether the application can modify the file methods
denoted by this abstract pathname. from
int compareTo(File pathname) : Compares two abstract pathnames fileinput
lexicographically. stream=2m
boolean createNewFile() : Atomically creates a new, empty file named by
this abstract pathname .
static File createTempFile(String prefix, String suffix) : Creates an empty
file in the default temporary-file directory.
boolean delete() : Deletes the file or directory denoted by this abstract
pathname.
boolean equals(Object obj) : Tests this abstract pathname for equality with
the given object.
boolean exists() : Tests whether the file or directory denoted by this abstract
pathname exists.
String getAbsolutePath() : Returns the absolute pathname string of this
abstract pathname.
long getFreeSpace() : Returns the number of unallocated bytes in the
partition
19
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
String getName() : Returns the name of the file or directory denoted by this
abstract pathname.
String getParent() : Returns the pathname string of this abstract pathname’s
parent.
File getParentFile() : Returns the abstract pathname of this abstract
pathname’s parent.
String getPath() : Converts this abstract pathname into a pathname string.
boolean isDirectory() : Tests whether the file denoted by this pathname is a
directory.
boolean isFile() : Tests whether the file denoted by this abstract pathname is
a normal file.
boolean isHidden() : Tests whether the file named by this abstract pathname
is a hidden file.
long length() : Returns the length of the file denoted by this abstract
pathname.
String[] list() : Returns an array of strings naming the files and directories in
the directory .
File[] listFiles() : Returns an array of abstract pathnames denoting the files in
the directory.
boolean mkdir() : Creates the directory named by this abstract pathname.
boolean renameTo(File dest) : Renames the file denoted by this abstract
pathname.
boolean setExecutable(boolean executable) : A convenience method to set
the owner’s execute permission.
boolean setReadable(boolean readable) : A convenience method to set the
owner’s read permission.
boolean setReadable(boolean readable, boolean ownerOnly) : Sets the
owner’s or everybody’s read permission.
boolean setReadOnly() : Marks the file or directory named so that only read
operations are allowed.
boolean setWritable(boolean writable) : A convenience method to set the
owner’s write permission.
String toString() : Returns the pathname string of this abstract pathname.
URI toURI() : Constructs a file URI that represents this abstract pathname.
Output:
}
class student extends person implements sports
{
int marks1,marks2;
student(String n,String c, int m1,int m2)
{
super(n,c);
marks1=m1;
marks2=m2;
}
public void calc_total()
{
int total;
if (category.equals("sportsman"))
total=marks1+marks2+sports_weightage;
else
total=marks1+marks2;
System.out.println("Name="+name);
System.out.println("Category ="+category);
System.out.println("Marks1="+marks1);
System.out.println("Marks2="+marks2);
System.out.println("Total="+total);
}
public static void main(String args[])
{
student s1=new student("ABC","sportsman",67,78);
student s2= new student("PQR","non-sportsman",67,78);
s1.calc_total();
s2.calc_total();
}
}
e) Write a program to find greater number among two numbers using 4
conditional operator.
Ans: class greater correct logic
{ 1 M, correct
public static void main(String args[]) use of
{ conditional
int a,b; operator
int bignum; :2M, other
a=100; correct
b=150; syntaxes :
bignum=(a>b?a:b); //conditional operator 1M
System.out.println("Greater number between "+a+ " and "+b +" is =
"+bignum);
}
}
Output:
E:\java\bin>javac greater.java
E:\java\bin>java greater
22
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 1 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Syntax: Syntax
protected void finalize() { 1M
}
c) Name the wrapper class methods for the following: 2M
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
Ans. (i) To convert string objects to primitive int:
String str=”5”;
int value = Integer.parseInt(str); 1M for
each
(ii) To convert primitive int to string objects: method
int value=5;
String str=Integer.toString(value);
d) List the types of inheritances in Java. 2M
(Note: Any four types shall be considered)
Ans. Types of inheritances in Java:
i. Single level inheritance Any
ii. Multilevel inheritance four
iii. Hierarchical inheritance types
iv. Multiple inheritance ½M
v. Hybrid inheritance each
Page 2 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
byte code.
Diagram
1M
Page 4 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 5 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
name=n;
}
void display() {
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
s.display();
}
}
Page 6 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 7 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 8 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 9 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
for(i=0;i<5;i++)
{
arr[i].display();
}
}
}
b) Explain dynamic method dispatch in Java with suitable example. 4M
Ans. 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 superclass
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 depends on the type of the object being referred to
Explana
(not the type of the reference variable) that determines which version
tion 2M
of an overridden method will be executed
A superclass reference variable can refer to a subclass object. This
is also known as upcasting. Java 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 versions 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()
{
System.out.println("Inside A's m1 method");
}
}
Example
2M
class B extends A
{
// overriding m1()
void m1()
Page 10 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("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();
Page 11 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 12 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 13 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 14 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 15 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 16 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 17 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
// 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();
Page 18 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Output:
Inside A’s m1 method
Inside 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
Page 19 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 20 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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.
4M for
Command Line Arguments can be used to specify configuration explanat
information while launching your application. ion
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 args[]){
System.out.println("Your first argument is: "+args[0]); 2M for
} example
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
b) Write a program to input name and salary of employee and 6M
throw user defined exception if entered salary is negative.
Ans. import java.io.*;
class NegativeSalaryException extends Exception Extende
{ d
public NegativeSalaryException (String str) Exceptio
{ n class
super(str); with
} construc
} tor 2M
public class S1
Page 21 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
{
public static void main(String[] args) throws IOException
{ Acceptin
BufferedReaderbr= new BufferedReader(new g data
InputStreamReader(System.in)); 1M
System.out.print("Enter Name of employee");
String name = br.readLine();
System.out.print("Enter Salary of employee");
int salary = Integer.parseInt(br.readLine()); Throwin
Try g user
{ defining
if(salary<0) Exceptio
throw new NegativeSalaryException("Enter Salary amount n with
isnegative"); try catch
System.out.println("Salary is "+salary); and
} throw
catch (NegativeSalaryException a) 3M
{
System.out.println(a);
}
}
}
c) Describe the applet life cycle in detail. 6M
Ans.
2M
Diagram
Page 22 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
start(): The start() method contains the actual code of the applet that 4M
should run. The start() method executes immediately after descripti
the init() method. It also executes whenever the applet is restored, on
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()
Page 23 / 23
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Winter – 19 EXAMINATION
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
b Define Class and Object. 2M
1|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Ans Class: A class is a user defined data type which groups data Definition 1
members and its associated functions together. Mark each
2. Runtime errors
e List any four Java API packages. 2M
Ans 1.java.lang 1/2 Marks for
2.java.util one Package
3.java.io
4.java.awt
5.java.net
6.ava.applet
2|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
1)One-Dimensional
2)Two-Dimensional
g List access specifiers in Java. 2M
Ans 1)public Any 2, 1M for
each
2)private
3)friendly
4)protected
5)Private Protected
3|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
float pi,radius;
abc(float p, float r)
pi=p;
radius=r;
void area()
float ar=pi*radius*radius;
System.out.println("Area="+ar);
void display()
System.out.println("Pi="+pi);
System.out.println("Radius="+radius);
}}
class area
a.display();
4|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
a.area();
}
c Define exception. State built-in exceptions. 4M
Ans An exception is a problem that arises during the execution of a Definition 2
program. Marks, List: 2
Marks
Java exception handling is used to handle error conditions in a
program systematically by taking the necessary action
Built-in exceptions:
5|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
1) drawRect()
2)drawOval()
Ans 1)drawRect() : drawRect:
2Marks,
drawRect () method display an outlined rectangle. drawOval: 2
Marks
Syntax: void drawRect(int top,int left, int width,int height)
Example: g.drawRect(10,10,60,50);
Syntax: void drawOval(int top, int left, int width, int height)
2) Use the byte stream classes when working with bytes or other
binary objects.
6|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
2. start( )
3. paint( )
4. stop( )
5. destroy( )
7|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
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.
8|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
7)syntax 7)syntax
Class classname Inteface Innterfacename
{ {
Variable declaration, Final Variable declaration,
Method 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 1M for
casting or type casting. definition,3M for
types explanation
2. If the two types are compatible, then java will perform the
conversion automatically.
3. It is possible to assign an int value to long variable.
4. However, if the two types of variables are not compatible, the
type conversions are not implicitly allowed, hence the need for
type casting.
1.Implicit type-casting:
2.Explicit type-casting:
1. Implicit type-casting:
Example:
int i = 3;
double f;
f = i;
9|24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
output:
f = 3.0
Widening Conversion:
2. Explicit type-casting:
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.
10 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Ans 2M for
diagram,2M for
explanation
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
11 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
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 2M for
functionality defined in this method will never be altered in any definition,2M for
way, ie a final method cannot be overridden. example
Syntax:
{
//implementation
}
Example of declaring a final method:
class A
{
12 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Operator Meaning
&& Logical
AND
|| Logical
OR
! Logical
NOT
Program demonstrating logical Operators
13 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
boolean a = true;
boolean b = false;
Output:
a && b = false
a || b = true
Array Vector
1) An array is a structure that 1)The Vector is similar to
holds multiple values of the array holds multiple objects
same type. and like an array; it contains
components that can be
accessed using an integer
index.
14 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Syntax: s1.toLowerCase()
System.out.println(s.toLowerCase());
Output: sachin
15 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
Syntax: s1.toUpperCase()
Example:
String s="Sachin";
System.out.println(s.toUpperCase());
Output: SACHIN
3) trim (): Returns a copy of the string, with leading and trailing
whitespace omitted.
Syntax: s1.trim()
Example:
System.out.println(s.trim());
Output:Sachin
Syntax: s1.replace(‘x’,’y’)
Example:
System.out.println(s2);
16 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
17 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
18 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
19 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
}
}
catch(InterruptedException e)
{System.out.println("odd thread interrupted");
}
}
}
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}
20 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
21 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
22 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
}
c Implement the following inheritance 6M
23 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
TA=t;
DA=d; (Any other logic
} considered)
public void Basic_Sal()
{
System.out.println("Basic Salary
:"+Basic_Salary);
}
void Total_Sal()
{
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
System.out.println("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();
}
}
24 | 2 4
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Example:
int y= Math.min(64,45);
ii)Sqrt()
Syntax:
static double sqrt(double arg) Returns square root of arg.
Example:
double y= Math.sqrt(64);
c) Define the interface in Java. 2M
Ans. Interface is similar to a class.
It consist of only abstract methods and final variables. 1M for
To implement an interface a class must define each of the method each point,
declared in the interface. Any two
It is used to achieve fully abstraction and multiple inheritance in points
Java.
d) Enlist any four inbuilt packages in Java. 2M
Ans. 1.java.lang ½ M for
2.java.util each
3.java.io package
4.java.awt Any four
5.java.net packages
6.java.applet
e) Explain any two methods of File Class 2M
Ans.1. 1. boolean createNewFile(): It creates a new, empty file named by 1M for
this abstract pathname automatically, if and only if no file with the each
same name exists. method
if(file.createNewFile()) Any two
System.out.println("A new file is successfully created."); methods
Page 2 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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
Page 3 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
3.Simple:
Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
4.Secure:
With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key
encryption.
5.Architecture-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.
6.Multithreaded:
With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows
the developers to construct interactive applications that can run
smoothly.
b) Write a Java program to copy the content of one file into another. 4M
Ans. import java.io.*; 2M for
class filecopy correct
{ logic,
public static void main(String args[]) throws IOException
{ 2M for
FileReader fr= new FileReader(“file1.txt"); code
FileWriter fo= new FileWriter("file2.txt");
int ch;
try
{
while((ch=fr.read())!= -1)
{
fo.write(ch);
}
System.out.println(“file copied successfully”);
fr.close();
fo.close();
}
finally
{
if(fr!=null)
fr.close();
if(fo!=null)
fo.close();
}}}
catch:
Your code can catch this exception (using catch) and handle it in some
rational manner. System-generated exceptions are automatically
thrown by the Java runtime system. A catch block immediately
follows the try block. The catch block can have one or more
statements that are necessary to process the exception.
Syntax:
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
Page 6 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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 important code such as
closing connection, stream etc. Java finally block is always executed
whether exception is handled or not. Java finally block follows try or
catch block.
Syntax:
finally
{
// block of code to be executed before try block ends
}
3. Attempt any THREE of the following: 12
a) Write a Java Program to find out the even numbers from 1 to 100 4M
using for loop.
Ans. class test
{ 2M for
public static void main(String args[]) Program
{ logic
System.out.println("Even numbers from 1 to 100 :");
for(int i=1;i<=100; i++) 2M for
{ program
if(i%2==0) syntax
System.out.print(i+" ");
}
}
}
b) Explain any four visibility controls in Java. 4M
Ans. Four visibility control specifiers in Java are public, default, private
and protected. The visibility control in java can be seen when concept 3M for
of package is used with the java application. Explanatio
1) private :The access level of a private specifier is only within the n
class. It cannot be accessed from outside the class.
2) default :When no specifier is used in the declaration, it is called as
default specification. Default scope for anything declared in java
Page 7 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
1M for
Example : each
class A example
{
Page 8 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
void display()
{
System.out.println(“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
System.out.println(“In child class B”);
}
public static void main(String args[])
{
B b= new B();
b.display(); //super class method call
b.show(); // 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()
Page 9 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
{
System.out.println(“In Parent class A”);
}
}
class B extends A //derived class B from A
{
void show()
{
System.out.println(“In child class B”);
}
}
class C extends B //derived class C from B
{
public void print()
{
System.out.println(“In derived from derived class C”);
}
public static void main(String args[])
{
C c= new C();
c.display(); //super class method call
c.show(); // sub class method call
c.print(); //sub-sub class method call
}
}
Note : any other relevant example can be considered.
Page 10 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
{
public void paint(Graphics g) 2M for
{ correct
int x[]={10,200,70}; syntax
int y[]={10,10,100};
g.setColor(Color.red);
g.drawPolygon(x,y,3);
}
}
/*<applet code=myapplet height=400 width=400>
</applet>*/
Page 11 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
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";
}
Page 12 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
System.out.println(day);
}
}
Note : any 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 1M for
to handling simple situations in a line. explanatio
Syntax: n
expression1 ? expression2:expression3; Conditiona
The above syntax means that if the value given in Expression1 is true, l operator
then Expression2 will be evaluated; otherwise, expression3 will be
evaluated. 1M for
example
Example
class test
{
public static void main(String[] args) {
String result;
int a = 6, b = 12;
result = (a==b ? "equal":"Not equal");
System.out.println("Both are "+result);
}
}
Note : any other relevant example can be considered.
Page 13 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
2M for
diagram
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 2M for
created, but it has not yet been started. A thread is started by calling explanatio
its start() method. n
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, the thread cannot even run
again.
c) Write a java program to sort an 1-d array in ascending order 4M
using bubble-sort.
Ans. public class BubbleSort 2M for
{ correct
public static void main(String[] args) logic
Page 14 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
{
int arr[] ={3,60,35,2,45,320,5};
System.out.println("Array Before Bubble Sort"); 2M for
for(int i=0; i<arr.length; i++) correct
{ syntax
System.out.print(arr[i] + " ");
}
System.out.println();
int n = arr.length;
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;
}
}
}
System.out.println("Array After Bubble Sort");
for(int i=0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Page 15 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 16 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
package myPack;
import java.util;
public class Myclass {
//code
}
Page 17 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
}
}
Page 19 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Types of constructors:
1. Default constructor
2. Parameterized constructor 1M List
3. Copy constructor types
4. Constructor with no arguments or No-Arg Constructor or Non-
Parameterized constructor. (Any 3 )
Example
class Student {
int roll_no;
String name; 1M
Student(int r, String n) // parameterized constructor parameteri
{ zed
roll_no = r; constructor
name=n;
} 2M
void display() Example
{
(Any Other
System.out.println("Roll no is: "+roll_no);
Example
System.out.println("Name is : "+name);
Can be
}
Page 20 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
try { while(c!=-1) 3M
{ Correct
c=fr.read(); program
if(c==(char)' ') with syntax
wc++;
}
System.out.println("Number of words :"+(wc+1));
3M
}
Correct
finally
logic
{
if(fr!=null)
fr.close();
}
}
}
b) Explain the difference between string class and string buffer 6M
class.
Explain any four methods of string class
Page 21 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Ans. 1M each
Any 2
points
1M each
Methods of string class Any 4
1)toLowercase (): Methods
Converts all of the characters in this String to lower case. correct
Syntax: s1.toLowerCase() explanatio
Example: String s="Sachin"; n
System.out.println(s.toLowerCase());
Output: sachin
2) toUppercase():
Converts all of the characters in this String to upper case
Syntax: s1.toUpperCase()
Example: String s="Sachin";
System.out.println(s.toUpperCase());
Output: SACHIN
3)trim ():
Returns a copy of the string, with leading and trailing whitespace
omitted.
Syntax: s1.trim()
Example: String s=" Sachin ";
System.out.println(s.trim());
Page 22 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Output:Sachin
4)replace ():Returns a new string resulting from replacing all
occurrences of old Char in this string with new Char.
Syntax: s1.replace(‘x’,’y’)
Example: String s1="Java is a programming language. Java is a
platform.";
String s2=s1.replace("Java","Kava"); //replaces all occurrences of
"Java" to "Kava" System.out.println(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”
System.out.println(str.length()); // Returns 5
6. charAt():
Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .
Eg. String s=”INDIA”
System.out.println(s.charAt(2) ); // returns D
7. substring():
Syntax:
String substring (int startindex)
startindex specifies the index at which the substring will begin.It will
returns a copy of the substring that begins at startindex and runs to the
end of the invoking string
Example:
System.out.println(("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 characters from the
Page 23 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
8. compareTo():
Syntax: int compareTo(Object o) or int compareTo(String
anotherString)
There are two variants of this 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 = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
c) Write a Java applet to draw a bar chart for the following values. 6M
setBackground(Color.yellow);
try {
int n = Integer.parseInt(getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] = getParameter("label1");
label[1] = getParameter("label2");
label[2] = getParameter("label3");
label[3] = getParameter("label4");
value[0] = Integer.parseInt(getParameter("c1"));
value[1] = Integer.parseInt(getParameter("c2"));
value[2] = Integer.parseInt(getParameter("c3"));
value[3] = Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
for(int i=0;i<4;i++) {
g.setColor(Color.black);
g.drawString(label[i],20,i*50+30);
g.setColor(Color.red);
g.fillRect(50,i*50+10,value[i],40);
}
Page 25 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
}}
Page 26 / 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2022 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 22412
Ans 2M (1/2 M
Operator Meaning
each)
< Less than Any Four
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Ans The access specifiers in java specify accessibility (scope) of a data member, 2M (1/2 M
method, constructor or class. There are 5 types of java access specifier: each)
public Any Four
private
Page No: 1 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
default (Friendly)
protected
private protected
c) Explain constructor with suitable example. 2M
Ans Constructors are used to assign initial value to instance variable of the class. 1M-
It has the same name as class name in which it resides and it is syntactically similar Explanation
to anymethod. 1M-
Constructors do not have return value, not even ‘void’ because they return the instance if Example
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();
System.out.println(“Area : ” +(r.length*r.breadth));
}
}
Output : Area : 20
d) List the types of inheritance which is supported by java. 2M
1 M each
Page No: 2 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans 1. Thread is a smallest unit of executable code or a single task is also called as thread. 1 M-
2. Each tread has its own local variable, program counter and lifetime. Define
3. A thread is similar to program that has a single flow of control. Thread
There are two ways to create threads in java:
1M -2ways
1. By extending thread class to create
Syntax: - thread
class Mythread extends Thread
{
-----
}
2. Implementing the Runnable Interface
Syntax:
class MyThread implements Runnable
{
public void run()
{
------
}
f) Distinguish between Java applications and Java Applet (Any 2 points) 2M
Page No: 3 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans 1 M for
each point
(any 2
Applet Application Points)
Applet does not use main() Application use main() method
method for initiating execution of for initiating execution of code
code
Applet cannot run independently Application can run
independently
Applet cannot read from or write Application can read from or
to files in local computer write to files in local computer
Applet cannot communicate with Application can communicate
other servers on network with other servers on network
Applet cannot run any program Application can run any program
from local computer. from local computer.
Applet are restricted from using Application are not restricted
libraries from other language from using libraries from other
such as C or C++ language
Applets are event driven. Applications are control driven.
Ans 2M-Correct
diagram
Page No: 4 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
2. Attempt any THREE of the following: 12 M
int i,m=0,flag=0;
m=n/2;
if(n==0||n==1){
}else{
for(i=2;i<=m;i++){
if(n%i==0){
flag=1;
break;
}//end of else
Output:
7 is prime number
Page No: 5 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
b) Define a class employee with data members 'empid , name and salary. 4M
Accept data for three objects and display it
Ans class employee 4M (for
{ correct
int empid; program
String name; and logic)
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter Emp number : ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine();
System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3; i++)
{
e[i] = new employee(); e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<3; i++)
e[i].show();
}
}
Page No: 6 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
c) Describe Life cycle of thread with suitable diagram. 4M
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); t.start();
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.
Page No: 7 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Page No: 8 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
a) Write a program to find reverse of a number. 4M
while(number !=0)
number = number/10;
} }
Ans Final keyword : The keyword final has three uses. First, it can be used to create the Use of final
equivalent of a named constant.( in interface or class we use final as shared constant or keyword-2
constant.) M
Program-2
Other two uses of final apply to inheritance
M
Using final to Prevent Overriding While method overriding is one of Java’s most powerful
features,
To disallow a method from being overridden, specify final as a modifier at the start of its
declaration. Methods declared as final cannot be overridden.
The following fragment illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
Page No: 9 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
As base class declared method as a final , derived class can not override the definition of
base class methods.
Page No: 10 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
(x1,y1) and (x2,y2) as arguments and draws a line between them.
The graphics object g is passed to paint() method.
Syntax: g.drawLine(x1,y1,x2,y2);
Example: g.drawLine(100,100,300,300;)
iv) drawArc ()
drawArc( ) It is used to draw arc.
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int sweep_angle);
where x, y starting point, w & h are width and height of arc, and start_angle is starting
angle of arc sweep_angle is degree around the arc
Ans One
public String getName() Returns the name of the file or directory denoted by this method
abstract pathname.
public String getParent() Returns the pathname string of this abstract pathname's 1M
parent, or null if this pathname does not name a parent
directory
public String getPath() Converts this abstract pathname into a pathname string.
public boolean isAbsolute() Tests whether this abstract pathname is absolute. Returns
true if this abstract pathname is absolute, false otherwise
public boolean exists() Tests whether the file or directory denoted by this abstract
pathname exists. Returns true if and only if the file or
directory denoted by this abstract pathname exists; false
otherwise
public boolean isDirectory() Tests whether the file denoted by this abstract pathname is
a directory. Returns true if and only if the file denoted by
this abstract pathname exists and is a directory; false
otherwise.
public boolean isFile() Tests whether the file denoted by this abstract pathname is
a normal file. A file is normal if it is not a directory and, in
addition, satisfies other system-dependent criteria. Any
nondirectory file created by a Java application is guaranteed
to be a normal file. Returns true if and only if the file
denoted by this abstract pathname exists and is a normal
file; false otherwise.
a) Write all primitive data types available in Java with their storage Sizes in 4M
Page No: 11 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
bytes.
Page No: 12 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
method to initialize and display the information for three objects.
Ans class Book Correct
{ program- 4
String author, title, publisher; M
Book(String a, String t, String p)
{
author = a;
title = t;
publisher = p;
}
}
class BookInfo extends Book
{
float price;
int stock_position;
BookInfo(String a, String t, String p, float amt, int s)
{
super(a, t, p);
price = amt;
stock_position = s;
}
void show()
{
System.out.println("Book Details:");
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
System.out.println("Price: " + price);
System.out.println("Stock Available: " + stock_position);
}
}
class Exp6_1
{
public static void main(String[] args)
{
BookInfo ob1 = new BookInfo("Herbert Schildt", "Complete Reference", "ABC
Publication", 359.50F,10);
BookInfo ob2 = new BookInfo("Ulman", "system programming", "XYZ Publication",
359.50F, 20);
BookInfo ob3 = new BookInfo("Pressman", "Software Engg", "Pearson Publication",
879.50F, 15);
ob1.show();
Page No: 13 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
ob2.show();
ob3.show();
}
}
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. 4M
Page No: 14 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
“Hellojava.java”
import java.awt.*;
import java.applet.*;
public class Hellojava extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello Java",10,100);
}}
Use the java compiler to compile the applet “Hellojava.java” file.
C:\jdk> javac Hellojava.java
After compilation “Hellojava.class” 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, correct them and compile the applet again.
We must have the following files in our current directory.
o Hellojava.java
o Hellojava.class
o HelloJava.html
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 = hellojava.class WIDTH = 400 HEIGHT = 200 > </APPLET>
Example: Adding applet to HTML file:
Create Hellojava.html 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.
>
<HEAD> <TITLE> Welcome to Java Applet </TITLE> </HEAD>
<BODY> <CENTER> <H1> Welcome to the world of Applets </H1> </CENTER> <BR>
<CENTER>
Page No: 15 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
<APPLET CODE=HelloJava.class WIDTH = 400 HEIGHT = 200 > </APPLET>
</CENTER>
</BODY>
</HTML>
e) Write a program to copy contents of one file to another. 4M
Ans
Page No: 16 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Sr. Array Vector
No.
4 Array can store primitive type data Vector are store non-primitive type data
element. element
8 Array allocates the memory for the Vector allocates the memory
fixed size ,in array there is wastage of dynamically means according to the
memory. requirement no wastage of memory.
9 No methods are provided for adding Vector provides methods for adding and
and removing elements. removing elements.
10 In array wrapper classes are not used. Wrapper classes are used in vector
elementAT( ):
The elementAt() method of Java Vector class is used to get the element at the specified
Page No: 17 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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 'salary with data members empid', ‘name' 6M
and ‘basicsalary'. Write an interface 'Allowance’ which stores rates of
calculation 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 it.
Ans interface allowance 6 M for
{ correct
double da=0.9*basicsalary; program
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()
{
System.out.println("Empid of Emplyee="+empid);
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+ basicsalary);
}
}
a) Write a program to check whether the string provided by the user is palindrome 6M
or not.
class palindrome
System.out.println("Enter String:");
String word=br.readLine( );
int l=0;
int flag=1;
int r=len;
while(l<=r)
Page No: 20 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
if(word.charAt(l)==word.charAt(r))
l++;
r--;
else
flag=0;
break;
if(flag==1)
System.out.println("palindrome");
else
System.out.println("not palindrome");
b) Define thread priority ? Write default priority values and the methods to set 6M
and change them.
Ans Thread Priority: 2 M for
define
In java each thread is assigned a priority which affects the order in which it is scheduled for Thread
running. Threads of same priority are given equal treatment by the java scheduler. priority
Default priority values as follows 2 M for
Page No: 21 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
The thread class defines several priority constants as: - default
priority
MIN_PRIORITY =1 values
NORM_PRIORITY = 5
MAX_PRIORITY = 10
2 M for
Thread priorities can take value from 1-10. method to
set and
getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given change
thread.
import java.lang.*;
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(b4);
Page No: 23 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
else if (e.getSource() == b3){
c = a * b;
else if (e.getSource() == b4){
c = a / b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new sample();
}
}
Page No: 24 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
SUMMER – 2023 EXAMINATION
Model Answer – Only for the Use of RAC Assessors
i) Class
ii) Object
Ans i) Class: Class is a set of object, which shares common characteristics/ behavior and 1 M for any
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 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
public static void main(String args[])
{
Student s1=new Student(); //creating an object of Student
}
}
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 s1 by new keyword.
b) Enlist any two access specifier with syntax. 2M
package nameOfPackage;
Example:
package p1;
Accessing Package:
• Package can be accessed using keyword import.
• There are 2 ways to access java system packages:
o Package can be imported using import keyword and the wild card(*) but
drawback of this shortcut approach is that it is difficult to determine from
which package a particular member name.
Syntax: import package_name.*;
Page No: 2 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
For e.g. import java.lang.*;
o The package can be accessed by using dot(.) operator and can be terminated
using semicolon(;)
Syntax: import package1.package2.classname;
d) Give a syntax of following thread method 2M
i) Notify ( )
ii) Sleep ( )
ii) sleep()
Sleep() causes the current thread to suspend execution for a specified period.
Syntax: public static void sleep(long milliseconds)
Ans User-define Parameter can be applied in applet using <PARAM…> tags. Syntax of
<param> - 1
Each <PARAM…> tag has a name and value attribute.
M
Syntax: <PARAM name = ……… Value = “………” >
And syntax
For example, the param tags for passing name and age parameters looks as shown below: of
getParameter
<param name=”name” value=”Ramesh” />
( )- 1 M
<param name=”age” value=”25″ />
The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page. The syntax of getParameter() method is as follows:
String getParameter(String param-name);
Example:
n = getParameter("name");
a = getParameter("age");
Page No: 3 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
f) Define stream class and list types of stream class. 2M
Ans A java stream is a group of objects that can be piped together to produce the desired result. Define
Streams are used in Java to transfer data between programs and I/O devices like a file, stream
network connections, or consoles. class=1 M
and
any 2 types
of stream
class=1 M
Ans In Java, type casting is a method or process that converts a data type into another data Definition of
Page No: 4 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
type in both ways manually and automatically. The automatic conversion is done by the type casting-
1M
compiler and manual conversion performed by the programmer.
Type casting is of two types: widening, narrowing. Types of
type
Widening (Implicit)
casting-1 M
• The process of assigning a smaller type to a larger one is known as widening or
implicit.
Byte short int long float double Example-2
M
For e.g.
(1 M for
class widening
each
{ example)
public static void main(String arg[])
{
int i=100;
long l=I;
float f=l;
System.out.println(“Int value is”+i);
System.out.println(“Long value is”+l);
System.out.println(“Float value is”+f);
}
}
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
For e.g.
class narrowing
{
Public static void main(String[])
{
Double d=100.04;
Long l=(long) d;
Int i=(int) l;
Page No: 5 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
System.out.println(“Int value is”+i);
System.out.println(“Long value is”+l);
System.out.println(“Float value is”
}
}
b) Differentiate between String and String Buffer Class. (any four points) 4M
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; program-4 M
import java.io.*;
class myException extends Exception
{
myException(String msg)
{
super(msg);
}
}
class agetest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Scanner class is also valid
try
{
System.out.println("enter the age : ");
int n=Integer.parseInt(br.readLine());
if(n < 18 )
throw new myException("Invalid Age"); //user defined exception
Page No: 6 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
else
System.out.println("Valid age");
}
catch(myException e)
{
System.out.println(e.getMessage());
}
catch(IOException ie)
{}
}
}
d) Write a program for reading and writing character to and from the given files 4M
using character stream classes.
OR
class ArmstrongWhile
{
public static void main(String[] arg)
{
int i=1,a,arm,n,temp;
System.out.println("Armstrong numbers between 0 to 999 are");
while(i<500)
{
n=i;
arm=0;
while(n>0)
{
a=n%10;
arm=arm+(a*a*a);
n=n/10;
}
if(arm==i)
System.out.println(i);
i++;
}
}
}
b) Explain the applet life cycle with neat diagram. 4M
Page No: 8 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Ans Diagram-2
M and
explanation
–2M
Applet Life Cycle: An Applet has a life cycle, which describes how it starts, how it
operates and how it ends. The life cycle consists of four methods: init(), start(), 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
cycle 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. In the start method user can interact within the applet.
public void start()
{
……..
……..
}
Idle (The Stop() method): An applet becomes idle when it is 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 cycle 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()
Page No: 9 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
{
……..
……..
}
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. It is 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
screen.
The display includes text, images, graphics and background. This happens immediately
after the applet enters into the running state. Almost every applet will have a paint()
method and can be called several times during an applet’s life cycle. The paint() method is
called whenever a window is required to paint or repaint the applet.
public void paint(Graphics g)
{
……..
……..
}
c) Describe the package in java with suitable example. 4M
Ans • Java provides a mechanism for partitioning the class namespace into more Description-
manageable parts called package (i.e package are container for a classes). 2 M,
• 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 files of any classes
which are declared in a
• package must be stored in a directory which has same name as package name.
• The directory must match with the package name exactly.
• A hierarchy can be created by separating package name and sub package name by
a period(.) as pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3.
• The classes and methods of a package must be public.
• To access package In a Java source file, import statements occur immediately
following the package. statement (if it exists) and before any class definitions.
• Syntax: import pkg1[.pkg2].(classname|*);
Page No: 10 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
• Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
}
Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
d) Enlist types of Byte stream class and describe input stream class and output 4M
stream class.
Page No: 11 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
of bytes that are read. At the end returns –1.
3. int read(byte buffer[ ], int offset, int numbytes)- Attempts to read up to numbytes
bytes into buffer starting at buffer[offset]. 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 till 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.
Ans 1. Compile & Interpreted: Java is a two staged system. It 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 is in the form of object. All program codes
and data reside within objects and classes. Similar to other OOP languages java also has
basic OOP properties such as encapsulation, polymorphism, data abstraction, inheritance
etc. Java comes with an extensive set of classes (default) in packages.
4. Robust & Secure: Java is a robust in the sense that it provides many safeguards to
ensure reliable codes. Java incorporates concept of exception handling which captures
errors and eliminates any risk of crashing the system. Java system not only verify all
memory access but also ensure that no viruses are communicated with an applet. It does
not use pointers by which you can gain access to memory locations without proper
Page No: 12 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
authorization.
5. Distributed: It is designed as a distributed language for creating applications on
network. It has ability to share both data and program. Java application can open and
access remote object on internet as easily as they can do in local system.
6. Multithreaded: It can handle multiple tasks simultaneously. Java makes this possible
with the feature of multithreading. This means that we need not wait for the application to
finish one task before beginning other.
7. Dynamic and Extensible: Java is capable of dynamically linking new class library’s
method and object. Java program supports function written in other languages such as C,
C++ which are called as native methods. Native methods are linked dynamically at run
time.
b) Explain any four methods of vector class with example. 4M
Example:
Page No: 13 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
import java.io.*;
import
java.lang.*;
import
java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new
vector(); Integer
s1=new Integer(1);
Integer s2=new
Integer(2); String
s3=new
String("fy"); String
s4=new
String("sy");
Character s5=new
Character('a'); Character
s6=new Character('b');
Float s7=new
Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s5);
v.addElement(s6);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}
c) Describe interface in java with suitable example. 4M
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. – 2 M, any
Syntax: suitable
access interface InterfaceName example – 2
{ M
Variables declaration;
Methods declaration;
Page No: 14 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
Example:
interface sports
{
int sport_wt=5;
public void disp();
}
class test
{
int roll_no;
String name;
int m1,m2;
test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class result extends test implements sports
{
result (int r, String nm, int m11,int m12)
{
super (r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
public static void main(String args[])
{
result r= new result(101,"abc",75,75);
r.disp();
}
}
Output :
D:\>java result
Roll no : 101
Name : abc
sub1 : 75
sub2 : 75
sport_wt : 5
Page No: 15 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
total : 155
d) Write an applet program for following graphics method. 4M
i) Drawoval ( )
ii) Drawline ( )
e) Enlist any four methods of file input stream class and give syntax of any two 4M
methods.
Ans • Input Stream Classes: java.io.InputStream is an abstract class that contains the One method
basic methods for reading raw bytes of data from a stream. The InputStream class –1M
defines methods for performing the input functions like: reading bytes, closing
streams, marking positions in streams, skipping ahead in a stream and finding the
number of bytes in a stream.
• Input stream class methods:
1. int read ()- Returns an integer representation of next available byte of input.-1 is
returned at the stream end.
2. int read (byte buffer[ ])- Read up to buffer.length bytes into buffer & returns
actual number
of bytes that are read. At the end returns –1.
3. int read(byte buffer[ ], int offset, int numbytes)- Attempts to read up to numbytes
bytes
into buffer starting at buffer[offset]. Returns actual number of bytes that are read.
Page No: 16 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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 till
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.
a) Write a program to copy all elements of one array into another array. 6M
System.out.println();
m1, m2, m3
Class: Result
display ()
Fig. No. 1
int sports_mark=20;
class Student
String S-name;
int Roll_no, m1, m2, m3;
Student(String n, int a, int b, int c, int d)
S-name = n;
Roll_no = a;
Page No: 18 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
m1 = b;
m2 = c;
m3 = d;
void showdata()
super(n, a, b, c, d );
void dispaly()
super.showdata();
int total=(m1+m2+m3);
float result=(total+Sports_mark)/total*100;
Page No: 19 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
System.out.println(“result of student is:”+result);
class studentsDetails
r.display();
}
c) Write a program to print even and odd number using two threads with delay 6M
of 1000ms after each number.
Page No: 20 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
}
}
}
}
class even extends Thread
{
public void run()
{
for(int i=0;i<=20;i=i+2)
{
System.out.println("EVEN="+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
}
class oddeven
{
public static void main(String arg[])
{
odd o=new odd();
even e=new even();
Page No: 21 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
o.start();
e.start();
}
}
Ans 2 M for
diagram, 4
M for
explanation
Thread Life Cycle Thread has five different states throughout its life.
1) Newborn State
When a thread object is created it is said to be in a new born state.When the thread is in a
new born state it is not scheduled running from this state it can be scheduled for running
by start() or killed by stop(). If put in a queue it moves to runnable state.
2) Runnable State
It means that thread is ready for execution and is waiting for the availability of the
processor i.e. the thread has joined the queue and is waiting for execution. If all threads
have equal priority then they are given time slots for execution in round robin fashion.The
thread that relinquishes control joins the queue at the end and again waits for its turn. A
thread can relinquish the control to another before its turn comes by yield().
Page No: 22 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
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.
o 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().
o sleep(): We can put a thread to sleep for a specified time period using sleep(time) where
time is in ms. It reenters the runnable state as soon as period has elapsed /over.
5) Dead State
Whenever we want to stop a thread form running further we can call its stop(). The stop()
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
Thread should be in any one state of above and it can be move from one state to another by
different methods and ways.
b) Write a program to generate following output using drawline () method. Refer 6M
Fig. No. 2.
Fig. No. 2
Page No: 23 | 26
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
g.drawLine(200,100,300,200);
g.drawLine(300,200,100,200);
}
}
/*<applet code="Triangle.class" height=300 width=200> </applet>*/
OR
Using drawPolygon() method
import java.applet.*;
import java.awt.*;
public class Triangle extends Applet
{
public void paint(Graphics g)
{
int a[]={100,200,300,100};
int b[]={200,100,200,200};
int n=4;
g.drawPolygon(a,b,n);
}
}
/*<applet code="Triangle.class" height=300 width=200> </applet>*/
Ans Constructor: A constructor in Java is a special method that is used to initialize objects. 2 M for
definition of
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