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

JPR-III Model Answer

The document contains a practice test for a Java programming exam with 3 questions and subparts. Question 1 covers topics like object-oriented principles in Java, byte code, inheritance, and the ternary operator. Question 2 involves designing an applet to display colored circles and creating a custom exception class. The final question covers packages in Java and adding a class to a user-defined package.

Uploaded by

Vaishnavi Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

JPR-III Model Answer

The document contains a practice test for a Java programming exam with 3 questions and subparts. Question 1 covers topics like object-oriented principles in Java, byte code, inheritance, and the ternary operator. Question 2 involves designing an applet to display colored circles and creating a custom exception class. The final question covers packages in Java and adding a class to a user-defined package.

Uploaded by

Vaishnavi Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Model Answer

Practice Test - III

Subject: Java Programming (17515) Marks: 100 Time: 03 HOUR


---------------------------------------------------------------------------------------------------------------------
Q 1. A) Attempt any Three of the following 12 Marks
a) Explain, why Java is called as true object oriented language. (Each point - 1 Mark)
Ans:
1. Java is a OOP language and it is not a pure Object Based Programming Language.
2. Many languages are Object Oriented. There are seven qualities to be satisfied for a
programming language to be pure Object Oriented. They are:
1. Encapsulation/Data Hiding
2. Inheritance
3. Polymorphism
4. Abstraction
5. All predefined types are objects
6. All operations are performed by sending messages to objects
7. All user defined types are objects.
3. Java is not because it supports Primitive datatype such as int, byte, long... etc, to be used,
which are not objects.
4. Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and
Boolean, int and methods are all objects.
b) What do you understand by Byte code?
(2 marks for diagram and 2 marks for explanation)
Ans:
1. JVM is the Java Virtual Machine the java compiler compiles produces an intermediate code
known as byte code for the java virtual machine, which exists only in the computer memory.
2. It is a simulated computer within the computer and does all the major functions of a real
computer
source code byte code process of compilation Virtual machine code is not machine specific.
3. Machine specific code is generated by Java Interpreter by acting as an intermediary between
the virtual machine and the real machine. Interpreter is written for each type of machine.
4. Virtual machine real machine Process of converting byte code into machine code.
c) What is single inheritance? Explain with suitable example.
[2- marks for explanation, 2-marks for Example]
Ans: The mechanism of creating new classes from old one is called as inheritance. The old class
is called known as the base class or super class or parent class, & the new one is called as derived
or sub or child class. The inheritance allows subclasses to inherit all the variables of their parent
classes. Inheritance can be of different types. Single level inheritance is that in which there is only
one super class.

Class A

Class B

Where Class A is a parent class and class B is derived from A.


Example:
//Single level inheritance
import java.lang.*;
class Square //parent or base class
{
int length;
Square(int x)
{
length=x;
}
void area()
{
int area=length*length;
System.out.println("Area of Square"+area);
}
}
class Rectangl extends Square // child or derived class
{
int breadth;
Rectangl(int x, int y)
{
super(x);
breadth=y;
}
void rectarea()
{
int area1=length*breadth;
System.out.println("Area of Rectangle :"+area1);
}
}
class Shape1
{
public static void main(String args[])
{
Rectangl r = new Rectangl(20,30);
r.rectarea();
r.area();
}
}
/* Output
C:\jdk1.3\bin>java Shape1
Area of Rectangle :600
Area of Square400 */
d) „?‟ what this operator is called? Explain with suitable example.
(Name of the operator – 1M, Explanation and example – 3 M)
Ans:
1) „?:‟ is called as conditional operator or ternary operator.
2) It can be used to check condition in one line, instead of writing if…else statement.
3) Its format is (condtion ? true case : false case)
4) example

int a,b; a=10; b=(a>5? 12 : 20);


