0% found this document useful (0 votes)
65 views15 pages

2021 Java Solution

Inheritance in Java allows classes to acquire properties and behaviors of parent classes. The main types of inheritance are: 1) Single inheritance: A class inherits from one parent class (e.g. Dog class inherits from Animal class). 2) Multilevel inheritance: A chain of inheritance with subclasses inheriting from parent classes (e.g. BabyDog inherits from Dog which inherits from Animal). 3) Hierarchical inheritance: Multiple classes can inherit from a single parent class (e.g. Dog and Cat classes both inherit from Animal class). Interfaces in Java allow classes to inherit common behaviors without inheriting concrete implementations. Implementing interfaces allows classes to achieve abstraction and multiple inheritance which are not possible

Uploaded by

Rajesh Pal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
65 views15 pages

2021 Java Solution

Inheritance in Java allows classes to acquire properties and behaviors of parent classes. The main types of inheritance are: 1) Single inheritance: A class inherits from one parent class (e.g. Dog class inherits from Animal class). 2) Multilevel inheritance: A chain of inheritance with subclasses inheriting from parent classes (e.g. BabyDog inherits from Dog which inherits from Animal). 3) Hierarchical inheritance: Multiple classes can inherit from a single parent class (e.g. Dog and Cat classes both inherit from Animal class). Interfaces in Java allow classes to inherit common behaviors without inheriting concrete implementations. Implementing interfaces allows classes to achieve abstraction and multiple inheritance which are not possible

Uploaded by

Rajesh Pal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

2021

COMPUTER SCIENCE — HONOURS


Paper : CC-12
(Object Oriented Programming)
Full Marks : 50

1. Answer any five questions :

a. What is mutable string?


Mutable means changing over time or that can be changed. In a mutable string, we can
change the value of the string and JVM doesn’t create a new object. In a mutable string,
we can change the value of the string in the same object.
To create a mutable string in java, Java has two classes StringBuffer and StringBuilder
where the String class is used for the immutable string.

b. What is the use of abstract class in Java?


A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of
the method.

c. What is the base class of Error and Exception?


All exception classes are subtypes of the java.lang.Exception class. The Exception class is
a subclass of the Throwable class. Other than the Exception class there is another
subclass called Error which is derived from the Throwable class.

d. What is the use of ‘this’ keyword in Java?


The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed
by a method or constructor parameter). If you omit the keyword in the example above,
the output would be "0" instead of "5".

1|Page
this can also be used to:
 Invoke current class constructor
 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

e. What is a Copy Constructor?


In Java, a copy constructor is a special type of constructor that creates an object using
another object of the same Java class. It returns a duplicate copy of an existing object of
the class.

We can assign a value to the final field but the same cannot be done while using the
clone() method. It is used if we want to create a deep copy of an existing object. It is
easier to implement in comparison to the clone() method.
Sometimes, we face a problem where we required to create an exact copy of an existing
object of the class. There is also a condition, if we have made any changes in the copy it
should not reflect in the original one and vice-versa. For such cases, Java provides the
concept of a copy constructor.

f. What Java is called platform independent?


The meaning of platform-independent is that the java compiled code(byte code) can run
on all operating systems.
A program is written in a language that is a human-readable language. It may contain
words, phrases, etc which the machine does not understand. For the source code to be
understood by the machine, it needs to be in a language understood by machines,
typically a machine-level language. So, here comes the role of a compiler. The compiler
converts the high-level language (human language) into a format understood by the
machines. Therefore, a compiler is a program that translates the source code for
another program from a programming language into executable code.
This executable code may be a sequence of machine instructions that can be executed
by the CPU directly, or it may be an intermediate representation that is interpreted by a
virtual machine. This intermediate representation in Java is the Java Byte Code.

g. How vector differs from a list?

Vector List

It has contiguous memory. While it has non-contiguous memory.

It is synchronized. While it is not synchronized.

Vector may have a default size. List does not have default size.

2|Page
Vector List

In list, each element requires extra space


for the node which holds the element,
In vector, each element only requires the including pointers to the next and previous
space for itself only. elements in the list.

Insertion at the end requires constant time Insertion is cheap no matter where in the
but insertion elsewhere is costly. list it occurs.

Vector is thread safe. List is not thread safe.

Deletion at the end of the vector needs Deletion is cheap no matter where in the
constant time but for the rest it is O(n). list it occurs.

Random access of elements is possible. Random access of elements is not possible.

