Intoduction to Java_Important Questions
Intoduction to Java_Important Questions
// Default constructor
public Person() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name; // 'this' differentiates the instance variable from the
parameter
this.age = age;
}
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
In this program, changing num inside modifyValues does not affect number in main because
primitives are passed by value. However, the object person is passed as a copy of its reference, so
modifying its field changes the object itself.
5. Write a program to perform Stack operations using proper class and Methods.
Answer:
Below is a simple Java program that implements a stack using an array. The program provides
methods for push, pop, peek, and checking if the stack is empty.
public class StackOperations {
private int maxSize;
private int[] stackArray;
private int top;
void display() {
System.out.println("Name: " + name);
}
}
void displayStudent() {
System.out.println("Student ID: " + studentId);
}
}
Animal() {
System.out.println("Animal Constructor");
}
}
Dog() {
// Calls the parent class (Animal) constructor
super();
System.out.println("Dog Constructor");
}
void display() {
// Accessing the subclass's type and the superclass's type using super
System.out.println("Type from Dog: " + type);
System.out.println("Type from Animal: " + super.type);
}
}
// Concrete method
void display() {
System.out.println("This is a shape.");
}
}
3. Define an exception. What are the key terms used in exception handling?
Explain.
Answer:
An exception is an event that occurs during the execution of a program that disrupts the normal flow
of instructions. Exceptions are objects that represent errors or unexpected events that may occur
during runtime.
Key terms in exception handling include:
• try:
A block of code where exceptions might occur. Code within the try block is executed until
an exception is thrown.
• catch:
A block that catches and handles exceptions thrown in the try block. Multiple catch blocks
can be used to handle different types of exceptions.
• finally:
A block that always executes after the try and catch blocks, regardless of whether an
exception was thrown. It is typically used for cleanup operations.
• throw:
A keyword used to explicitly throw an exception from a method or block of code.
• throws:
Used in a method signature to declare that the method might throw one or more exceptions,
thereby shifting the responsibility of handling those exceptions to the caller.
These constructs provide a structured way to detect and handle errors, ensuring the program can
either recover or terminate gracefully.
5. How do you create your own exception class? Explain with a program.
Answer:
You can create your own exception class by extending either the Exception class (for a checked
exception) or the RuntimeException class (for an unchecked exception). Here’s an example of a
custom exception:
// Custom Exception class extending Exception (checked exception)
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
1. What do you mean by a thread? Explain the different ways of creating threads.
Answer:
A thread in Java represents a single sequential flow of control within a program. Threads allow
concurrent execution of two or more parts of a program to maximize the use of CPU. In Java, a
thread is an instance of the class Thread (or an instance of a class that implements the Runnable
interface) that can run concurrently with other threads.
There are several ways to create threads in Java:
1. Extending the Thread Class:
You can create a new thread by subclassing the Thread class and overriding its run()
method. When you create an instance of your subclass and call its start() method, a new
thread of execution begins.
class MyThread extends Thread {
public void run() {
System.out.println("Thread running by extending Thread class.");
}
}
t1.start();
t2.start();
}
}
In this example, the deposit method is synchronized, so even if multiple threads call it
simultaneously, each deposit operation is performed completely before another begins, ensuring the
account balance remains consistent.
Producer(SharedResource resource) {
this.resource = resource;
}
Consumer(SharedResource resource) {
this.resource = resource;
}
producerThread.start();
consumerThread.start();
}
}
In this example, the SharedResource class uses wait() and notify() to coordinate between the
producer (which puts data) and the consumer (which retrieves data). The producer waits if the
resource is full (i.e., available is true), and the consumer waits if there is no data (i.e., available
is false).
// Auto-boxing in expressions
Integer a = 5;
Integer b = 10;
// The following expression unboxes a and b, performs addition, and then
auto-boxes the result
Integer sum = a + b;
System.out.println("Sum: " + sum);
}
}
In this example, the conversion between int and Integer happens automatically by the compiler.
When the expression a + b is evaluated, the values are unboxed to perform arithmetic and then the
result is boxed back into an Integer object.