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

OOP-1 Answers

Uploaded by

makkakuldip
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)
65 views

OOP-1 Answers

Uploaded by

makkakuldip
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/ 28

Object Oriented Programming - I 3140705

Question 1: Explain features of JAVA.


Answer: Features of java are as follows:
1) Compiled and Interpreted:
 Java combines both approaches are either compiled or interrupted. Thus making java a two stage
system.
 Java compiler translates source code into byte code instructions. Byte codes are not machine
instructions and therefore in the second stage java interpreter generates machine code that can be
directly executed by the machine that is running the java program.
2) Platform Independent and Portable:
 The most significant contribution of java over other languages is its portability.
 Java programs can be easily moved from one computer system to another, anywhere and anytime.
 Changes and upgrades in operating system, processors and system resources will not force any
changes in java programs.
 Java ensures portability in two ways: first, java compiler generates byte code instructions that can
be implemented on any machine. Secondly, the size of primitive data types is machine
independent.
3) Object-Oriented:
 Java is true object oriented language. Almost everything in java is an object. All program code
and data reside within objects and classes.
 Java comes with an extensive set of classes, arranged in packages that we can use in programs by
inheritance.
4) Robust and Secure:
 Java is a robust language. it provides many safeguards to ensure reliable code.
 It has strict compile time and run time checking for data types.
 Java systems not only verify all memory access but also ensure that no viruses are communicated
with an applet.
5) Distributed:
 Java is designed as distributed language for creating application on networks. It has ability to
share both data and programs.
 Java applications can open and access remote objects on internet as easily as they can do in local
system.
6) Simple, Small and Familiar:
 Java is small and simple language.
 Java does not use pointers, preprocessor header files, goto statement and many others.
 It also eliminates operator overloading and multiple inheritance.
7) Multithreaded and Interactive:
 Multithreaded means handling multiple tasks simultaneously.
 Java supports multithreaded programs. This means that we need not wait for application to finish
one task before beginning another.
 The java runtime comes with tools that support multiprocess synchronization and construct
smoothly running interactive systems.
8) Dynamic and Extensible:
 Java is dynamic language; java is capable of dynamically linking in new class libraries, methods
and objects.
 Java can also determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.
 Java programs support functions written in other languages such as c and c++. These functions
are known as native methods.
9) High Performance:
 Java performance is impressive for an interpreted language, mainly due to the use of byte code.
 Java architecture is also designed to reduce overheads during runtime.

1 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Question 2: Define and write a program to differentiate between pass by value and pass
by reference.
Answer:
 There are two ways that a computer language can pass an argument to a subroutine.

 The first way is call-by-value. This method copies the value of an argument into the formal parameter
of the subroutine.
 Therefore, changes made to the parameter of the subroutine have no effect on the argument.

 The second way an argument can be passed is call-by-reference.


 In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
 Inside the subroutine, this reference is used to access the actual argument specified in the call.
 This means that changes made to the parameter will affect the argument used to call the subroutine.

// Simple types are passed by value.


class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}

class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);

ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}

The output is shown here:

a and b before call: 15 20


a and b after call: 15 20

As you can see, the operations that occur inside meth( ) have no effect on the values of a and b used in the call;
their values here did not change to 30 and 10.

When you pass an object to a method, the situation changes dramatically, because objects are passed by
reference.

This effectively means that objects are passed to methods by use of call-by-reference. Changes to the object
inside the method do affect the object used as an argument.

2 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

For example, consider the following program:


// Objects are passed by reference.
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}

// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}

class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);

ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}

This program generates the following output:

ob.a and ob.b before call: 15 20


ob.a and ob.b after call: 30 10

Question 3: Differentiate between constructor and method of class. Define method


overloading and its purpose. Write a program to demonstrate the constructor
overloading.
Answer:

Differentiate between constructor and method:


 Name of constructor must be same with name of the Class but there is no such requirement for method
in Java. Methods can have any arbitrary name in Java.

 Constructor doesn't have any return type but method has return type and returns something unless it
is void.
o Constructors are not inherited by child classes but methods are inherited by child classes until
they are made private.

3 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Method overloading:
 If class have more than one method by same name but different argument is called overloaded method,
and the process is referred to as method overloading.
 Method overloading is one of the ways that Java implements polymorphism.
 When an overloaded method is invoked, Java uses the type and/or number of arguments to determine
