15CS45 OOC Solutions - Jun - July 2018

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

15CS45: Object Oriented Concepts

Fourth Semester B.E Degree Examination, Jun/July 2018


Detailed Solution

Q. Question and Answer Descriptions Marks


No.
MODULE – I
1a. State the important features of object oriented programming paradigm 08
Marks
• OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system.
• It ties data more closely to the function that operate on it and protects it from
accidental modification from outside function.
• OOP allows decomposition of a problem into a number of entities called objects
and then builds data and function around these objects.
• The data of an object can be accessed only by the function associated with that
object. However, function of one object can access the function of other objects.
• The organization of data and function in object-oriented programs is shown in
fig.

Some of the features of object oriented programming are:


• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data
structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.

1b. Write a C++ program to get employees details (empno, ename, bsalary (initialized to 08
1000 by constructor) and allowance) of the employee class through keyboard using Marks
the method Getdata()and display them using the method Dispdata() in the console in
the format empno, ename, bsalary, allowance.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
#include<stdio.h>

Using namespace std;

Class Employee{
private:
int empno;
char ename[50];
float bsalary, allowance;
Employee(){
bsalary= 1000;
}
public:
void Getdata(){
cout<<”Enter Employee Number: “;
cin>>empno;
cout<<”Enter Employee Name: “;
cin>>ename;
cout<<”Enter Base Salary: “;
cin>>bsalary;
cout<<”Enter Employee Allowance: “;
cin>>allowance;
}
void Dispdata(){
cout<<”Employee Number: “<<empno<<endl;
cout<<”Emloyee Name: “<<ename<<endl;
cout<<”Employee Base Salary: “<<bsalary<<endl;
cout<<”Employee Allowance: “<<allowance<<endl;
}
}

void main(){
Employee e;
e.Getdata();
e.Dispdata();
}

2a. Describe function prototype with an example. 04


Marks
• 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.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
• Function prototyping guarantees protection from errors arising out of incorrect
function calls.
• Function prototyping produces automatic-type conversion wherever appropriate.

2b. Explain namespace, with an example. 04


Solution: Marks
• 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.
Enclosing the two definitions of the class in separate namespaces overcomes the problem
of class with the same names is defined in two header files.
/*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
}

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
2c. Define function overloading and write a C++ program for finding areas of circle 08
(PI * R * R), rectangle (l * b) and square (x * x) by getting r, l, b and x through Marks
keyboard and printing the areas on console using the method Area() applying the
concept of function overloading.

• 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.

#include<stdio.h>

using namespace std;

void Area(int l, int b){


cout<<”Area of Rectangle is: “<<l*b;
}

void Area(float r){


cout<<”Area of Circle is: “<<3.14*r*r;
}

void Area(int x){


cout<<”Area of square is: “<<x * x;
}

void main(){
int x, l, b;
float r;
cout<<”Enter length and breadth of the rectangle: ”;
cin>>l>>b;
cout<<”Enter radius of circle: “;
cin>>r;
cout<<”Enter length of square: “:
cin>>x;
Area(l, b);
Area(r);
Area(x);
}

MODULE – II
3a. State the features used in C++ which are eliminated in Java. Why? 04
Marks
Solution:
Java does not adopt those features of C++ that make the language significantly more
complicated.
• C++ supports multiple inheritance of method implementations from more than one
superclass at a time. While this seems like a useful feature, it introduces many
complexities to the language. The Java language designers chose to avoid the
added complexity by using interfaces instead. Thus, a class in Java can inherit
method implementations only from a single superclass, but it can inherit method
declarations from any number of interfaces.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
• C++ supports templates that allow you, for example, to implement a Stack class
and then instantiate it as Stack or Stack to produce two separate types: a stack of
integers and a stack of floating-point values. Java does not allow this, but efforts
are underway to add this feature to the language in a robust and standardized way.
• C++ allows you to define operators that perform arbitrary operations on instances
of your classes. In effect, it allows you to extend the syntax of the language. This
is a nifty feature, called operator overloading, that makes for elegant examples. In
practice, however, it tends to make code quite difficult to understand. After much
debate, the Java language designers decided to omit such operator overloading
from the language. Note, though, that the use of the + operator for string
concatenation in Java is at least reminiscent of operator overloading.
• C++ allows you to define conversion functions for a class that automatically
invoke an appropriate constructor method when a value is assigned to a variable
of that class. This is simply a syntactic shortcut (similar to overriding the
assignment operator) and is not included in Java.
• In C++, objects are manipulated by value by default; you must use & to specify a
variable or function argument automatically manipulated by reference. In Java, all
objects are manipulated by reference, so there is no need for this & syntax.

3b. Discuss briefly concept of byte code in java. 04


Marks
Solution:

Bytecode is a highly optimized set of instructions designed to be executed by the Java


run-time system, which is called the Java Virtual Machine (JVM). Translating a Java
program into bytecode makes it much easier to run a program in a wide variety of
environments because only the JVM needs to be implemented for each platform. Once the
run-time package exists for a given system, any Java program can run on it. Remember,
although the details of the JVM will differ from platform to platform, all understand the
same Java bytecode. Thus, the execution of bytecode by the JVM is the easiest way to
create truly portable programs.

3c. Explain the structure of java program and its keywords with an example. 08
Marks
Solution:
/* This is a simple Java program. Call this file "Example.java". */
class Example
{

// Your program begins with a call to main().


public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}