Iterators become invalid if elements are Iterators are valid if elements are added to
added to or removed from the vector. or removed from the list.

h. What is the use of finally () method in Java?


The finally keyword is used to execute code (used with exceptions - try..catch
statements) no matter if there is an exception or not.
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.
The finally block follows the try-catch block.

3|Page
2.
a. What is inheritance in Java? Explain different types of inheritance with example.
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class TestInheritance{  

4|Page
8. public static void main(String args[]){  
9. Dog d=new Dog();  
10. d.bark();  
11. d.eat();  
12. }} 

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see
in the example given below, BabyDog class inherits the Dog class which again inherits
the Animal class, so there is a multilevel inheritance.
1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class BabyDog extends Dog{  
8. void weep(){System.out.println("weeping...");}  
9. }  
10. class TestInheritance2{  
11. public static void main(String args[]){  
12. BabyDog d=new BabyDog();  
13. d.weep();  
14. d.bark();  
15. d.eat();  
16. }}

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class Cat extends Animal{  
8. void meow(){System.out.println("meowing...");}  
9. }  
10. class TestInheritance3{  
11. public static void main(String args[]){  
12. Cat c=new Cat();  
13. c.meow();  
14. c.eat();  
15. //c.bark();//C.T.Error  
16. }}
b. Explain with the help of an example, how Java gets benefited by using Interface.
Here is a list of the main advantages of using an interface in Java. THese are also the
most important reasons I use interface while coding.

Easier to Test

5|Page
One of the key benefits of using an interface in Java is Testing, the interface makes unit
testing easier. The best example of this is DAO pattern and parser classes. If your code is
using interface for dependencies then you can easily replace them with a mock, stub, or
a dummy for testing. 
For example, if your code needs a Cache and you are using an interface variable to hold
that dependency, you can write a HashMap based Cache implementation for testing like
below:

In this code, if you want to test isExists() method, you need to create an object


of BookRepository which needs a Cache. If this class loads data from a database, and
build cache then it would be difficult to test because loading data from the database
takes time. 
If you use the interface, you can swap the actual cache with a dummy in-memory
hashmap based cache and test with lightning speed.
Faster Development
This is the fourth practical benefit of interface I have noticed while working on a Java
project. In a real project, you often have dependencies on your partner's and colleagues'
work. 
For example, if your application is a client-server application where the client sends and
receives data from the server then you may need to wait until your partner finishes
server-side work before you can start client-side work.
If you use an interface, you can work around this becuase the interface doesn't require
any actual implementation. All you need to agree on is the name of the interface and
operation on them which is much easier than actually coding those operations. To be
honest, this has saved a ton of time in our case.
Increased Flexibility
The third benefit of the interface in Java is that it increases flexibility or result in more
flexible code. You may be wondering what is flexibility? well, it means your code should
be flexible to change. It should be easy to use different logic at different times. 
For example, a TracelCostCalculator should be able to calculate fair for bus, train, or
plane journey. This is achieved by using different implementations of the same
interface. 
Anyway, this example may not be the best to prove the point but it does make intention
clear. If you have a better example, feel free to share it with us.

Loosely couple code


The first benefit of the interface in Java is that it creates loosely coupled code, which is
easier to change and maintain. In a loosely coupled code, you can replace pieces without
affecting the whole  structure.

6|Page
While in a tightly coupled code, it's not possible to replace one part of code without
impacting other parts of code. I am not able to think of an appropriate example now, but
I'll add it later. In the meantime, if you have any, just drop a note and we can discuss.
Dependency Injection
Finally, the Dependency injection is based on an interface. In the case of DI, instead of
a developer, the framework injects dependencies and this is achieved by declaring
dependencies as interfaces.
3.
a. Write a Java program to check whether a string is palindrome using command line
argument.
import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it
is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a
palindrome.");
else
System.out.println("Entered string/number isn't a
palindrome.");
}
}
b. How will you perform type casting in Java?

Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting Example –


public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting Example –
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

7|Page
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

c. Explain with an example how Labelled loop works in Java.


A label is a valid variable name that denotes the name of the loop to where the control
of execution should jump. To label a loop, place the label before the loop with a colon at
the end. Therefore, a loop with the label is called a labelled loop.
Labeling a for loop is useful when we want to break or continue a specific for loop
according to requirement. If we put a break statement inside an inner for loop, the
compiler will jump out from the inner loop and continue with the outer loop again.
What if we need to jump out from the outer loop using the break statement given inside
the inner loop? The answer is, we should define the label along with the colon(:) sign
before the loop.
Example:
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
4.
a. State the differences between the string and stringbuffer classes in Java.