which version of the overloaded method to actually call.
 Thus, overloaded methods must differ in the type and/or number of their parameters.

Constructor overloading Example:


class Box
{
double width, height, depth;

// constructor
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor
Box()
{
width = -1;
height = -1;
depth = -1;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
Box b1 = new Box(10, 20, 15);
Box b2 = new Box();

double vol;

vol =b1.volume();
System.out.println("Volume of mybox1 is " + vol);

vol = b2.volume();
System.out.println("Volume of mybox2 is " + vol);
}
}

4 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

The output produced by this program is shown here:

Volume of mybox1 is 3000.0


Volume of mybox2 is -1.0

As you can see, the proper overloaded constructor is called based upon the parameters specified when
new is executed.

Question 4: Explain short circuited operators and shift operators.


Answer:

Short circuited operators

 These are secondary versions of the Boolean AND and OR operators, and are known as short-circuit
logical operators
 The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't
necessary.

public class Example


{
public static void main(String[] args)
{
int denom = 0;
int num = 3;

if (denom != 0 && num / denom > 10)


{
System.out.println("Here");
}
else
{
System.out.println("There");
}
}
}

Output: There

Shift operators
 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

 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

5 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

 The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. It has
this general form:
value << num

 That is, the << moves all of the bits in the specified value to the left by the number of bit positions
specified by num.

Question 5: (I) JVM is platform dependent. Justify.


(II) There is no destructor in Java. Justify.
Answer:

(I) JVM is platform dependent.

 The Java provides portability because of bytecode.


 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).
 The JVM is an interpreter for bytecode.
 Translating a Java program into bytecode helps makes it much easier to run a program in a wide variety
of environments.
 The reason is straightforward: 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 interpret the
same Java bytecode.
 Hence we needs different JVM for different platform, so we can say JVM is platform dependent.

(II) There is no destructor in Java.

 In Java objects are dynamically allocated by using the new operator.


 In some languages, such as C++, dynamically allocated objects must be manually released by use of a
delete operator.
 Java takes a different approach; it handles deallocation automatically.
 The technique that accomplishes this is called garbage collection.
 When no references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
 There is no explicit need to destroy objects like in C++.
 Garbage collection only occurs sporadically during the execution of your program.

Question 6: Define polymorphism with its need. Define and explain static and dynamic
binding using program.
Answer:

 ABALATY to take more than one form is called polymorphism.


 If we have to perform same operation using different argument so methods increase the readability of
the program.

Polymorphism in Java has two types:


 Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding).
 Method overloading is an example of static polymorphism, while method overriding is an example of
dynamic binding.

6 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Static Binding OR Method Overloading OR Early Binding:


 If compiler can solve the binding at the compile time only then such a binding is called as static
binding.
 Method overloading means there are several methods present in a class having the same name but
different types/order/number of parameters.

// Demonstrate method overloading.


class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();

ob.test();
ob.test(10);
ob.test(10, 20);
}
}

This program generates the following output:

No parameters
a: 10
a and b: 10 20

Dynamic Binding OR Overriding Method OR Late Binding OR Runtime Polymorphism

When a method in a subclass has the same name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the superclass.

When an overridden method is called from within a subclass, it will always refer to the version of that method
defined by the subclass.

The version of the method defined by the superclass will be hidden. Consider the following:

7 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

// Method overriding.
class A
{
int i, j;

A(int a, int b)
{
i = a;
j = b;
}

void show()
{
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A
{
int k;

B(int a, int b, int c)


{
super(a, b);
k = c;
}
void show() //This overrides show() in A
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B b1 = new B(1, 2, 3);
b1.show(); // this calls show() in B
}
}

The output produced by this program is shown here:


k: 3

Question 7: List OOP characteristics and describe inheritance with examples.


Answer:

OOP characteristics are listed as below:-


1. Object and classes
2. Data abstraction and Encapsulation
3. Inheritance
4. Polymorphism
8 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA
Object Oriented Programming - I 3140705

5. Compile time and run time mechanism


6. Dynamic binding
7. Message passing.

 Inheritance allows the creation of hierarchical classifications.


 Using inheritance, you can create a general class that defines common set of related items.
 This class can then be inherited by other, more specific classes, each adding those things that are unique to it.
 A class that is inherited is called a superclass.
 The class that does the inheriting is called a subclass.
 Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods
defined by the superclass and adds its own, unique elements.

The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name


{
// body of class
}

// A simple example of inheritance.


// Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
B b1 = new B();
b1.i = 7;
b1.j = 8;
b1.k = 9;

b1.showij();
System.out.println("Sum of i, j and k in b1 is=:");
b1.sum();
}
}
9 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA
Object Oriented Programming - I 3140705