public static void main(String args[]) // Your program begins with a call to main().

This line begins the main( ) method. As the comment preceding it suggests, this is the line
at which the program will begin executing. All Java applications begin execution by
calling main( ). The public keyword is an access specifier, that member may be accessed
by code outside the class in which it is declared.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
The keyword static allows main( ) to be called without having to instantiate a particular
instance of the class. This is necessary since main( ) is called by the Java Virtual Machine
before any objects are made. The keyword void simply tells the compiler that main( ) does
not return a value.

In main( ), String args[ ] declares a parameter named args, which is an array of instances
of the class String. (Arrays are collections of similar objects.) Objects of type String store
character strings. In this case, args receives any command-line arguments present when
the program is executed.
System.out.println("This is a simple Java program.");

This line outputs the string “This is a simple Java program.” followed by a new line on
the screen. Output is actually accomplished by the built-in println( ) method. System is a
predefined class that provides access to the system, and out is the output stream that is
connected to the console.

Java Keywords
There are 50 keywords currently defined in the Java language. These keywords, combined
with the syntax of the operators and separators, form the foundation of the Java language.
These keywords cannot be used as names for a variable, class, or method.

Example: continue, break, byte, int, switch, for, if

4a. How arrays are defined in java? Explain with an example. 04


Solution: Marks
An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index. Arrays offer a convenient means of grouping related
information.

type. The general form of a one-dimensional array declaration is


type var-name[ ];

Here, type declares the base type of the array. The base type determines the data type of
each element that comprises the array.

int month_days[];

Although this declaration establishes the fact that month_days is an array variable, no
array actually exists. In fact, the value of month_days is set to null, which represents an
array with no value.

The general form of new as it applies to one-dimensional arrays appears as follows:


array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of elements
in the array, and array-var is the array variable that is linked to the array. That is, to use
new to allocate an array, you must specify the type and number of elements to allocate.

month_days = new int[12];

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
4b. Elucidate how java is a platform independent language, with neat sketches. 06
Marks
Solution:
Java is a platform independent programming language, because when you install jdk
software on your system then automatically JVM are installed on your system. For every
operating system separate JVM is available which is capable to read the .class file or byte
code. When we compile your Java code then .class file is generated by javac compiler
these codes are readable by JVM and every operating system have its own JVM so JVM
is platform dependent but due to JVM java language is become platform independent.

