0% found this document useful (0 votes)
197 views24 pages

15CS45 OOC Solutions - Dec 2018 - Jan 2019

This document contains solutions to questions on object oriented concepts and Java programming. It discusses the differences between procedure oriented and object oriented programming, features of OOP, function overloading examples, defining a student class with read and print functions, friend functions, constructor types with a parameterized constructor example, and Java buzzwords like simple, object oriented, robust, and multithreaded. The solutions include code snippets in C++ and descriptions of concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views24 pages

15CS45 OOC Solutions - Dec 2018 - Jan 2019

This document contains solutions to questions on object oriented concepts and Java programming. It discusses the differences between procedure oriented and object oriented programming, features of OOP, function overloading examples, defining a student class with read and print functions, friend functions, constructor types with a parameterized constructor example, and Java buzzwords like simple, object oriented, robust, and multithreaded. The solutions include code snippets in C++ and descriptions of concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

15CS45: Object Oriented Concepts

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


Detailed Solution

Q. Question and Answer Descriptions Marks


No.
MODULE – I
1a. Write the difference between procedure-oriented programming and object-oriented 04
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 data function that operate on it, and
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. List and explain any four features of object oriented program. 05
Marks
Solution:

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

1c. What is function overloading? Write a C++ program to define three overloaded 07
functions to find the sum of two integers, sum of two floating point numbers and sum Marks
of three integers.

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.

#include<stdio.h>
using namespace std;

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
void add(int, int, int);
void add(int, int);
void add(float, float);

void main()
{
add(10, 20);
add(10, 20, 30);
add(2.4, 1.3);
}

void add(int a, int b)


{
cout<<”sum = “<<a+b;
}

void add(int a, int b, int c)


{
cout<<”sum – “<<a+b+c;
}
void add(float a, float b)
{
cout<<”sum = ”<<a+b;
}

2a. Define a student class with the following measures 05


Data members: Roll No., Name, averagemarks Marks
Member functions: to read the data, to print the data,
Write a C++ program to read the data of 10 students and print the 10 students’
information.

Solution:
#include <stdio.h>
using namespace std;

class student{
private:
int rollno;
char name[30];
float avgmarks;
public:
void read(){
cout<<”Enter roll no: “;
cin>> rollno;
cout<<”Enter Name: ”;
cin>>name;
cout<<”Enter average marks: “;
cin>> avgmarks;
}
void print(){
cout<<”Roll No: “<<rollno<<”\nName: “<<name<<”\nAverage Marks:
“<<avgmarks<<endl;
}
}
void main()
{
Student s[10];
for(int i=0;i<10;i++)
{
cout<<”Enter details of student “<<i+1;
s[i].read();
}

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
for(int i=0;i<10;i++)
{
cout<<”Details of student ”<<i+1<<”is”<<endl;
s[i].print();
}
}

2b. Define a friend function. Illustrate with an example. 05


Marks
Solution:

If a function is defined as a friend function then, the private and protected data of a class
can be accessed using the function.

The complier knows a given function is a friend function by the use of the keyword friend.

For accessing the data, the declaration of a friend function should be made inside the body
of the class (can be anywhere inside class either in private or public section) starting with
keyword friend.

Example :
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
// friend function definition
int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}
Output:
Distance: 5
Here, friend function addFive() is declared inside Distance class. So, the private data meter
can be accessed from this function.

2c. What is constructor? Mention its types. Explain parameterized constructor with an 06
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.

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

Parameterized Constructors
• Constructors take arguments and can, therefore, be overloaded.
• Suppose, for the class Distance, the library programmer decides that while creating
an object, the application programmer should be able to pass some initial values for
the data members contained in the object.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
MODULE – II
3a. List and explain Java buzzwords. 08
Marks
Solution:

Simple
If you already understand the basic concepts of object-oriented programming, learning Java
will be even easier. Because Java inherits the C/C++ syntax and many of the object-oriented
features of C++.

Object-Oriented
The object model in Java is simple and easy to extend, while primitive types, such as integers,
are kept as high-performance non objects. Java supports all object-oriented features like
abstraction, encapsulations, inheritance, polymorphism.

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

Multithreaded
Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.

Architecture-Neutral
A central issue for the Java designers was portability. Their goal was “write once; run
anywhere, anytime, forever.” To a great extent, this goal was accomplished.

Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols. Java also supports Remote Method Invocation (RMI). This feature enables a
program to invoke methods across a network.

