Вы находитесь на странице: 1из 20

15CS45: Object Oriented Concepts

Fourth Semester B.E Degree Examination, Dec 2017 / Jan 2018


Detailed Solution

Q. Question and Answer Descriptions Marks


No.
MODULE – I
1a. List out the difference between procedure-oriented programming and object-oriented 05
programming. Marks

Solution:

Procedure oriented programming Object oriented programming


• The primary focus is on functions • The primary focus is on data.
• Employs top-down approach in • Employs bottom-up approach in
program design. program design.
• The drawback with this • It ties data more closely to the
programming pattern is that the function that operate on it, and
data is not secure. protects it from accidental
modification from outside
function.
• No easy way for data hiding and • Data hiding is possible in object
concept of inheritance. oriented programing, and
inheritance is allowed.
• Different parts of a program are • The functions of the objects are
interconnected via parameter linked via message passing.
passing.
• Example: C, Pascal, Fortran • C++, Java

1b. Explain function overloading with example. 05


Marks
Solution:
• C++ allows two or more functions to have the same name. For this, however, they
must have different signatures.
• Signature of a function means the number, type, and sequence of formal
arguments of the function.
• In order to distinguish amongst the functions with the same name, the compiler
expects their signatures to be different.
• Depending upon the type of parameters that are passed to the function call, the
compiler decides which of the available definitions will be invoked.
• For this, function prototypes should be provided to the compiler for matching the
function calls.
• Accordingly, the linker, during link time, links the function call with the correct
function definition.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
The compiler decides which function is to be called based upon the number, type, and
sequence of parameters that are passed to the function call.

1c. What is a constructor? List the different type of constructors and explain default 06
constructor with an example. Marks

Solution:

• The constructor gets called automatically for each object that has just got created.
• It appears as member function of each class, whether it is defined or not.
• It has the same name as that of the class.
• It may or may not take parameters.
• It does not return anything (not even void).
• The prototype of a constructor is
<Class name> (<parameter list>);
• The compiler embeds a call to the constructor for each object when it is created.
• The different types of constructors are:
o Zero-argument/ default constructor
o Parameterized constructor
o Explicit constructor
o Copy constructor

Default Constructor
• The constructor does not take any arguments and is called the default constructor.
• The constructor provided by default by the compiler also does not take any
arguments.
• Therefore, the terms ‘zero-argument constructor’ and ‘default constructor’ are
used interchangeably.
Example program

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
2a. Explain the concept of object-oriented programming 08
I) Encapsulation Marks
II) Polymorphism
III) Inheritance
IV) Data initialization

Solution:

Encapsulation - Encapsulation is the mechanism that binds together code and the data it
manipulates and keeps both safe from outside interference and misuse. One way to think
about encapsulation is as a protective wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the wrapper. Access to the code and data
inside the wrapper is tightly controlled through a well-defined interface.

Polymorphism - Polymorphism (from Greek, meaning “many forms”) is a feature that


allows one interface to be used for a general class of actions. More generally, the concept
of polymorphism is often expressed by the phrase “one interface, multiple methods.” This
means that it is possible to design a generic interface to a group of related activities. This
helps reduce complexity by allowing the same interface to be used to specify a general class
of action.

Inheritance - Inheritance is the process by which one object acquires the properties of
another object. This is important because it supports the concept of hierarchical
classification.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
Data Initialization - Initialization of a variable provides its initial value at the time of
construction. The initial value may be provided in the initializer section of a declarator or a
new expression. It also takes place during function calls: function parameters and the
function return values are also initialized.

2b. Explain function prototyping with example. 05


Marks
Solution:
• A prototype describes the function’s interface to the compiler.
• It tells the compiler the return type of the function as well as the number, type, and
sequence of its formal arguments.
• The general syntax of function prototype is as follows:
return_type function_name(argument_list);
Example:
int add(int, int);
• This prototype indicates that the add() function returns a value of integer type and
takes two parameters both of integer type. Since a function prototype is also a
statement, a semicolon must follow it.
• Providing names to the formal arguments in function prototypes is optional. Even if
such names are provided, they need not match those provided in the function
definition.