4c. Write a Java program to print factorial of a number ‘n’ using for loop 06
Marks
Solution:
import java.lang.*;
import java.util.*;
class Factorial{
public static void main(String []args){
int fact=1, n, i = 1;
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number to find factorial”);
n = sc.nextInt();
for(i = 1; i<=n ; i++)
fact *= i;
System.out.println(“Factorial of “+n+” is “+fact);
}
}

MODULE – III
5a. Explain package and its types and import command in Iava with examples. 08
Marks
Solution:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.

There are three ways to access the package from outside the package.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
a) import package.*;
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages. The import keyword is used to make the classes and
interface of another package accessible to the current package. Example for import
package:

//save as A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save as B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello

b) import package.classname;
If you import package.classname then only declared class of this package will be
accessible. Example of package by import package.classname:
//save as A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save as B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output: Hello

c) fully qualified name:


If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface. It is generally used when two packages have same
class name e.g. java.util and java.sql packages contain Date class. Example of package by
import fully qualified name:
//save as A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save as B.java

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

Output: Hello

5b. Write a Java program to define an interface called Area which contains method 08
called Compute() and calculate the areas of rectangle ( l * b) and triangle (1/2 * b * Marks
h) using classes Rectangle and Triangle.

Solution:
interface Area{
double Compute(double x,double y);
}

class Rectangle implements Area{


public double Compute(double l,double b){
return(l*b);
}
}

class Triangle implements Area{


public double calc(double b,double h){
return(1/2*b*h);
}
}

class IntfDemoProg {
public static void main(String arg[]) {
Rectangle r = new Rectangle();
Triangle t = new Triangle();
area a;

a = r;
System.out.println("\nArea of Rectangle is : " +a.Compute(10,20));

a = t;
System.out.println("\nArea of Triangle is : " +a.Compute(5,7));
}
}
Output:
Area of Rectangle is : 200.0

Area of Triangle is : 17.5

6a. Define the role of Exception handling in software development. 02


Marks
Solution:
• Provision to Complete Program Execution without abrupt stopping of program
• Easy Identification of Program Code and Error-Handling Code
• Propagation of Errors
• Meaningful Error Reporting
• Identifying Error Types

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
6b. Write a Java program for illustrating the exception handling when a number is 06
divided by zero and an array has a negative index value. Marks

Solution:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[-1] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Output 1:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

Output 2:
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:-1
After try/catch blocks.

6c. Elucidate the concept of inheritance and its classification in Java with sketches. 08
Marks
Solution:
Inheritance is a mechanism in which one class acquires the property of another class. With
inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance
facilitates Reusability and is an important concept of OOPs.

Classification / Types of inheritance in Java:


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical. In java programming, multiple and hybrid inheritance is not supported.

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

// TestInheritance.java
class Animal{
void eat() { System.out.println("eating..."); }
}
class Dog extends Animal{
void bark(){ System.out.println("barking..."); }
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}

Output:

barking...
eating...

Multilevel Inheritance Example


// TestInheritance2.java
class Animal{
void eat() { System.out.println("eating..."); }
}
class Dog extends Animal{
void bark() { System.out.println("barking..."); }
}
class BabyDog extends Dog{
void weep() { System.out.println("weeping..."); }
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}

Output:

weeping...
barking...
eating...
MODULE – IV
7a. Define the concept of multithreading in Java and explain the different phases in the 08
life cycle of a thread, with a neat sketch. Marks

Solution:
A multithreaded program contains two or more parts that can run concurrently. Each part
of such a program is called a thread, and each thread defines a separate path of execution.
Thus, multithreading is a specialized form of multitasking.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
The benefit of Java’s multithreading is that the main loop/polling mechanism is
eliminated. One thread can pause without stopping other parts of your program. For
example, the idle time created when a thread reads data from a network or waits for user
input can be utilized elsewhere. Multithreading allows animation loops to sleep for a
second between each frame without causing the whole system to pause. When a thread
blocks in a Java program, only the single thread that is blocked pauses. All other threads
continue to run.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread
life cycle in java new, runnable, non-runnable and terminated. There is no running state.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable: The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently
not eligible to run.
5) Terminated: A thread is in terminated or dead state when its run() method exits.