Here b= 12 as a is 10 and condition is true. If value of a is changed to 15 then b will have value as
20.
B) Attempt any one of the following. 6 Marks
a) What is need of Interface in Java? Explain it with suitable example.
(Need of interface – 2 marks Program: 1 mark – declaration of interface, 1 mark - use of
interface, 1 mark- Syntax, 1 mark- Logic)
Ans: Need of interface: Java does not support multiple inheritance. That is classes in Java cannot
have more than one super class. Java allows the use of interface to implement multiple inheritance.
Although a Java class cannot be a subclass of more than one super class, it can implement more
than one interfaces.
interface Area
{
final static float pi = 3.14F;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return(pi*x * x);
}
}
class InterfaceArea
{
public static void main(String args[ ])
{
Rectangle rect = new Rectangle ( );
Circle cir = new Circle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(5,6));
area = cir;
System.out.println("Area Of Circle = "+ area.compute(10,0));
}
}
b) Define a class „employee‟ with data members as empid, name and salary. Accept data
for 5 objects and print it. (Explanation for array of objects –1 mark. 4 marks for logic 1
mark for syntax of program)
Ans: When same type of data is to be stored in contiguous memory allocations arrays are used.
When objects are stored in array, it is called array of objects.
import java.io.*;
class EmployeeDetails
{
int empid;
String name;
float salary;
EmployeeDetails()
{
try
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the employee id");
empid = Integer.parseInt(b.readLine());
System.out.println("Enter the name");
name = b.readLine();
System.out.println("Enter the salary");
salary = Float.parseFloat(b.readLine());
}
catch(Exception e)
{}
}
public String toString()
{
return "empid: " + empid + " name: " + name + " salary: " + salary;
}
public static void main(String a[])
{
EmployeeDetails[] e = new EmployeeDetails[5];
for(int i = 0; i<5; i++)
{
e[i] = new EmployeeDetails();
}
System.out.println("The details of five employees are: ");
for(int i = 0;i<5; i++)
{
System.out.println(e[i].toString());
}
}
}
Q 2. Attempt any Two of the following 16 Marks
a) Design an applet which displays three circle one below the other and fill them red, green
and yellow color respectively.( 3M- correct logic, 2M – correct use of class, packages and
<applet> tag , 3M – correct syntaxes)
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(50,50,100,100);
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
/*<applet code=myapplet width= 300 height=300> </applet>*/
Output:

b) What is throw clause? Write a program to create own exception class


Ans: The uses of throw keyword are as:
1. The throws keyword is used in method declaration, in order to explicitly specify the exceptions
that a particular method might throw. When a method declaration has one or more exceptions
defined using throws clause then the method-call must handle all the defined exceptions.
2. When defining a method you must include a throws clause to declare those exceptions that
might be thrown but doesn‘t get caught in the method.
3. If a method is using throws clause along with few exceptions then this implicitly tells other
methods that - ― If you call me, you must handle these exceptions that I throw‖.
Syntax of Throws in java:
void MethodName( ) throws ExceptionName
{
Statement1
...
...
}
E.g:
public void sample( ) throws IOException
{
//Statements
//if (somethingWrong)
IOException e = new IOException( );
throw e;
//More Statements
}

//Program throw a user defined exception if the given number is not positive

import java.io.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class Pr8
{
public static void main(String a[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter any no:");
int n=Integer.parseInt(br.readLine());
if(n<0)
throw new MyException("Negative Number!");
else
throw new MyException("Positive Number!");
}
catch(MyException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

c) What is package? State any four system packages along with their use? How to add class
to a user defined packages?
(package – 2 M, Four packages and their use – 1 M each, how to add class to package – 2 M)
Ans:
Package: Java provides a mechanism for partitioning the class namespace into more manageable
parts. This mechanism is the „package‟. The package is both naming and visibility controlled
mechanism. System packages with their use:(Any 4 can be considered)
1. java.lang - language support classes. These are classes that java compiler itself uses and
therefore they are automatically imported. They include classes for primitive types, strings, math
functions, threads and exceptions.
2. java.util – language utility classes such as vectors, hash tables, random numbers, date etc.
3. java.io – input/output support classes. They provide facilities for the input and output of data
4. java.awt – set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
5. java.net – classes for networking. They include classes for communicating with local computers
as well as with internet servers.
6. java.applet – classes for creating and implementing applets.

To add a class to user defined package:


1) Include a package command as the first statement in a Java source file.
2) Any classes declared within that file will belong to the specified package.
3) The package statement defines a name space in which classes are stored.
4) Example :