• Function prototyping guarantees protection from errors arising out of incorrect


function calls.
• Function prototyping produces automatic-type conversion wherever appropriate.

2c. How do namespace help in preventing pollution of the global namespace? 03


Marks
Solution:
• Namespaces enable the C++ programmer to prevent pollution of the global
namespace that leads to name clashes.
• The term ‘global namespace’ refers to the entire source code. It also includes all
the directly and indirectly included header files.
Suppose a class with the same name is defined in two header files.
/*Beginning of A1.h*/

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
class A
{
};
/*End of A1.h*/
/*Beginning of A2.h*/
class A //a class with an existing name
{
};
/*End of A2.h*/

Now, let us include both these header files in a program and see what happens if we
declare an object of the class
#include “A1.h”
#include “A2.h”
void main()
{
A obj; // Ambiguity error due to multiple definitions of A
}

Enclosing the two definitions of the class in separate namespaces overcomes this problem.

/*Beginning of A1.h*/
namespace A1 //beginning of a namespace A1
{
class A
{
};
} //end of a namespace A1
/*End of A1.h*/
/*Beginning of A2.h*/
namespace A2 //beginning of a namespace A2
{
class A
{
};
} //end of a namespace A2

Then in the main function, it can used as follows

#include “A1.h”
#include “A2.h”
void main()
{
using namespace A1;
A obj1; // using object from namespace A1 from header file A1.h
using namespace A1;
A obj2; // using object from namespace A2 from header file A2.h
// or can be used as
A2::A a2obj2; // creates object of namespace A2 from A2.h
}

MODULE – II
3a. Explain how java is robust and interactive 05
Marks
Solution:
Robust: Java frees you from having to worry about many of the most common causes of
programming errors. Because Java is a strictly typed language, it checks your code at
compile time. However, it also checks your code at run time.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
To better understand how Java is robust, consider two of the main reasons for program
failure:
1. memory management mistakes
2. Mishandled exceptional conditions (that is, run-time errors).
Memory management mistakes
Memory management can be a difficult, tedious task in traditional programming
environments. For example, in C/C++, the programmer must manually allocate and free all
dynamic memory. This sometimes leads to problems, because programmers will either
forget to free memory that has been previously allocated or, worse, try to free some memory
that another part of their code is still using. Java virtually eliminates these problems by
managing memory allocation and deallocation for you. (In fact, deallocation is completely
automatic, because Java provides garbage collection for unused objects.)

Mishandled exceptional conditions (that is, run-time errors).


Exceptional conditions in traditional environments often arise in situations such as division
by zero or “file not found,” and they must be managed with clumsy and hard-to-read
constructs. Java helps in this area by providing object-oriented exception handling. In a
well-written Java program, all run-time errors can—and should—be managed by your
program.

Interactive: Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time. This makes it
possible to dynamically link code in a safe and expedient manner. This is crucial to the
robustness of the Java environment, in which small fragments of byte code may be
dynamically updated on a running system.

3b. Write a Java program to sum only first 5 elements of the array using for each loop. 05
Solution: Marks
import java.lang.*
class SumFirstFive
{
public static void main( String args[])
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int counter = 1, sum = 0;
for(int i : arr)
{
sum += i;
counter++;
if( counter == 5)
break;
}
System.out.println(“Sum of first 5 numbers is “ + sum);
}
}

3c. Explain the operation of the following operators with example 06


Marks
i) %
ii) >>>
iii) &&

Solution:

i) Modulus Operator - %

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
The modulus operator, %, returns the remainder of a division operation. It can be
applied to floating-point types as well as integer types. The following example
program demonstrates the %:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25

ii) Logical/unsigned right shift >>>


Logical right shift operator is used to shift the individual bits of the binary representation
of a number of n number of bits specified and fill in zeros at the MSB.

// Demonstration of >>> operator


