0% found this document useful (0 votes)
15 views

Java5 Organized

The document is a model answer for the Winter 2022 Java Programming examination by the Maharashtra State Board of Technical Education. It includes important instructions for examiners on assessing student answers, a variety of questions covering Java concepts, and example answers with marking schemes. The content addresses topics such as relational operators, access specifiers, threading, applets vs applications, and file handling in Java.

Uploaded by

sydnehu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java5 Organized

The document is a model answer for the Winter 2022 Java Programming examination by the Maharashtra State Board of Technical Education. It includes important instructions for examiners on assessing student answers, a variety of questions covering Java concepts, and example answers with marking schemes. The content addresses topics such as relational operators, access specifiers, threading, applets vs applications, and file handling in Java.

Uploaded by

sydnehu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
WINTER – 2022 EXAMINATION
Subject Name: Java Programming Model Answer Subject Code: 22412

Important Instructions to examiners: XXXXX


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.
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
+Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
model answer.

Q. Sub Answer Marking


No. Q. N. Scheme

1 Attempt any FIVE of the following: 10 M

a) State any four relational operators and their use. 2M

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

b) Enlist access specifiers in Java. 2M

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)
__________________________________________________________________________________________________

e) Define thread. Mention 2 ways to create thread. 2M

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)
__________________________________________________________________________________________________
2. Attempt any THREE of the following: 12 M

a) Write a program to check whether the given number is prime or not. 4M

Ans Code: 4M (for any


correct
class PrimeExample program
{ and logic)

public static void main(String args[]){

int i,m=0,flag=0;

int n=7;//it is the number to be checked

m=n/2;

if(n==0||n==1){

System.out.println(n+" is not prime number");

}else{

for(i=2;i<=m;i++){

if(n%i==0){

System.out.println(n+" is not prime number");

flag=1;

break;

if(flag==0) { System.out.println(n+" is prime number"); }

}//end of else

Output:

7 is prime number

Page No: 5 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
c) Describe Life cycle of thread with suitable diagram. 4M

Ans 1) Newborn State 1M-digram


A NEW Thread (or a Born Thread) is a thread that's been created but not yet of life
started. It remains in this state until we start it using the start() method. cycle
3M-
The following code snippet shows a newly created thread that's in the NEW state:
explanation
Runnable runnable = new NewState();

Thread t = new Thread(runnable);

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.

o suspend() : Thread can be suspended by this method. It can be rescheduled


by resume().
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

Page No: 7 | 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.

g) Draw the hierarchy of stream classes. 2M

Ans 2M-Correct
diagram

Fig: hierarchy of stream classes

Page No: 4 | 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

Ans Any two

1 M each

Page No: 2 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________

Fig: Life cycle of Thread


d) Write a program to read a file (Use character stream) 4M

Ans import java.io.FileWriter; 4M (for


import java.io.IOException; correct
public class IOStreamsExample { program
public static void main(String args[]) throws IOException { and logic)
//Creating FileReader object
File file = new File("D:/myFile.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()];
//Reading data from the file
reader.read(chars);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileWriter writer = new FileWriter(out);
//Writing data to the file
writer.write(chars);
writer.flush();
System.out.println("Data successfully written in the specified file");
}
}

3. Attempt any THREE of the following: 12 M

Page No: 8 | 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)
__________________________________________________________________________________________________
a) Write a program to find reverse of a number. 4M

Ans public class ReverseNumberExample1 Any


Correct
{ public static void main(String[] args) program
{ with proper
logic -4M
int number = 987654, reverse =0;

while(number !=0)

int remainder = number % 10;

reverse = reverse * 10 + remainder;

number = number/10;

System.out.printtln(“The reverse of the given number is: “ + reverse);

} }

b) State the use of final keyword with respect to inheritance. 4M

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)
__________________________________________________________________________________________________
(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

Example: g.drawArc(10, 10, 30, 40, 40, 90);

d) Write any four methods of file class with their use. 4M

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.

4. Attempt any THREE of the following: 12 M

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)
__________________________________________________________________________________________________
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)
__________________________________________________________________________________________________
“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)
__________________________________________________________________________________________________
bytes.

Ans Data type


name, size
Data Type Size
and default
Byte 1 Byte
Short 2 Byte value and
Int 4 Byte description
Long 8 Byte carries 1 M
Double 8 Byte
Float 4 Byte
Char 2 Byte
boolean 1 Bit
b) Write a program to add 2 integer, 2 string and 2 float values in a vector. 4M
Remove the element specified by the user and display the list.

Ans import java.io.*; Correct


import java.lang.*; program- 4
import java.util.*; M, stepwise
class vector2 can give
{ marks
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
v.addElement(s7);
v.addElement(s8);
System.out.println(v);
v.removeElement(s2);
v.removeElementAt(4);
System.out.println(v);
}
}
c) Develop a program to create a class ‘Book’ having data members author, title 4M
and price. Derive a class 'Booklnfo' having data member 'stock position’ and

Page No: 12 | 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.

c) Give the usage of following methods 4M


i) drawPolygon ()
ii) DrawOval ()
iii) drawLine ()
iv) drawArc ()
Ans i) drawPolygon (): Method use
with
 drawPolygon() method is used to draw arbitrarily shaped figures. description
 Syntax: void drawPolygon(int x[], int y[], int numPoints) 1M
 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.drawPolygon(xpoints,ypoints,num);