Question 8: Explain inner class and working of concatenation operator + by giving


examples.
Answer:

 It is possible to define a class within another class; such classes are known as nested classes.
 The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined
within class A, then B is known to A, but not outside of A.
 A nested class has access to the members, including private members, of the class in which it is nested.
 However, the enclosing class does not have access to the members of the nested class.
 There are two types of nested classes: static and non-static.
 A static nested class is one which has the static modifier applied. Because it is static, it must access the
members of its enclosing class through an object.
 That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested
classes are seldom used.

The most important type of nested class is the inner class.


 An inner class is a non-static nested class.
 It has access to all of the variables and methods of its outer class and may refer to them directly in the
same way that other non-static members of the outer class do.
 Thus, an inner class is fully within the scope of its enclosing class.

// Demonstrate an inner class.


class Outer
{
int outer_x = 100;
void test()
{
Inner in = new Inner();
in.display();
}
// this is an inner class
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
Output from this application is shown here:
display: outer_x = 100

10 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Working of concatenation operator +

Concatenation describes the operation of joining two strings together.

The operator "+" normally acts as an arithmetic operator unless one of its operands is a String.

If necessary it converts the other operand to a String before joining the second operand to the end of the first
operand.

To join the two Strings "java" and "oopj":

System.out.println("java" + "oopj");

If one of the operands is not a String it will be converted:

int age = 12;


System.out.println("My age is " + age);

Question 9: Explain interface in JAVA. How do interfaces support polymorphism?


Answer:

 Using the keyword interface, you can fully abstract a class’ interface from its implementation.
 That is, using interface, you can specify what a class must do, but not how it does it.
 Once it is defined, any number of classes can implement an interface.
 Also, one class can implement any number of interfaces.
 To implement an interface, a class must create the complete set of methods defined by the interface.
 However, each class is free to determine the details of its own implementation.
 By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.

Defining an Interface
An interface is defined much like a class. This is the general form of an interface:

access interface interfacename


{
return-type method-name1(parameter-list);
type final-varname1 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.

To implement an interface, include the implements clause in a class definition, and then create the methods
defined by the interface.

The general form of a class that includes the implements clause looks like this:

11 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

access class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

//Example of Interface:
interface A
{
void addition(int a,int b);
void subtraction(int a,int b);
}
class B implements A
{
int sum,sub;
public void addition(int a, int b)
{
sum=a+b;
System.out.println("summation="+sum);
}
public void subtraction(int a, int b)
{
sub=a-b;
System.out.println("subtraction="+sub);
}
}
class InterfaceDemo
{
public static void main(String args[])
{
B b1= new B();
b1.addition(10,5);
b1.subtraction(10,5);
}
}

Question 10: What is the use following java keywords: super, transient, finally, final,
static, throw, throws.
Answer:

super:
 super is used to refer immediate parent class instance variable.
 super is used to invoked immediate parent class constructor.
 super is used to invoke immediate parent class method

transient:
 The transient keyword is used in serialization. If you define any data member as transient, it will
not be serialized.
 When an instance variable is declared as transient, then its value need not persist when an object
is stored. For example:

12 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

class T
{
transient int a; // will not persist
int b; // will persist
}

finally :
 The finally block always executes immediately after try-catch block exits.
 The finally block is executed incase even if an unexpected exception occurs.
 The main usage of finally block is to do clean up job. Keeping cleanup code in a finally block is
always a good practice, even when no exceptions are occurred.
 The runtime system always executes the code within the finally block regardless of what happens
in the try block. So it is the ideal place to keep cleanup code.
final :
 Final method can not be overridden in Java .
 Final class can not be inheritable in Java.

final class A
{
// ...
}
// The following class is illegal.
class B extends A
{ // ERROR! Can't subclass A
// ...
}

static:
The static keyword is used i n java mainly for memory mgmt. we may apply static keywords with
variable, methods, blocks, and nested class. The static keywords belong to the class than instance of
class.
The static can be:
 variable (also known as class variable): the static variable can be used to refer the common
property of all object
 Method (also known as class method):A static method belongs to the class rather than object of a
class. A static method can be invoked without the need for creating an instance of a class. and
access static data member.
 Block (The static block, is a block of statement inside a Java class that will be executed before
main method at time of class loading.)
throw :
 It is used to create a new Exception object and throw it.
 The throw keyword is mainly used to throw custom execption.

The general form of throw is shown here:


throw ThrowableInstance;

throws :
 throws keyword must be used when a method is throwing checked exception, This will enforce
its handling by callee method otherwise JVM will throw compile time exception for that.
 throws keyword has not much impact or JVM won't bother if its throwing unchecked exception,
Hence JVM won't throw any compile time exception for that.

Syntax:
void method_name () throws Exception_class_name
13 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA
Object Oriented Programming - I 3140705

{
....
}

Question 11: Explain the importance of exception handling in java. Which key words are
used to handle exceptions? Write a program to explain the use of these keywords.
Answer:

 An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a run-time error.
 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.
 Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
 Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system.
 To manually throw an exception, use the keyword throw.
 Any exception that is thrown out of a method must be specified as such by a throws clause. Any code
that absolutely must be executed before a method returns is put in a finally block.

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 before try block ends
}

//Example: Exception handling program

class Ex2
{
public static void main(String args[])

14 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("this is finally block");

}
}
}

