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

Java

Some more Java questions
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java

Some more Java questions
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

Answer any ve questions:

(a) What is mutable string?

• A mutable string is a string object whose value can be changed after it is created. In Java, the
StringBuilder and StringBuffer classes represent mutable strings. This means
you can modify the contents of a StringBuilder or StringBuffer object without
creating a new object.
(b) What is the use of abstract class in Java?.

• Uses of abstract classes:

◦ To de ne common behavior for a group of related classes.


◦ To enforce a speci c structure or interface for subclasses.
◦ To provide partial implementation for common functionality.
(c) What is the base class of Error and Exception?

• The base class of both Error and Exception is Throwable.


(d) What is the use of 'this' keyword in Java?

• The this keyword in Java refers to the current object of the class. It is used to:
◦ Refer to the current object's instance variables.
◦ Invoke another constructor of the same class.
◦ Pass the current object as an argument to a method.
(e) What is a Copy Constructor?

• A copy constructor is a special constructor that creates a new object of the same class as the
current object, initializing the new object with the values of the current object. It is used to
create a deep copy of an object.
(f) What Java is called platform independent?

• Java is called platform-independent because Java bytecode, which is the intermediate code
generated by the Java compiler, can run on any platform that has a Java Virtual Machine
(JVM) installed. The JVM is responsible for translating the bytecode into machine code
speci c to the underlying operating system.
(g) How vector differs from a list?

• Vector:

◦ Thread-safe (synchronized).
◦ Slower than ArrayList due to synchronization overhead.
◦ Uses an array internally to store elements.
◦ Legacy class, consider using ArrayList for most use cases.
• List:


Not inherently thread-safe.

More ef cient than Vector for most operations.

Provides more exibility in terms of implementation.

Can be used with different implementations like ArrayList, LinkedList,
etc.
(h) What is the use of nally() method in Java?
fi
fi
fi
fl
fi
fi
fi
• The finally block is a block of code that is guaranteed to execute, regardless of whether
an exception is thrown or not. It is often used to release resources such as le handles or
database connections.1
2. (a) What is inheritance in Java? Explain different types of inheritance with example.

• Inheritance is a fundamental concept in object-oriented programming that allows a class to


inherit properties and behaviors from another1 class. This promotes code reusability and
establishes a hierarchical2 relationship between classes.

• Types of Inheritance in Java:

1. Single Inheritance: A class inherits from only one parent class.


Java

class Animal {

2. void eat() {
3. System.out.println("Animal eats");
4. } }
5.
6. class Dog
7. }
8.

Here, the Dog class inherits from the Animal class.


9. Multilevel Inheritance: A class inherits from another class, which itself inherits
from another class, forming a chain.
Java

class Grandparent { }

10. class Parent extends Grandparent { }


11. class Child extends Parent { }
12.

The Child class inherits from the Parent class, and the Parent class inherits
from the Grandparent class.
13. Hierarchical Inheritance: Multiple classes inherit from a single base class.
Java

class Animal { }

14. class Dog extends Animal {}


15. class Cat extends Animal {}
16.
fi
Both Dog and Cat inherit from the base class Animal.
17. Multiple Inheritance (Through Interfaces): A class can implement multiple
interfaces, achieving a form of multiple inheritance for behavior. Java doesn't
support multiple inheritance for classes directly, but it can be simulated using
interfaces.
Java

interface Flyable { void fly(); }

18. interface Swimmable { void swim(); }


19. class Bird implements Flyable {
20. // ...
21. }
22.

2. (b) Explain with the help of an example, how Java gets bene ted by using Interface.

• Interfaces de ne a contract or blueprint for classes that implement them. They specify
methods that the implementing classes must provide.

• Bene ts:

◦Code Reusability: Interfaces promote code reusability by de ning common


behavior for unrelated classes. For example, both a bird and a plane can y, even
though they are different entities.
◦ Flexibility: Interfaces allow for loose coupling between classes. An object that
implements an interface can be used interchangeably with other objects that
implement the same interface.
◦ Extensibility: It's easy to add new implementations to an interface without affecting
existing code.
• Example:
Java

interface Shape {

• double calculateArea();
• }

• class Circle implements Shape {
• // ...
• }

• class Rectangle implements Shape {
• // ...
• }
fi
fi
fi
fi
fl

Here, both Circle and Rectangle implement the Shape interface, even though they
represent different geometric shapes.
3. (a) How does String class differ from StringBuffer class?

Feature String StringBuffer