8|Page
b. Explain with example, how copy constructor is used in Java.
Sometimes, we face a problem where we required to create an exact copy of an existing
object of the class. There is also a condition, if we have made any changes in the copy it
should not reflect in the original one and vice-versa. For such cases, Java provides the
concept of a copy constructor.
In Java, a copy constructor is a special type of constructor that creates an object using
another object of the same Java class. It returns a duplicate copy of an existing object of
the class.
We can assign a value to the final field but the same cannot be done while using the
clone() method. It is used if we want to create a deep copy of an existing object. It is
easier to implement in comparison to the clone() method.
We can use the copy constructor if we want to:
o Create a copy of an object that has multiple fields.
o Generate a deep copy of the heavy objects.
o Avoid the use of the Object.clone() method.

Example:
public class Fruit
{
private double fprice;
private String fname;
//constructor to initialize roll number and name of the student
Fruit(double fPrice, String fName)
{
fprice = fPrice;
fname = fName;
}
//creating a copy constructor
Fruit(Fruit fruit)
{
System.out.println("\nAfter invoking the Copy Constructor:\n");
fprice = fruit.fprice;
fname = fruit.fname;
}

9|Page
//creating a method that returns the price of the fruit
double showPrice()
{
return fprice;
}
//creating a method that returns the name of the fruit
String showName()
{
return fname;
}
//class to create student object and print roll number and name of the student
public static void main(String args[])
{
Fruit f1 = new Fruit(399, "Ruby Roman Grapes");
System.out.println("Name of the first fruit: "+ f1.showName());
System.out.println("Price of the first fruit: "+ f1.showPrice());
//passing the parameters to the copy constructor
Fruit f2 = new Fruit(f1);
System.out.println("Name of the second fruit: "+ f2.showName());
System.out.println("Price of the second fruit: "+ f2.showPrice());
}
}

c. Discuss about different types of throwable exceptions in Java.


In Java, exception is an event that occurs during the execution of a program and disrupts
the normal flow of the program's instructions. Bugs or errors that we don't want and
restrict our program's normal execution of code are referred to as exceptions. In this
section, we will focus on the types of exceptions in Java and the differences between
the two.

1. ArithmeticException: It is thrown when an exceptional condition has occurred in an


arithmetic operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal
to the size of the array.

10 | P a g e
3. ClassNotFoundException: This Exception is raised when we try to access a class
whose definition is not found
4. FileNotFoundException: This Exception is raised when a file is not accessible or does
not open.
5. IOException: It is thrown when an input-output operation failed or interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some
processing, and it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is not found.
9. NullPointerException: This exception is raised when referring to the members of a
null object. Null represents nothing
10. NumberFormatException: This exception is raised when a method could not convert
a string into a numeric format.
11. RuntimeException: This represents an exception that occurs during runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods to indicate
that an index is either negative or greater than the size of the string
13. IllegalArgumentException : This exception will throw the error or error statement
when the method receives an argument which is not accurately fit to the given
relation or condition. It comes under the unchecked exception. 
14. IllegalStateException : This exception will throw an error or error message when the
method is not accessed for the particular operation in the application. It comes
under the unchecked exception.

5.
a. Predict the output of the following code and comment of your answer.
Class leftshift_operator
{
Public static void main (string avgs [ ] )
{
byte x=64;
int i;
byte y;
i=x<<2;
y=(byte)(x<<2);
System.out.print (i+ “ ” + y);
}
}

b. What are the different types of AWT components? How are these components added
to the container?
An AWT component can be considered as an object that can be made visible on a
graphical interface screen and through which interaction can be performed.
In java.awt package, the following components are available:

1. Containers: As the name suggests, this awt component is used to hold other
components.
Basically, there are the following different types of containers available in java.awt
package:

11 | P a g e
a. Window: This is a top-level container and an instance of a window class that does
not contain a border or title.

b. Frame: Frame is a Window class child and comprises the title bar, border and
menu bars. Therefore, the frame provides a resizable canvas and is the most widely
used container used for developing AWT-based applications. Various components
such as buttons, text fields, scrollbars etc., can be accommodated inside the frame
container.
Java Frame can be created in two ways:
 By Creating an object of Frame class.
 By making Frame class parent of our class.
