2021 Java Solution
2021 Java Solution
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
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.
Vector List
Vector may have a default size. List does not have default size.
2|Page
Vector List
Insertion at the end requires constant time Insertion is cheap no matter where in the
but insertion elsewhere is costly. list it occurs.
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.
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.
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.
4|Page
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
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:
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:
7|Page
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
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());
}
}
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
Vector may have a default size. List does not have default size.
Insertion at the end requires constant time but Insertion is cheap no matter where in the list it
insertion elsewhere is costly. occurs.
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.
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.
14 | P a g e
System.out.print("Number of words in the string: " +
count_Words(str)+"\n");
}
15 | P a g e