class LogicalRightShift {
public static void main(String args[]) {
int x = 10; // binary representation = 1010
System.out.println("x right shift 1 = " +(x >>> 1)); // _101 1 shifts 1
// bit to right
System.out.println("x right shift 2 = " + (x >>> 2)); // __10 10 shifts 2
// bits to the right
}
}
Output:
x right shift 1 = 5 // 0101
x right shift 2 = 2 // 0010

iii) Logical and &&


Logical AND ( &&) returns a Boolean true with both the expressions on either side
operator is true
// Demonstration of && operator
class LogicalAnd{
public static void main(String args[]) {
if( 1 == 1 && 5 < 10)
System.out.println(“ Both expressions are true”);
else
System.out.println(“ Both expressions are not true”);
}
}

4a. Write a java program to initialize and display different types of integers and floating 06
point variables. Marks
Solution:
class IntegersAndFloating{
public static void main(String args[]){
byte b =10;
short s = 300;
int i = 20000;
long l = 3426987;
float f = 1.3456;
double d = 3.145674;

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
System.out.println(“Byte data = “ + b);
System.out.println(“short data = “ + s);
System.out.println(“int data = “ + i);
System.out.println(“long data = “ + l);
System.out.println(“float data = “ + f);
System.out.println(“double data = “ + d);
}
}

4b. What is type casting? Illustrate with an example. What is meant by automatic type 06
promotion? Marks

Solution:

The process of converting one data type to another data type is known as type conversion.
If the two types are compatible, then Java will perform the conversion automatically. For
example, it is always possible to assign an int value to a long variable.
A cast is simply an explicit type conversion.
It has this general form:
(target-type) value

The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion
{
public static void main(String args[])
{
int i;
double d = 323.142;
System.out.println("Conversion of double to int.");
i= (int) d;
System.out.println("integer is " + i);
}
}
This program generates the following output:
Conversion of double to int
integer is 323

Automatic Type Promotion


When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the
int type is always large enough to hold all valid byte values, so no explicit cast statement
is required.
For widening conversions, the numeric types, including integer and floating-point types,
are compatible with each other. However, there are no automatic conversions from the
numeric types to char or boolean. Also, char and boolean are not compatible with each
other.

4c. How to declare two dimensional arrays in Java? Explain with simple example. 04
Marks
Solution:

The following declares a two- dimensional array variable called twoD.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented
as an array of arrays of int.
The following program numbers each element in the array from left to right, top to
bottom, and then displays these values:

// Demonstrate a two-dimensional array.


class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
MODULE – III
5a. Describe the various levels of access protections available for packages and their 08
implications. Marks

Solution:
Access modifiers define the scope of the class and its members (data and methods). For
example, private members are accessible within the same class members (methods). Java
provides many levels of security that provides the visibility of members (variables and
methods) within the classes, subclasses, and packages.

Packages are meant for encapsulating, it works as containers for classes and other
subpackages. Class acts as containers for data and methods. There are four categories,
provided by Java regarding the visibility of the class members between classes and
packages:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three main access modifiers private, public and protected provides a range of ways to
access required by these categories.
ACCESS PROTECTION IN PACKAGES

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
Simply remember, private cannot be seen outside of its class, public can be access from
anywhere, and protected can be accessible in subclass only in the hierarchy.

A class can have only two access modifier, one is default and another is public. If the class
has default access then it can only be accessed within the same package by any other code.
But if the class has public access then it can be access from any where by any other code.

5b. Give the basic form of an exception handling block. 04


Marks
Solution:
This is the general form of an exception-handling block:

try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}

5c. What is the importance of the clause finally? 04


Marks
Solution:
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method. Depending upon how the method is coded,
it is even possible for an exception to cause the method to return prematurely. This could
be a problem in some methods, finally keyword is designed to address this contingency.
That is, if a method opens a file upon entry and closes it upon exit, then you will not want
the code that closes the file to be bypassed by the exception-handling mechanism. Use of
finally block, the file can be closed before the block terminates.