Interpreted and High Performance


Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java byte code. This code can be executed on any system that
implements the Java Virtual Machine. Most previous attempts at cross-platform solutions
have done so at the expense of performance. As explained earlier, the Java byte code was
carefully designed so that it would be easy to translate directly into native machine code for
very high performance by using a just-in-time compiler. Java run-time systems that provide
this feature lose none of the benefits of the platform-independent code.

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

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
3b. class Example{ 04
public static void main(String args[]){ Marks
int a;
for(a=0;a<3;a++)
{
Int b = -1;
System.out.println(“ “+b);
b = 50;
System.out.println(“ “+b);
}
}
}
What is the output of the above code? If you insert another ‘int b’ outside the for loop,
what is the output?

Solution:

Output:
-1
50
-1
50
-1
50

If we add int b before for loop, we will get a compile time error as duplication declaration
of local variable b, as b is again declared inside the for loop

3c. With an example, explain in working of >> and >>> (unsigned right shift). 04
Marks
Solution:

Right Shift operator


The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num.
The following code fragment shifts the value 32 to the right by two positions, resulting in a
being set to 8:
int a = 32;
a = a >> 2; // a now contains 8

When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with
the previous contents of the top bit. This is called sign extension and serves to preserve the
sign of negative numbers when you shift them right.
For example, –8 >> 1 is –4, which, in binary, is

11111000 –8
>>1
11111100 –4

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
It is interesting to note that if you shift –1 right, the result always remains –1, since sign
extension keeps bringing in more ones in the high-order bits.

The Unsigned Right Shift


As you have just seen, the >> operator automatically fills the high-order bit with its previous
contents each time a shift occurs. This preserves the sign of the value. However, sometimes
this is undesirable. In these cases, you will generally want to shift a zero into the high-order
bit no matter what its initial value was. This is known as an unsigned shift. To accomplish
this, you will use Java’s unsigned, shift-right operator, >>>, which always shifts zeros into
the high-order bit.

int a = -1;
a = a >>> 24;

Here is the same operation in binary form to further illustrate what is happening:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an int

4a. Define bytecode. How does it help java program(s) achieve portability? 05
Marks
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.

4b. Write a java program to sum only the first five elements of the array {1, 2, 3, 4, 5, 6, 7, 06
8, 9, 10} using “for each” version of the for loop. 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);
}
}

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
4c. What is type casting? Explain with an example. 05
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

MODULE – III
5a. Define inheritance. Explain multilevel, hierarchy with an example program. 05
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.

The multilevel and hierarchical inheritance can be explained as follows:


1. Multilevel Inheritance:
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the
derived class becomes the base class for the new class.

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.


// Java program to illustrate the
// concept of Multilevel inheritance

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void display()
{
System.out.println("Display in class one");
}
}

class two extends one


{
public void disp_two()
{
System.out.println("Display in class two");
}
}

class three extends two


{
public void display()
{
System.out.println("Display in class three");
}
}

// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_display();
g.print_disp_two();
g.print_display();
}
}
Output:
Display in class one
Display in class two
Display in class three

2. Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.

As per above example, Class B, C, and D inherit the same class A.


Example Program:

// Java program to illustrate the concept of Hierarchical inheritance


import java.util.*;

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
import java.lang.*;
import java.io.*;

class one {
public void print_one() {
System.out.println("Printing in one");
}
}

class two extends one


{
public void print_two()
{
System.out.println("Printing in two");
}
}

class three extends one


{
/*............*/
}

// Derived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_one();
two t = new two();
t.print_two();
g.print_one();
}
}
Output:
Printing in one
Printing in two
Printing in one

5b. Describe the various levels of access protections available for packages and their 07
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.

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

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.

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

Example program for Method overloading:

class Adder{
static int add(int a,int b){ return a+b; }
static int add(int a,int b,int c){ return a+b+c; }
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

Output:
22
33

Example program for Method overriding:

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike is running safely

6a. Define exception. Explain exception handling mechanism with an example. 08


Marks
Solution:

A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose
to handle the exception itself or pass it on. Either way, at some point, the exception is caught
and processed. Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code. Exceptions thrown by Java relate to fundamental errors
that violate the rules of the Java language or the constraints of the Java execution
environment. Manually generated exceptions are typically used to report some error condition
to the caller of a method.

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
}
Here, ExceptionType is the type of exception that has occurred.