This program generates the following output:

Division by zero.
this is finally block

Question 12: Enlist and explain the difference between error and exception. Write a
program to handle InterruptedException, IllegalArgumentException using try-catch-
finally and throw.
Answer:

Difference between error and exception

Exceptions:
Can be checked or unchecked
Indicate an error caused by the programmer
Should be handled at the application level

Errors:
Are always unchecked
Usually indicate a system error or a problem with a low-level resource
Should be handled at the system level, if possible.

class ExceptionDemo
{
static void demoproc()
{
try

15 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

{
throw new IllegalArgumentException("demo");
}
catch(IllegalArgumentException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
Thread t = Thread.currentThread();

try
{
demoproc();

try
{
for(int n = 5; n > 0; n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}

}
catch(IllegalArgumentException e)
{
System.out.println("Recaught: " + e);
}
}
}

Output:
Caught inside demoproc.
Recaught: java.lang.IllegalArgumentException: demo

16 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Question 12: Explain Thread Life Cycle in detail. Write a code to create Thread in JAVA.
Answer:
Thread has many different state throughout its life.

1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State

1 Newborn State
 When we create a thread it will be in Newborn State.
 The thread is just created still its not running.
 We can move it to running mode by invoking the start() method and it can be killed by using stop()
method.

2 Runnable State
 It means that thread is now ready for running and its waiting to give control.
 We can move control to another thread by yield() method.

17 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

3 Running State
 It means thread is in its execution mode becaause the control of cpu is given to that particular thread.
 It can be move in three different situation from running mode.
 These all are different methods which can be apply on running thread and how the state is changing
and how we can come in our original previous state using different methods are shown in above
figure

4 Blocked State
 A thread is called in Blocked State when it is not allowed to entering in Runnable State or Running
State.
 It happens when thread is in waiting mode, suspended or in sleeping mode.
5 Dead State
 When a thread is completed executing its run() method the life cycle of that particular thread is end.
 We can kill thread by invoking stop() method for that particular thread and send it to be in Dead
State.

class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Thread");

System.out.println("After name change: " + t);


try
{

18 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

for(int n = 5; n > 0; n--)


{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}

19 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Output:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1

Question 14: What is multithreading? Why it is required? Write a program that creates
three threads. Make sure that the main thread executes last.
Answer:
 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.
 There are two distinct types of multitasking: processbased and thread-based.
 A process is, in essence, a program that is executing.
 Thus, process-based multitasking is the feature that allows your computer to run two or more programs
concurrently.
 For example, process-based multitasking enables you to run the Java compiler at the same time that you
are using a text editor.
 In processbased multitasking, a program is the smallest unit of code that can be dispatched by the
scheduler.
 In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code.
 This means that a single program can perform two or more tasks simultaneously.
 For instance, a text editor can format text at the same time that it is printing, as long as these two actions
are being performed by two separate threads.
 Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the
details.

// Create multiple threads.


class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}

20 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

The output from this program is shown here:

New thread: Thread[One,5,main]


New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.

21 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Question 15: Why synchronization is required in multithreaded programming. Write a


program that uses thread synchronization to guarantee data integrity in a multithreaded
application.
Answer:
 When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
 A monitor is an object that is used as a mutually exclusive lock, or mutex.
 Only one thread can own a monitor at a given time.
 When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to
enter the locked monitor will be suspended until the first thread exits the monitor.
 These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the
same monitor if it so desires.
 Java implements synchronization through language elements, most of the complexity associated with
synchronization has been eliminated.

class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
class Synch
{
public static void main(String args[])
{

22 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Callme target = new Callme();


Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}

Output:

[Hello]
[Synchronized]
[World]

Question 16: Explain wait, notify, synchronized methods.


Answer:
 Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods.
 These methods are implemented as final methods.
 All three methods can be called only from within a synchronized context.

 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 as shown here:

final void wait( ) throws InterruptedException


final void notify( )
final void notifyAll( )

Synchronization is easy in Java, because all objects have their own implicit monitor associated with them.

To enter an object’s monitor, just call a method that has been modified with the synchronized keyword.

While a thread is inside a synchronized method, all other threads that try to call it on the same instance have to
wait.

To exit the monitor the owner of the monitor simply returns from the synchronized method.

23 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

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

24 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

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.");
}
}

Output:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5

25 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Question: 17. differentiate the followings:


a. String class and String Buffer class
b. Text I/O and Binary I/O
c. Compare byte streams and character streams.
Answer:

a) String class and String Buffer class