Dialog: Dialog is also a child class of window class, and it provides support
for the border as well as the title bar. In order to use dialog as a container, it
always needs an instance of frame class associated with it.
Panel: It is used for holding graphical user interface components and does
not provide support for the title bar, border or menu.
2. Button: This is used to create a button on the user interface with a specified label. We
can design code to execute some logic on the click event of a button using listeners.
3. Text Fields: This component of java AWT creates a text box of a single line to enter
text data.
4. Label: This component of java AWT creates a multi-line descriptive string that is
shown on the graphical user interface.
5. Canvas: This generally signifies an area that allows you to draw shapes on a graphical
user interface.
6. Choice: This AWT component represents a pop-up menu having multiple choices. The
option which the user selects is displayed on top of the menu.
7. Scroll Bar: This is used for providing horizontal or vertical scrolling feature on the GUI.
8. List: This component can hold a list of text items. This component allows a user to
choose one or more options from all available options in the list.
9. Checkbox: This component is used to create a checkbox of GUI whose state can be
either checked or unchecked.
c. Explain how multiple inheritance can be implemented in Java.
Java does not support multiple inheritance. This means that a class cannot extend more
than one class, but we can still achieve the result using the keyword 'extends'.
Step 1 – START
Step 2 – Declare three classes namely Server, connection and my_test
Step 3 – Relate the classes with each other using 'extends' keyword
Step-4 – Call the objects of each class from a main function.
Step 5 – STOP
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit
properties of more than one parent class. The problem occurs when there exist methods
with the same signature in both the superclasses and subclass. On calling the method,
the compiler cannot determine which class method to be called and even on calling
which class method gets the priority. 
Example:
// Java Program to Illustrate Unsupportance of
// Multiple Inheritance

12 | P a g e
// Importing input output classes
import java.io.*;
// Class 1
// First Parent class
class Parent1 {
// Method inside first parent class
void fun() {
// Print statement if this method is called
System.out.println("Parent1");
}
}
// Class 2
// Second Parent Class
class Parent2 {
// Method inside first parent class
void fun() {
// Print statement if this method is called
System.out.println("Parent2");
}
}
// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {
// Main driver method
public static void main(String args[]) {
// Creating object of class in main() method
Test t = new Test();
// Trying to call above functions of class where
// Error is thrown as this class is inheriting
// multiple classes
t.fun();
}
}
Output:
Compilation error is thrown

6.
a. What is a vector? How does it differ from an array and list?
A vector is a list of data items, and can be constructed with an assignment statement like
A=[1.2, 3.1, 4.6, 5.7]
Note that square brackets are used to contain the list. Try typing a list like that shown
above and then using HELP,A to get information about the vector.
Vectors can contain any of the number types that are accepted by IDL. When the
assignment is made all of the numbers are converted to one type. The type that is used
is determined by the data type hierarchy. Try typing
A=[1, 3B, 4L, 5.7] & HELP,A
IDL responds that A is an array of type FLOAT of length 4. If you were to type

13 | P a g e
A=[1, 3B, 4L, 5] & HELP,A
you would find that A is now of type LONG. The rule is to convert all of the numbers to
the highest number type.

Vector List

It has contiguous memory. While it has non-contiguous memory.

It is synchronized. While it is not synchronized.

Vector may have a default size. List does not have default size.

In list, each element requires extra space for the


In vector, each element only requires the space node which holds the element, including pointers to
for itself only. the next and previous elements in the list.

Insertion at the end requires constant time but Insertion is cheap no matter where in the list it
insertion elsewhere is costly. occurs.

Vector is thread safe. List is not thread safe.

Deletion at the end of the vector needs constant Deletion is cheap no matter where in the list it
time but for the rest it is O(n). occurs.

Random access of elements is possible. Random access of elements is not possible.

Iterators become invalid if elements are added to Iterators are valid if elements are added to or
or removed from the vector. removed from the list.

b. Write a program to count the number of words in a given sentence.


import java.util.Scanner;
public class Exercise5 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();

14 | P a g e
System.out.print("Number of words in the string: " +
count_Words(str)+"\n");
}

public static int count_Words(String str)


{
int count = 0;
if (!(" ".equals(str.substring(0, 1))) || !("
".equals(str.substring(str.length() - 1))))
{
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ' ')
{
count++;
}
}
count = count + 1;
}
return count; // returns 0 if string starts or ends with
space " ".
}
}

15 | P a g e

You might also like