package MyPack;
public class Balance
{...}
Then class Balance in included inside a user defined package „MyPack‟.

3. Attempt any four. 16 Marks


a)Explain following methods related to threads:
1) suspend( )
2) resume( )
3) yield( )
4) wait( )
( 1 M – each method’s syntax and use)
Ans:
1) suspend( ) -
syntax :
public void suspend( )
This method puts a thread in suspended state and can be resumed using resume() method.

2) resume( )
syntax :
public void resume( )
This method resumes a thread which was suspended using suspend() method.

3) yield( )
syntax :
public static void yield()
The yield() method causes the currently executing thread object to temporarily pause and allow
other threads to execute.
4) wait()
syntax :
public final void wait()

This method causes the current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.
b) Describe any four methods from graphics class.
(Each method – 1 mark)
Ans: The methods contained within the Graphics Class in the package java.awt.
Following are some of the graphics class methods
1. drawLine( ):
I. This method draws a line between (x1, y1) and (x2, y2).
II. The line is drawn below and to the left of logical coordinate.
III. Syntax:
public void drawLine(int x1, int y1, int x2, int y2);
IV. Eg:
public void drawLine(10, 10, 100, 100);
2. DrawString( );
I. This method draws the text given by the specified string, using this graphics context's
current font and color.
II. The baseline of the leftmost character is at position (x, y) in this graphics context's
coordinate system.
III. Syntax:
public void drawString(String str, int x, int y);
IV. Eg:
public void drawString(―Hello Java‖, 50, 50);

3. drawRect( );
I. This method draws the outline of the specified rectangle. The left and right edges of the
rectangle are at x and x + width.
II. The top and bottom edges are at y and y + height. The rectangle is drawn using the
graphics context's current color.
III. Syntax:
public void drawRect(int x, int y, int width, int height);
IV. Eg:
public void drawRect(10,10,120,120);
4. fillRect( ):
I. This method fills the specified rectangle. The left and right edges of the rectangle
are at x and x + width - 1. The top and bottom edges are at y and y + height - 1.
II. The resulting rectangle covers an area width pixels wide by height pixels tall.
III. Syntax:
Public void fillRect( int x, int y, int height, int width );
IV. Eg:
Public void fillRect(0,0,100,100);
c) How do we put an applet into web page? Explain. (Each point 1 marks)
Ans: An Applet can embed into the web page as below:
1. An applet developed locally and stored in a local system is known as local applet. When a
web page is trying to find a local applet, it does not need to use the Internet connection. It
simple searches the directories in the local system and locates and loads the specified
applet.
2. In the case of local applets, CODEBASE may be absent or may specify a local directory. A
remote applet is that which is developed by someone else and stored on a remote computer
connected to the Internet.
3. If our system is connected to the Internet, we can download the remote applet onto our
system via at the Internet and run it. In order to locate and load a remote applet, we must
know the applet‟s address on the Web.
4. This address is known as Uniform Resource Locator (URL) and must be specified in the
applet‟s HTML document as the value of the CODEBASE attribute. e.g. CODEBASE =
http://www, .msbte.com/applets
d) Write a program to accept a number as command line argument and print the number is
even or odd. (Any other program with correct program may also be considered) (Logic 2-M,
Syntax 2-marks)
Ans:
public class CMD
{
public static void main(String key[ ])
{
int x=Integer.parseInt(key[0]);
if (x%2 ==0)
{
System.out.println("Even Number");
}
else
{
System.out.println("Odd Number");
}
}
}
e) Explain use of following methods:
1) indexOf( )
2) charAt( )
3) substring( )
4) replace( )
(1 mark each for each method use with parameters and return type.) (Any one syntax of
each method should be considered)
Ans:
1. indexOf( ):
int indexOf(int ch):
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex):
Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.
int indexOf(String str):
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex):
Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.

2. charAt( ):
char charAt(int index):
Returns the char value at the specified index.
3. substring( ):
String substring(int beginIndex):
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex):
Returns a new string that is a substring of this string. The substring begins at the specified
beginIndex and extends to the character at index endIndex - 1
4. replace( ):
String replace(char oldChar, char newChar): Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

Q 4. A) Attempt any Three. 12 Marks