Mutabil Immutable (cannot be changed once Mutable (can be modi ed after creation)
ity
Perfor created)
Generally more ef cient for Less ef cient for frequent modi cations due
mance3 concatenation and manipulation due to to object creation overhead.
Thread immutability. Not thread-safe by default. Use
Immutable, hence inherently thread-safe.
Safety StringBuilder for thread-safe string
Memor Creates a new String object for each modi cations.
Modi es the existing object, reducing
y Usage modi cation. memory usage for frequent changes.

3. (b) What are Implicate and Explicit Casting? Explain with the help of example.

• Implicit Casting (Widening): This happens automatically when converting a value from a
smaller data type to a larger data type. No explicit cast operator is needed.
Java

int num = 10;

• long l = num; // Implicit casting from int to long


• Explicit Casting (Narrowing): This is required when converting a value from a larger data
type to a smaller one. It is done using the cast operator (target_type).
Java

double d = 3.14;

• int i = (int)d; // Explicit casting from double to int


(decimal part will be truncated)

4. (a) What is the difference between ‘error’ and ‘exception’?

• Error: Represents serious system-level errors that usually cannot be recovered from.
Examples include OutOfMemoryError, StackOverflowError,
VirtualMachineError.
fi
fi
fi
fi
fi
fi
fi
• Exception: Represents more general errors that can occur during program execution. These
can be handled using try-catch blocks. Examples include IOException,
ArithmeticException, SQLException.
4. (b) Illustrate ‘ArrayIndexOutOfBounds’ exception with an example.

Java

int[] arr = {1, 2, 3};


int i = arr[3]; // This will cause an
ArrayIndexOutOfBoundsException
This code attempts to access an element at index 3 in an array with only 3 elements (valid indices
are 0, 1, and 2). Since the valid range of indices is 0 to 2, this will throw an
ArrayIndexOutOfBoundsException.

4. (c) De ne an exception called “NotEqualException” that is thrown when a oat value is not
equal to 3.14. Write a program that uses that user-de ned exception.

Java

class NotEqualException extends Exception {


public NotEqualException(String message) {
super(message);
}
}

public class Example {


public static void main(String[] args) {
float value = 3.15;
try {
if (value != 3.14) {
throw new NotEqualException("Value is not
equal to 3.14");
}
} catch (NotEqualException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
This program de nes a custom exception NotEqualException. If the value of value is not
equal to 3.14, the NotEqualException is thrown and caught in the catch block.

5. (a) What is the difference between Method Overloading and Method Overriding?

• Method Overloading: Occurs within the same class when you have multiple methods with
the same name but different parameters (different number of parameters or different data
types of parameters).
fi
fi
fi
fl
• Method Overriding: Occurs when a subclass provides a speci c implementation for a
method that is already de ned in its superclass. The method in the subclass4 must have the
same name, return type, and parameters as the method in the superclass.5
5. (b) Explain Dynamic Method Dispatch with suitable example.

• Dynamic Method Dispatch is the process of determining which method to call at runtime.
When a method is called on an object, the JVM determines the actual method to execute
based on the object's actual class at runtime. This allows for polymorphism.
Java

class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Woof!");
}
}

public class Test {


public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound(); // Calls the Dog's makeSound()
method
}
}
In this example, even though the variable animal is of type Animal, it actually refers to a Dog
object. The makeSound()method executed at runtime will be the one de ned in the Dog class.

5. (c) Write a program in Java to access static variable and static method to explain ‘static’
keyword properly.

Java

class MyClass {
static int count;
static void displayCount() {
System.out.println("Count: " + count);
}

MyClass() {
count++;
}
fi
fi
fi
}

public class Main {


public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass.displayCount();
}
}
Explanation:

• Static Variable (count):

◦ Declared using the static keyword.


◦ Belongs to the class itself, not to any speci c object of the class.
◦ Only one copy of the static variable exists for the entire class, shared by all objects
of the class.
• Static Method (displayCount()):

◦ Declared using the static keyword.


◦ Can be accessed without creating an object of the class using the class name.
◦ Does not have access to instance variables of the class.
6. (a) What is multithreading?

• Multithreading is the ability of a program to execute multiple parts (called threads)


concurrently within a single process. This allows programs to perform multiple tasks
simultaneously, improving responsiveness and utilizing CPU resources more ef ciently.
6. (b) Explain the difference between creation of user thread by extending thread class and
implementing runnable interface with a suitable example.

• Extending Thread Class:

◦ A class directly extends the Thread class.


◦ Overrides the run() method to de ne the thread's behavior.
• Java

