OOP-1 Answers
OOP-1 Answers
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.
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);
}
}
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.
// 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);
}
}
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.
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
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);
}
}
As you can see, the proper overloaded constructor is called based upon the parameters specified when
new is executed.
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.
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
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 6: Define polymorphism with its need. Define and explain static and dynamic
binding using program.
Answer:
ob.test();
ob.test(10);
ob.test(10, 20);
}
}
No parameters
a: 10
a and b: 10 20
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:
// 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;
The general form of a class declaration that inherits a superclass is shown here:
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
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 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.
System.out.println("java" + "oopj");
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:
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:
//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:
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.
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.
class Ex2
{
public static void main(String args[])
{
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");
}
}
}
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:
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
{
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
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.
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");
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.
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.");
}
}
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[])
{
Output:
[Hello]
[Synchronized]
[World]
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.
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.
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++);
}
}
}
Output:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
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”;
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.
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.
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.
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.
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.