A thread can be running. It can be ready to run as soon as it gets CPU time. A running
thread can be suspended, which temporarily suspends its activity. A suspended thread can
then be resumed, allowing it to pick up where it left off.

A thread can be blocked when waiting for a resource. At any time, a thread can be
terminated, which halts its execution immediately. Once terminated, a thread cannot be
resumed.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
7b. Discuss briefly Synchronization in Java 2. 02
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.

7c. Write an example Program for implementing static synchronization in Java. 06


Marks
Solution:
By applying synchronized keyword on the static method to perform static
synchronization.
class Table{

synchronized static void printTable(int n){


for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}

class MyThread1 extends Thread{


public void run(){
Table.printTable(1);
}
}

class MyThread2 extends Thread{


public void run(){
Table.printTable(10);
}
}

class MyThread3 extends Thread{


public void run(){
Table.printTable(100);
}
}

class MyThread4 extends Thread{


public void run(){
Table.printTable(1000);
}
}

public class TestSynch{


public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
t2.start();
t3.start();
t4.start();
}
}
Output:
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

8a. Elucidate the two ways of making a class threadable, with examples. 06
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() {

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
// 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...

8b. Describe the delegation event model and explain what happens internally at a button 04
click. 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

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
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.

MODULE – V
9a. Briefly explain Applets. 03
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.
There are two types of applets:
The first type is basic applets that use the Abstract Window Toolkit (AWT) to provide the
graphic user interface (or use no GUI at all). This style of applet has been available since
Java was first created.
The second type of applets are those based on the Swing class JApplet. Swing applets use
the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user
interface than does the AWT. Thus, Swing-based applets are now the most popular.

9b. Elucidate Lucidly the skeleton of an Applet. 05


Marks
Solution:

// 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
}
// 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

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
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( )
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( ).

9c. Write a Java program to play an audio file using Applet. 08


Marks
Solution:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class PlaySoundApplet extends Applet implements ActionListener {


Button play,stop;
AudioClip audioClip;

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
public void init() {
play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "Sound.wav");
}
public void actionPerformed(ActionEvent ae) {
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop ") {
audioClip.play();
} else if(source.getLabel() == " Stop "){
audioClip.stop();
}
}
}

10a. Write the advantages of swing over AWT. 04


Marks
Solution: Any four of the following:
• Swing provides both additional components and added functionality to AWT-
replacement components
• Swing components can change their appearance based on the current "look and feel"
library that's being used. You can use the same look and feel as the platform you're
on, or use a different look and feel.
• Swing components follow the Model-View-Controller paradigm (MVC), and thus
can provide a much more flexible UI.
• Swing provides "extras" for components, such as:
✓ Icons on many components
✓ Decorative borders for components
✓ Tooltips for components
• Swing components are lightweight (less resource intensive than AWT)
• Swing provides built-in double buffering.
• Swing provides paint debugging support for when you build your own components.

10b. Write a brief note on Containers in swing. 04


Marks
Solution:
A container holds a group of components. Thus, a container is a special type of component
that is designed to hold other components. Furthermore, in order for a component to be
displayed, it must be held within a container. Thus, all Swing GUIs will have at least one
container. Because containers are components, a container can also hold other containers.
This enables Swing to define what is called a containment hierarchy, at the top of which
must be a top-level container.

Swing defines two types of containers:


The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. These
containers do not inherit JComponent. They do, however, inherit the AWT classes
Component and Container.
Unlike Swing’s other components, which are lightweight, the top-level containers are
heavyweight. This makes the top-level containers a special case in the Swing component
library.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
10c. Write a swing program for displaying anyone of the options: C, C++, Java, Php 08
through the selection of Combobox by clicking show button. Marks

Solution:
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:

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

You might also like