a) Write down the differences between abstract class and interface.
(Each point - 1 mark)
Ans: Differences between abstract class and interface are:
Abstract class Interface
Keywords ‗abstract‘, ‗class‘ are used to Keyword ‗interface‘ is used to declare
declare it. interface.
The variables declared in an abstract class are Variables declared in interface are ‗static‟ and
instance variables „final‟ by default
Abstract Class methods can contain Interface methods are totally abstract methods
implementation which does not contain implementation.
It can‘t create multiple inheritance All types of inheritances are possible in
interface
An abstract class can inherit a class and can Interface can only inherit another interface
implement the interface also

b) What is stream? Explain various types of streams.


(Definition - 1 marks, Explanation - 03 marks)
Ans: A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.
The stream in the java.io package supports many data such as primitives, Object, localized
characters, etc.
Types of Streams:
1. Byte Streams
2. Character Streams
3. Standard Streams:
1. Byte Streams:
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.
2. Character Streams:
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are , FileReader and
FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream.
3. Standard Streams:
All the programming languages provide support for standard I/O where user's program can
take input from a keyboard and then produce output on the computer screen. Java provides
following three standard streams
 Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
 Standard Output: This is used to output the data produced by the user's program and
usually a computer screen is used to standard output stream and represented as System.out.
 Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
c) Describe the following String class methods with example:
i) length( ) ii) equals( )
iii) charAt( ) iv) compareTo( )
(Each Method – 01 mark)
Ans: Following are the methods of the String class.
i) length( ):
This method is used to find total number of characters present in the string.
Syntax:
int length()
Example:
String s = ―Santosh‖;
int len = s.length();
This will print the value 6 which is the length of string ‗s‘.
ii) equals( ):
These methods are used to check two strings for equality and returns the boolean value true if they
are equal else false.
Syntax:
boolean equals(String str)
Example:
String a = ―Welcome‖;
String b = ―WELCOME‖;
if(a.euals(b)) //false
System.out.println(―Equals in case‖);
iii) charAt( ):
This method extracts(get) a single character from the string.
Syntax:
char charAt(int index)
It extracts the character of invoking String from position specified by ‗index‘.
Example:
String s = ―Gramin‖;
char ch = s.charAt(2); //ch will be ‗a‘ after this
iv) coampareTo( ):
This method is used to compare two string is equal or not.
Syntax:
int compareTo(Object o)
Eg:
String str1=‖gramin‖
String str1=‖gramin‖
int result = str1.compareTo( str2 );
d) Write a simple applet to draw rectangle which is filled with red color.
Ans: //Applet to draw rectangle which is filled with red color.
/* <applet code="FilledRectangleExample" width=200 height=200>
</applet> */
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class FilledRectangleExample extends Applet


{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(10, 10, 50,100);
}
}
Output:
B) Attempt any one: 06 Marks
a) Write any four mathematical functions used in Java.
(1 M – each method’s syntax and use) Note: Any four methods can be considered.
Ans:
1) min( ) :
Syntax:
static int min(int a, int b)
Use: This method returns the smaller of two int values.
2) max( ) :
Syntax:
static int max(int a, int b)
Use: This method returns the greater of two int values.
3) sqrt( )
Syntax:
static double sqrt(double a)
Use : This method returns the correctly rounded positive square root of a double value.
4) pow( ) :
Syntax:
static double pow(double a, double b)
Use : This method returns the value of the first argument raised to the power of the second
argument.
5) exp( )
Syntax:
static double exp(double a)
Use : This method returns Euler's number e raised to the power of a double value.
6) round( ) :
Syntax:
static int round(float a)
Use : This method returns the closest int to the argument.
7) abs( )
Syntax:
static int abs(int a)
Use : This method returns the absolute value of an int value.
b) Create an applet with title MyApplet, size 600 x 400. Display a string “Hi I am Java
developer” with „red‟ color & font name=”Calibri”, style=BOLD, size=20. Show the
status as “Applet is running”.
Ans:/*Create an applet with title MyApplet, size 600 x 400. Display a string ―Hi I am Java
developer‖ with ‗red‘ color & font name=‖Calibri‖, style=BOLD, size=20. Show the status as
―Applet is Running‖.*/
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.orange);
Font f=new Font("Calibri",Font.BOLD,20);
g.setFont(f);
g.drawString("Hi I am Java developer",15, 40);
showStatus("Applet is Running");
}
} /* <applet code="MyApplet" height=600 width=400> </applet> */
Output:

Q 5. Attempt any Two. 16 Marks


a) Describe different logical and relational operators with example.
Ans: (Logical operators – 4 Marks, Relational operator – 4 Marks)
1. The Logical Operators:
The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:
Show Examples

Operator Description Example

Called Logical AND operator. If both the operands are non-zero,


&& (A && B) is false.
then the condition becomes true.
Called Logical OR Operator. If any of the two operands are
|| (A || B) is true.
non-zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the logical state of


! its operand. If a condition is true then Logical NOT operator will !(A && B) is true.
make false.

2. Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:
Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes then (A == B) is not
==
condition becomes true. true.

Checks if the values of two operands are equal or not, if values are
!= (A != B) is true.
not equal then condition becomes true.

Checks if the value of left operand is greater than the value of right
> (A > B) is not true.
operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the (A >= B) is not
>=
value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than or equal to the value
<= (A <= B) is true.
of right operand, if yes then condition becomes true.

c) State the use of Font class. Write syntax to create an object of Font class. Describe any 3
methods of Font class with their syntax and example of each.
[Font class 3-Marks, Syntax 2-Marks & Methods 3-Marks]
Font class: A font determines look of the text when it is painted. Font is used while painting
text on a graphics context & is a property of AWT component. The Font class defines these
variables:
Variable Meaning
String name Name of the font
float pointSize Size of the font in
points
int size Size of the font in point
int style Font style

Syntax to create an object of Font class: To select a new font, you must first construct a Font
object that describes that font. Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
fontName specifies the name of the desired font. The name can be specified using either the logical
or face name. All Java environments will support the following fonts: Dialog, DialogInput, Sans
Serif, Serif, Monospaced, and Symbol. Dialog is the font used by once system‟s dialog boxes.
Dialog is also the default if you don‟t explicitly set a font. You can also use any other fonts
supported by particular environment, but be careful—these other fonts may not be universally
available. The style of the font is specified by fontStyle. It may consist of one or more of these
three constants: Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR them
together. For example, Font.BOLD | Font.ITALIC specifies a bold, italics style. The size, in
points, of the font is specified by pointSize. To use a font that you have created, you must select it
using setFont( ), which is defined by Component. It has this general form: void setFont(Font
fontObj) Here, fontObj is the object that contains the desired font Methods of Font class
1. String getFamily(): Returns the family name of this Font.
2. int getStyle():Returns the style of this Font
3. int getSize() : Returns the size of this Font
4. boolean is bold(): Returns true if the font includes the bold style value. Else returns false
5. String toString(): Returns the string equivalent of the invoking font.
Example Using Methods of Font class: Program:
A program to make use of Font class methods. Which will display string ―Java Programming Is
Language‖ if font object style is BOLD else it will display string ―Java Programming Is Language‖
with another string saying ―String is not bold‖
import java.applet.*;
import java.awt.*;
/*<applet code="FontD" width=350 height=60> </applet> */
public class FontD extends Applet
{
Font f, f1; String s="";
String msg="";
public void init()
{
f=new Font("Dialog", Font.BOLD,30);
s="Java Programming";
setFont(f);
msg="Is Language";
int a=f.getSize();
String b=f.getFontName();
Int d=f.getStyle();
System.out.println("String Information: Size"+a);
System.out.println("Name:"+b);
System.out.println("Style:"+d);
}
public void paint(Graphics g)
{
if(f.isBold()==true)
g.drawString(s,50,50);
else g.drawString("String is not bold",400,400);
g.drawString(s,50,50);
g.drawString(msg,100,100);
}
}
Output:

d) Write a program to create two threads; one to print numbers in original order and other
to reverse order from 1 to 50. ( 4-marks for Logic, 4-marks for correct Syntax) (Any
other program with correct logic may also be considered)
Ans: // Program
class original extends Thread
{
public void run( )
{
try
{
for(int i=1; i<=50;i++)
{
System.out.println("\t First Thread="+i);
Thread.sleep(300);
}
}
catch(Exception e)
{}
}
}
class reverse extends Thread
{
public void run( )
{
try
{
for(int i=50; i>=1;i--)
{
System.out.println("\t Second Thread="+i);
Thread.sleep(300);
}
}
catch(Exception e) {}
}
}
class orgrev
{
public static void main(String args[])
{
new original().start();
new reverse().start();
System.out.println("Exit from Main");
}
}
6. Attempt any 4: 16 Marks
a) What is the default priority for all the threads? How to obtain and change this priority.
(Priority – 2 Marks, Change Priority-2 Marks)
Ans: Default priority of a thread is 5 (NORM_PRIORITY).

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defiend in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

To change the priority we have a method called setPriority().


setPriority( ):
This method is used to set or change priority of the thread.
Syntax:

public final void setPriority(int newPriority)


newPriority -- This is the priority to set this thread to.
Eg:
Thread.setPriority(9);
To obtain the thread priority we have getPriority( ) method.

This method is used to get or obtain priority of the thread.


Syntax:

public final int getPriority()


This method returns this thread's priority.
Eg:
int p=t.getPriority( );
The above example will return the thread priority.

b) Give differences between start ( ) and init ( ) methods of Applet class.


(Each Method – 2 Marks)
Ans: There are two methods called at the beginning of an applet's lifetime:
Applet.init( ) - Called to tell the applet that it has been loaded into the system. You should use this
method to initialize any resources used by the applet.
Applet.start( ) - Called to tell the applet that it should start running.
start() is always called after init()
The init() method is called exactly once in an applet's life, when the applet is first loaded. It's
normally used to read PARAM tags, start downloading any other images or media files you need,
and set up the user interface. Most applets have init() methods.
The start() method is called at least once in an applet's life, when the applet is started or restarted.
In some cases it may be called more than once. Many applets you write will not have explicit
start()methods and will merely inherit one from their superclass. A start() method is often used to
start any threads the applet will need while it runs.
c) Explain serialization in relation with stream class.
(4 M Explanation, example not expected)
Ans:
 Serialization in java is a mechanism of writing the state of an object into a byte stream.
 Java provides a mechanism, called object serialization where an object can be represented
as a sequence of bytes that includes the object's data as well as information about the
object's type and the types of data stored in the object.
 After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data can
be used to recreate the object in memory.
 Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain
the methods for serializing and deserializing an object.
 The ObjectOutputStream class contains many write methods for writing various data types
such as writeObject() method. This method serializes an Object and sends it to the output
stream. Similarly, the ObjectInputStream class contains method for deserializing an object
as readObject(). This method retrieves the next Object out of the stream and deserializes it.
 The return value is Object, so you will need to cast it to its appropriate data type.
 For a class to be serialized successfully, two conditions must be met:
The class must implement the java.io.Serializable interface. All of the fields in the class must
be serializable. If a field is not serializable, it must be marked transient.
d) Comment on following two statements:
import java.io.*;
import java.io.File;
(Each Point – 1 Mark)
Ans:
1. The above given statement are the type of importing s package in your program
2. The first way i.e. import java.io.*; is called relative import statement.
3. The second way i.e. import java.io.File.*; is called absolute import statement.
4. In first import statement we are calling all classes of the input/output package.
5. In second import statement we are calling only file related classes.
6. Both the import statements are important as per situation.
d) How to pass parameters to the applet? Illustrate with example.
(Explanation – 2 Marks, Example – 2 Marks)
Ans: Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the
opening and closing APPLET tags. Inside the applet, you read the values passed through the
PARAM tags with the getParameter( ) method of the java.applet.Applet class.
The program below demonstrates this with a generic string drawing applet. The applet parameter
"Message" is the string to be drawn.
import java.applet.*;
import java.awt.*;

public class DrawStringApplet extends Applet


{

private String defaultMessage = "Hello!";

public void paint(Graphics g)


{
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 25);
}
}
/*<APPLET code="DrawStringApplet" width="300" height="50">
<PARAM name="Message" value="Howdy, there!">*/

You might also like