class MyThread extends Thread {


• public void run() {
• // Thread's execution code here
• }
• }

• Implementing Runnable Interface:

◦ A class implements the Runnable interface and overrides its run() method.
fi
fi
fi
◦ An object of this class is then passed to a Thread object to create and start the
thread.
• Java

class MyRunnable implements Runnable {


• public void run() {
• // Thread's execution code here
• }
• }

• // ...
• MyRunnable runnable = new MyRunnable();
• Thread thread = new Thread(runnable);
• thread.start();

• Differences:

◦ Inheritance: Extending Thread limits the class to inherit from only one class
(since Java doesn't support multiple inheritance for classes). Implementing
Runnable allows a class to inherit from another class while still having
multithreading capabilities.
◦ Flexibility: The Runnable interface provides more exibility as it decouples the
thread execution logic from the class hierarchy.
6. (c) What is thread synchronization? How it is achieved in Java?

• Thread Synchronization is a mechanism to control access to shared resources (e.g.,


variables, objects) by multiple threads simultaneously. This prevents data corruption and
ensures that threads execute in a predictable and safe manner.

• Achieving Thread Synchronization in Java:

◦ synchronized keyword: This keyword can be used to synchronize access to a


block of code or a method. Only one thread can execute a synchronized block or
method at a time.
• Java

public synchronized void myMethod() {


• // ... code that accesses shared resources ...
• }

◦ wait() and notify() methods: These methods are used to pause and resume
threads that are waiting for a condition to be met. The wait() method causes a
thread to wait until another thread noti es it using the notify() method.
fi
fl
7. (a) Explain the life-cycle of an Applet.

1. Initialization:
◦ The browser downloads the applet's bytecode from the server.
◦ The JVM creates an instance of the applet class.
◦ The applet's constructor is called to initialize the applet object.
◦ The init() method is called to perform any necessary initializations.
2. Starting:

◦ The start() method is called when the applet is rst loaded and whenever the
applet is returned to the foreground.
◦ The applet begins its execution.
3. Painting:

◦ The paint() method is called to draw the applet's graphical components on the
screen.
◦ This method is typically called whenever the applet needs to be redrawn.
4. Stopping:

◦ The stop() method is called when the browser leaves the applet's page or
minimizes the browser window.
◦ The applet should release any resources it is using (e.g., stop any animations).
5. Destroying:


The destroy() method is called when the applet is being unloaded from
memory.
◦ The applet should perform any necessary cleanup tasks (e.g., close les, release
network connections).
7. (b) List various attributes of Applet tag used in HTML.

• code: Speci es the name of the Java class that implements the applet.
• width: Sets the width of the applet in pixels.
• height: Sets the height of the applet in pixels.
• align: Speci es the alignment of the applet within the page.
• alt: Provides alternative text for browsers that do not support Java.
• archive: Speci es the location of the JAR le containing the applet's class les.
7. (c) Write a Java program that uses the drawPolygon () method of Graphics class to draw a
triangle with endpoints (28, 35); (78, 82) and (43, 43)

Java

import java.awt.*;
import java.applet.*;

public class DrawTriangle extends Applet {


public void paint(Graphics g) {
int x[] = {28, 78, 43};
int y[] = {35, 82, 43};
g.drawPolygon(x, y, 3);
fi
fi
fi
fi
fi
fi
fi
}
}
8. (a) What are the different access speci ers available in Java? How a protected access
speci er differs from private access speci er?

• Access Speci ers:

◦ Public: Accessible from anywhere (any class, any package).


◦ Protected: Accessible within the same class, subclasses, and classes in the same
package.
◦ Private: Accessible only within the same class.
◦ Default (no modi er): Accessible within the same package.
• Difference between Protected and Private:


Private: Members declared as private are accessible only within the same class.
They are not accessible from outside the class, including subclasses or other classes
in the same package.
◦ Protected: Members declared as protected are accessible within the same class,
subclasses, and classes in the same package. They are not accessible to classes in
other packages.
8. (b) How an array is declared in Java? Write a program in Java to sort an array in
ascending order and display it.

Declaration:

Java

data_type[] array_name;
// Example: int[] numbers;
Program to sort an array in ascending order using bubble sort:

Java

public class ArraySort {


public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 5, 6};

// Bubble Sort
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - i - 1; j++)
{
if (numbers[j] > numbers[j + 1]) {
// Swap elements
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
fi
fi
fi
fi
fi
// Display sorted array
System.out.print("Sorted array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}

You might also like