finally creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block. The finally block will execute whether
or not an exception is thrown.

6a. Define inheritance. List the different types of inheritance. 05


Marks
Solution:
Inheritance refers to a feature of Java programming that lets you create classes that are
derived from other classes. A class that’s based on another class inherits the other class.
The class that is inherited is the parent class, the base class, or the superclass. The class
that does the inheriting is the child class, the derived class, or the subclass.

Different types of inheritances in Java are:


• Single inheritance
• Multilevel inheritance
• Hybrid inheritance
• Hierarchical inheritance

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
6b. Illustrate with example a super class variable can reference a subclass object. 06
Marks
Solution:
A reference variable of a superclass can be assigned a reference to any subclass derived
from that superclass. For example, consider the following:

class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}

Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box


objects. Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a
reference to the weightbox object.

6c. Compare and contrast method overloading and overriding. 05


Marks
Solution:
Method Overloading Method Overriding
Method overriding is used to provide
Method overloading is used to increase the the specific implementation of the
readability of the program. method that is already provided by its
super class.
Method overriding occurs in two
Method overloading is performed within
classes that have IS-A (inheritance)
class.
relationship.
In case of method overloading, parameter In case of method overriding,
must be different. parameter must be same.
Method overloading is the example of Method overriding is the example of
compile time polymorphism. run time polymorphism.
In java, method overloading can't be
performed by changing return type of the
Return type must be same or covariant
method only. Return type can be same or
in method overriding.
different in method overloading. But you
must have to change the parameter.

MODULE – IV

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
7a. What is Thread? Explain two ways of creation of thread. 05
Marks
Solution:
A thread is a lightweight sub-process, the smallest unit of processing.

The two ways of creating a thread can be accomplished as:


• By implementing the Runnable interface.
• By extending the Thread class.

a) The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable
abstracts a unit of executable code. You can construct a thread on any object that implements Runnable.

// Create a second thread.


class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

b) Java Thread Example by extending Thread class

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:
thread is running...

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
7b. What is synchronization? When do we use it? 05
Marks
Solution:
Synchronization in java is the capability to control the access of multiple threads to any
shared resource. Java Synchronization is better option where we want to allow only one
thread to access the shared resource.

The synchronization is mainly used / need for synchronization is:


(a) To prevent thread interference.
(b) To prevent consistency problem.

By using Java synchronized method, synchronization can be implemented. If you declare


any method as synchronized, it is known as synchronized method. Synchronized method is
used to lock an object for any shared resource. When a thread invokes a synchronized
method, it automatically acquires the lock for that object and releases it when the thread
completes its task.

7c. Explain keyEvents and mouseEvents class. 06


Marks
Solution:

keyEvents

public class KeyEvent extends InputEvent

An event which indicates that a keystroke occurred in a component.

This low-level event is generated by a component object (such as a text field) when a key
is pressed, released, or typed. The event is passed to every KeyListener or KeyAdapter
object which registered to receive such events using the component's addKeyListener
method. (KeyAdapter objects implement the KeyListener interface.) Each such listener
object gets this KeyEvent when the event occurs.

The getKeyChar method always returns a valid Unicode character or


CHAR_UNDEFINED. Character input is reported by KEY_TYPED events:
KEY_PRESSED and KEY_RELEASED events are not necessarily associated with
character input. Therefore, the result of the getKeyChar method is guaranteed to be
meaningful only for KEY_TYPED events.

For key pressed and key released events, the getKeyCode method returns the event's
keyCode. For key typed events, the getKeyCode method always returns
VK_UNDEFINED. The getExtendedKeyCode method may also be used with many
international keyboard layouts.

"Key pressed" and "key released" events are lower-level and depend on the platform and
keyboard layout. They are generated whenever a key is pressed or released, and are the only
way to find out about keys that don't generate character input (e.g., action keys, modifier
keys, etc.). The key being pressed or released is indicated by the getKeyCode and
getExtendedKeyCode methods, which return a virtual key code.