Strings:

Immutable:-When You perform any write operation on existing String object, a new object will be
created, the modification is done there, and that object will be returned to you. The old object will lose
the reference and hence garbage collected later.

String Pool:-It supports String Pool concepts. So you can write String str=”Hello”;

Performance:-Low performance, due to unnecessary object created

overriding:-Strings class has overrided equals() from object class, equals() checks for content equality

StringBuffers:

mutable:-When you perform any write operation on existing StringBuffer object, new object will not
be created and same object will be modified

String Pool:-It doesnot support String pool concepts.So you cannot write StringBuffer strBuff=”Hello”;

Performance:-High Performance

Overriding:-This class has not overrided equals().so equals() will still compare for reference equality
b ) Text I/O and Binary I/O:
Text I/O:
 Text I/o requires encoding and decoding.
 JVM converts a Unicode to a file specific encoding when writing a character.
 JAVA source program are started.
Binary I/O:
 Binary I/O does not require conversion.
 When you write a byte to a file, the original byte is copied into the file. When you read a byte from a file
,the exact in the file is returned.
 Java classes are stored.

c) Compare byte streams and character streams:

Byte streams:

 The byte stream classes provide a rich environment for handling byte-oriented I/O.

 A byte stream can be used with any type of object, including binary data. This versatility makes byte
streams important to many types of programs.

 The byte stream classes are topped by InputStream and OutputStream.

26 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Character streams:
 While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they
cannot work directly with Unicode characters.

 Since one of the main purposes of Java is to support the “write once, run anywhere” philosophy, it was
necessary to include direct I/O support for characters.

 At the top of the character stream hierarchies are the Reader and Writer abstract classes. We will begin
with them.

Question 18: What is an abstract class? Explain with the help of example.
Answer:
 Sometimes you will want to create a superclass that only defines a generalized form that will be shared
by all of its subclasses, leaving it to each subclass to fill in the details, that is called abstract class.
 Such a class determines the nature of the methods that the subclasses must implement.

 To declare an abstract method, use this general form:

abstract type name(parameter-list);

abstract class A
{
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a simple method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}

Output:
B's implementation of callme
This is a simple method.

27 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA


Object Oriented Programming - I 3140705

Question 19: Explain Access protection in detail.


Answer:

 The three access specifiers, private, public, and protected, provide a variety of ways to produce the
many levels of access required by these categories.
 Anything declared public can be accessed from anywhere.
 Anything declared private cannot be seen outside of its class.
 When a member does not have an explicit access specification, it is visible to subclasses as well as to
other classes in the same package. This is the default access.
 If you want to allow an element to be seen outside your current package, but only to classes that subclass
your class directly, then declare that element protected.
 Below table applies only to members of classes.
 A class has only two possible access levels: default and public.
 When a class is declared as public, it is accessible by any other code.
 If a class has default access, then it can only be accessed by other code within its same package.

28 SANJAYBHAI RAJGURU COLLEGE OF ENGINEERING – RAJKOT J.K. RATANPARA

You might also like