Example:

class Excep {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.

6b. Discuss the following terms with example: i) super ii) final 08
Marks
Solution:
i) super keyword: Whenever a subclass needs to refer to its immediate superclass, it can do
so by use of the keyword super. super has two general forms. The first calls the superclass’
constructor. The second is used to access a member of the superclass that has been hidden
by a member of a subclass.

The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of Java super Keyword

super can be used to refer immediate parent class instance variable.


super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.

a) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
b) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

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

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local.

To call the parent class method, we need to use super keyword.

c) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}
}

Output:

animal is created
dog is created

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
ii) final keyword: The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:

• variable
• method
• class

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only.

a) Java final variable: If you make any variable as final, you cannot change the value of
final variable (It will be constant). Example of final variable:

//There is a final variable speedlimit, we are going to change the value of this variable, but
//it can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:
Compile Time Error

b) Java final method: If you make any method as final, you cannot override it. Example of
final method:

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:
Compile Time Error

c) Java final class: If you make any class as final, you cannot extend it. Example of final
class:

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}

Output:
Compile Time Error

MODULE – IV
7a. What is thread? Explain two ways of creating a thread in JAVA with an example. 08
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.");
}
}

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

7b. What is the need of synchronization? Explain with an example how synchronization is 08
implemented in Java. 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.

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

8a. Explain the delegation event model used to handle events in JAVA. What are events, 06
event listener and event sources? 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,

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

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. With the syntax, explain the use of isAlive() and join() methods. 04
Marks
Solution:

Sometimes one thread needs to know when other thread is terminating. In java, isAlive() and
join() are two different methods that are used to check whether a thread has finished its
execution or not.

The isAlive() method returns true if the thread upon which it is called is still running
otherwise it returns false.

final boolean isAlive()

But, join() method is used more commonly than isAlive(). This method waits until the thread
on which it is called terminates.

final void join() throws InterruptedException

Using join() method, we tell our thread to wait until the specified thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.

final void join(long milliseconds) throws InterruptedException

Example of isAlive method

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());

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

Output:
r1
true
true
r1
r2
r2

Example of thread with join() method

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}catch(InterruptedException ie){ }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();

try{
t1.join(); //Waiting for t1 to finish
}catch(InterruptedException ie){}
t2.start();
}
}

Output:
r1
r2
r1
r2

In this above program join() method on thread t1 ensures that t1 finishes it process before
thread t2 starts.

MODULE – V
9a. What is an Applet? Explain the skeleton of an Applet. Enlist applet tags. 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() {

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

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

The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are optional:
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>

9b. Write a program using an Applet which will Print “key pressed” on the status window 08
when you press the key, “key released” on the status window when you release the key Marks
and when you type characters it should print “Hello” at coordinates (50, 50) on Applet.

Solution:
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class StatusWindow extends Applet
implements KeyListener {
String msg = "Hello";
int X = 50, Y = 50; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Output:

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
10a. Describe the two key features of swings. 04
Marks
Solution:
Two Key Swing Features are:

a) Swing Components Are Lightweight


With very few exceptions, Swing components are lightweight. This means that they are
written entirely in Java and do not map directly to platform-specific peers. Because
lightweight components are rendered using graphics primitives, they can be transparent,
which enables nonrectangular shapes. Thus, lightweight components are more efficient and
more flexible.

b) Swing Supports a Pluggable Look and Feel


Swing supports a pluggable look and feel (PLAF). Because each Swing component is
rendered by Java code rather than by native peers, the look and feel of a component is under
the control of Swing. This fact means that it is possible to separate the look and feel of a
component from the logic of the component, and this is what Swing does.

10b. Explain the following with an example for each and syntax: 12
(i) JLabel Marks
(ii) JTextfield
(iii) JButton
(iv) JComboBox

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)

Prepared by: Mr. R Rajkumar – Assistant Professor, Dept. of ISE, RNSIT, Bengaluru – 98
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) JComboBox: Swing provides a combo box (a combination of a text field and a drop-
down list) through the JComboBox class. A combo box normally displays one entry, but it
will also display a drop-down list that allows a user to select a different entry.
The JComboBox constructor is shown here:
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box.

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

You might also like