Pressing and releasing a key on the keyboard results in the generating the following key
events (in order):

KEY_PRESSED

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
KEY_TYPED (is only generated if a valid Unicode character could be generated.)
KEY_RELEASED

MouseEvents

The MouseEvents class extends Applet and implements both the MouseListener and
MouseMotionListener interfaces. These two interfaces contain methods that receive and
process the various types of mouse events. Notice that the applet is both the source and the
listener for these events. This works because Component, which supplies the
addMouseListener( ) and addMouseMotionListener( ) methods, is a superclass of Applet.
Being both the source and the listener for events is a common situation for applets.
Inside init( ), the applet registers itself as a listener for mouse events. This is done by using
addMouseListener( ) and addMouseMotionListener( ), which, as mentioned, are members
of Component. They are shown here:

void addMouseListener(MouseListener ml)


void addMouseMotionListener(MouseMotionListener mml)

Here, ml is a reference to the object receiving mouse events, and mml is a reference to the
object receiving mouse motion events.

8a. Explain Delegation Event Model used to handle events in Java. 08


Marks
Solution:
In the delegation event model, a class designated as an event source generates an event and
sends it to one or more listeners. The responsibility of handling the event process is handed
over to its listeners. The listeners classes wait in the vicinity, to spring into action only when
it is poked by the event that it is interested in. However, the listeners must register or agree
with the event source class to receive any notification. This means that a particular event is
processed only by a specific listener.
A component can be mapped to numerous types of events; for example, a click event of a
button behaves differently than a click event of a list box. It is quite easy to be lost in the
event scheme API. But, Java uses a very intuitive naming convention. Related event classes,
interfaces, and methods and their types can be very easily known by their naming scheme.
For example, the listener naming scheme for an event of, say, classMyEvent may be
MyEventListener and the consuming event method may be addMyEventListener,
removeMyEventListener, and the like.

Events, Sources, and Listeners:


The delegation event model can be defined by three components: event, event source, and
event listeners.

Events: The event object defines the change in state in the event source class. For example,
interacting with the graphical interfaces, such as clicking a button or entering text via
keyboard in a text box, item selection in a list, all represent some sort of change in the state.
The event object is used to carry the required information about the state change. However,
all events are not cause by user interaction. There are events such as timer event,
hardware/software events, and so forth, that do not depend upon user interaction. They
occur automatically. We can define the procedure to handle them once they occur.

Event sources: Event sources are objects that cause the events to occur due to some change
in the property of the component. Because there can be various types a component can
trigger, each must be registered to a listener to provide a suitable response.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
Event listeners: Event listeners are objects that are notified as soon as a specific event
occurs. Event listeners must define the methods to process the notification they are
interested to receive.

8b. Explain the role of synchronization with producer and consumer problem. 08
Marks
Solution:
Java includes an elegant interprocess communication mechanism via
the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final
methods in Object, so all classes have them. All three methods can be called only from
within a synchronized context. The rules for using these methods are actually quite simple:
• wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.
These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )

Consider the following sample program that implements a simple form of the producer/
consumer problem. It consists of four classes: Q, the queue that you’re trying to
synchronize; Producer, the threaded object that is producing queue entries; Consumer, the
threaded object that is consuming queue entries; and PC, the tiny class that creates the single
Q, Producer, and Consumer. The methods wait( ) and notify( ) to signal in both directions.
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies
you that some data is ready. When this happens, execution inside get( ) resumes. After the
data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more
data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed
the item from the queue. When execution resumes, the next item of data is put in the queue,
and notify( ) is called. This tells the Consumer that it should now remove it. Implementation
of a producer and consumer program in Java is given below:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

MODULE – V
9a. What is an applet? Explain five main methods of applet. 08
Marks
Solution:
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.

// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}
/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}
Applet Initialization and Termination
It is important to understand the order in which the various methods shown in the skeleton
are called. When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

Let’s describe these methods in detail:

init( )
The init( ) method is the first method to be called. This is where you should initialize
variables. This method is called only once during the run time of your applet.

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. So, if a user leaves a web
page and comes back, the applet resumes execution at start( ).

paint( )
The paint( ) method is called each time your applet’s output must be redrawn. This situation
can occur for several reasons. For example, the window in which the applet is running may
be overwritten by another window and then uncovered. Or the applet window may be
minimized and then restored. paint( ) is also called when the applet begins execution.
Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The
paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.

stop( )
The stop( ) method is called when a web browser leaves the HTML document containing
the applet—when it goes to another page, for example. When stop( ) is called, the applet is
probably running. You should use stop( ) to suspend threads that don’t need to run when
the applet is not visible. You can restart them when start( ) is called if the user returns to
the page.

destroy( )

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory. At this point, you should free up any resources the
applet may be using. The stop( ) method is always called before destroy( ).

9b. Explain with syntax the following: 08


i) JLabel Marks
ii) JTextField
iii) JButton
iv) JCheckBox

Solution:
(i) JLabel: JLabel is the simplest and easiest-to-use component because it does not accept
user input. It simply displays information, which can consist of text, an icon, or a
combination of the two. The label created by the program contains only text, which is
passed to its constructor. The next line of code creates a Swing JLabel component:

JLabel jlab = new JLabel(" Swing means powerful GUIs.");

(ii) JTextfield: JTextField is the simplest Swing text component. It is also probably its most
widely used text component. JTextField allows you to edit one line of text. It is derived
from JTextComponent, which provides the basic functionality common to Swing text
components. JTextField uses the Document interface for its model.

Three of JTextField’s constructors are shown here:


JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

Here, str is the string to be initially presented, and cols is the number of columns in the text
field. If no string is specified, the text field is initially empty. If the number of columns is
not specified, the text field is sized to fit the specified string.

(iii) JButton: The JButton class provides the functionality of a push button. JButton allows
an icon, a string, or both to be associated with the push button. Three of its constructors are
shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.

(iv) JCheckBox: The JCheckBox class provides the functionality of a check box. Its
immediate superclass is JToggleButton, which provides support for two-state buttons.
JCheckBox defines several constructors. The one used here is JCheckBox(String str). It
creates a check box that has the text specified by str as a label. Other constructors let you
specify the initial selection state of the button and specify an icon.
When the user selects or deselects a check box, an ItemEvent is generated. You can obtain
a reference to the JCheckBox that generated the event by calling getItem( ) on the ItemEvent
passed to the itemStateChanged( ) method defined by ItemListener. The easiest way to
determine the selected state of a check box is to call isSelected( ) on the JCheckBox
instance.

10a. Create swing applet that has two buttons named beta and gamma. When either of the 08
buttons pressed, it should display “beta was pressed” and “gamma was pressed” Marks
respectively.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
Solution:
import java.awt.event.*;
import javax.swing.*;
public class Beta_Gamma{
Beta_Gamma(){
JFrame f=new JFrame("Beta_Gamma Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b1=new JButton("Beta");
b1.setBounds(50,100,95,30);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Beta was pressed"); } });
JButton b2=new JButton("Gamma");
b2.setBounds(50,150,95,30);
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Gamma was pressed");} });
f.add(tf);
f.add(b1);
f.add(b2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Beta_Gamma();
}
}

10b. Explain getDocumentbase and getCodebase in applet class. 08


Solution: Marks
To create applets that will need to explicitly load media and text. Java will allow the applet
to load data from the directory holding the HTML file that started the applet (the document
base) and the directory from which the applet’s class file was loaded (the code base). These
directories are returned as URL objects by getDocumentBase( ) and getCodeBase( ). They
can be concatenated with a string that names the file you want to load. To actually load
another file, you will use the showDocument( ) method defined by the AppletContext
interface.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
The following applet illustrates these methods:
// Display code and document bases.
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=300 height=50>
</applet>
*/
public class Bases extends Applet{
// Display code and document bases.
public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}
Sample output from this program is shown here:

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98

Вам также может понравиться