ii) drawOval ():
 To draw an Ellipses or circles used drawOval() method can be used.
 Syntax: void drawOval(int top, int left, int width, int height) The ellipse is drawn
within a bounding rectangle whose upper-left corner is specified by top and left
and whose width and height are specified by width and height to draw a circle or
filled circle, specify the same width and height the following program draws
several ellipses and circle.
 Example: g.drawOval(10,10,50,50);
ii) drawLine ():
 The drawLine() method is used to draw line which take two pair of coordinates,

Page No: 10 | 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 import java.io.*; Correct


class copyf program- 4
{ M
public static void main(String args[]) throws IOException
{
BufferedReader in=null;
BufferedWriter out=null;
try
{
in=new BufferedReader(new FileReader("input.txt"));
out=new BufferedWriter(new FileWriter("output.txt"));
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
System.out.println("File copied successfully");
}
finally
{
if(in!=null)
{
in.close();
}
if(out!=null)
{
out.close();
}
}
}
}

5. Attempt any TWO of the following: 12 M

a) Compare array and vector. Explain elementAT( ) and addElement( ) methods. 6M

Ans
Page No: 16 | 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

Ans Adding Applet to the HTML file: Steps – 2M


Steps to add an applet in HTML document Example –
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the body section 2M
of HTML
file.
2. Specify the name of the applet’s .class file.
3. If the .class file is not in the current directory then use the codebase parameter to
specify:-
a. the relative path if file is on the local system, or
b. the uniform resource locator(URL) of the directory containing the file if it is on a remote
computer.
4. Specify the space required for display of the applet in terms of width and height in
pixels.
5. Add any user-defined parameters using <param> tags
6. Add alternate HTML text to be displayed when a non-java browser is used.
7. Close the applet declaration with the </APPLET> tag.
Open notepad and type the following source code and save it into file name

Page No: 14 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
Sr. Array Vector
No.

1 An array is a structure that holds The Vector is similar to array holds


4 M for
multiple values of the same type. multiple objects and like an array; it
any 4
contains components that can be
correct
accessed using an integer index.
points
2 An array is a homogeneous data type Vectors are heterogeneous. You can
1 M for
where it can hold only objects of one have objects of different data types
elementAt()
data type. inside a Vector.
1 M for
3 After creation, an array is a fixed- The size of a Vector can grow or shrink
addElement
length structure. as needed to accommodate adding and
()
removing items after the Vector has
been created.

4 Array can store primitive type data Vector are store non-primitive type data
element. element

5 Array is unsynchronized i.e. Vector is synchronized i.e. when the


automatically increase the size when size will be exceeding at the time;
the initialized size will be exceed. vector size will increase double of
initial size.

6 Declaration of an array : Declaration of Vector:

int arr[] = new int [10]; Vector list = new Vector(3);

7 Array is the static memory allocation. Vector is the dynamic memory


allocation

8 Array allocates the memory for the 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

11 Array is not a class. Vector is a class.

elementAT( ):

The elementAt() method of Java Vector class is used to get the element at the specified
Page No: 17 | 24
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
super(i,n,b);
ta=t;
}
void disp()
{
display();
System.out.println("da of Employee="+da);
}
public void netsalary()
{
double net_sal=basicsalary+ta+hra+da;
System.out.println("netSalary of Employee="+net_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
net_salary s=new net_salary(11, “abcd”, 50000);
s.disp();
s.netsalary();
}
}
c) Define an exception called 'No Match Exception' that is thrown when the 6M
passward accepted is not equal to "MSBTE'. Write the program.

Ans import java.io.*; 6 M for


class NoMatchException extends Exception correct
{ program
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
Page No: 19 | 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)
__________________________________________________________________________________________________
}
c) Design an applet to perform all arithmetic operations and display the result by using 6M
labels. textboxes and buttons.
Ans import java.awt.*; 6 M for
import java.awt.event.*; correct
public class sample extends Frame implements ActionListener { program
Label l1, l2,l3;
TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;
sample() {
l1=new Lable(“First No.”);
l1.setBounds(10, 10, 50, 20);
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
l2=new Lable(“Second No.”);
l2.setBounds(10, 60, 50, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
l3=new Lable(“Result”);
l3.setBounds(10, 110, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
b3 = new Button("*");
b3.setBounds(220, 200, 50, 50);
b4 = new Button("/");
b4.setBounds(320,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);

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)
__________________________________________________________________________________________________
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}

6. Attempt any TWO of the following: 12 M

a) Write a program to check whether the string provided by the user is palindrome 6M
or not.

Ans import java.lang.*; 6 M for


correct
import java.io.*; program
import java.util.*;

class palindrome

public static void main(String arg[ ]) throws IOException

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter String:");

String word=br.readLine( );

int len=word.length( )-1;

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)
__________________________________________________________________________________________________
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);
}
}

class net_salary extends salary implements allowance


{
float ta;
net_salary(int i, String n, float b, float t)
{
Page No: 18 | 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)
__________________________________________________________________________________________________
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.

setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign


the priority of the thread to newPriority. The method throws IllegalArgumentException if
the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

import java.lang.*;

public class ThreadPriorityExample extends Thread


{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().gtName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrority();
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPiority());
}
Page No: 22 | 24

You might also like