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

JAVA Unit 3.Model questions

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

JAVA Unit 3.Model questions

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

1.Explain types of Errors.

1. Syntax Errors
 Explanation: These occur when the code doesn't follow the Java
language rules, leading to compile-time issues.
 Example: Missing semicolon, incorrect method signature, or unclosed
brackets.
2. Runtime Errors
 Explanation: These occur while the program is running, typically due to
invalid operations like dividing by zero or accessing invalid memory
locations.
 Example: NullPointerException, ArrayIndexOutOfBoundsException.
3. Logical Errors
 Explanation: The program runs without crashing but produces incorrect
results due to flawed logic or algorithms.
 Example: Incorrect calculations or faulty conditional statements.
4. Exceptions
 Explanation: Special runtime errors in Java that can be caught and
handled using try-catch blocks. They can be checked (required to be
handled at compile time) or unchecked (runtime exceptions).

2. Explain use of try-catch blocks.

The try-catch block in Java is used to handle exceptions, which are runtime
errors that may occur during the execution of a program. The purpose of using
try-catch is to gracefully handle errors instead of letting the program crash.
Here's an explanation of how try-catch blocks work:
Syntax: try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}

How it Works:
1. try block: You write the code that might throw an exception inside the try
block. The program will attempt to execute this code.
2. catch block: If an exception occurs inside the try block, the control is
passed to the corresponding catch block. The catch block contains the
code that handles the exception. The type of exception that can be caught
is specified in the parentheses after catch.

3.Explain types of exception classes.

1.Checked Exceptions
 Explanation: Exceptions that must be either caught or declared in the
method signature using the throws keyword. These are checked at
compile time.
 Common Classes:
o IOException
o SQLException
o ClassNotFoundException
o FileNotFoundException
2. Unchecked Exceptions (Runtime Exceptions)
 Explanation: Exceptions that do not need to be caught or declared. They
are checked at runtime and usually occur due to programming errors.
 Common Classes:

o ArithmeticException
o NullPointerException
o ArrayIndexOutOfBoundsException
o IllegalArgumentException
o ClassCastException
3. Errors
 Explanation: Serious problems that are beyond the application's control.
These are not exceptions and are usually not meant to be caught.
 Common Classes:
o OutOfMemoryError
o StackOverflowError
o VirtualMachineError

4.What is the importance of handling an exception?

Handling exceptions is important because it:


1. Prevents Program Crashes: It avoids unexpected terminations by
managing errors.
2. Improves User Experience: Provides meaningful feedback to users
instead of abrupt errors.
3. Enables Fault Tolerance: Allows the program to continue running
despite certain failures.
4. Facilitates Debugging: Provides useful error details for troubleshooting.
5. Improves Code Readability: Separates error-handling logic from
business logic.
6. Manages Resources: Ensures resources like files or connections are
properly closed.
7. Enhances Security: Catches potential threats like invalid input or
unauthorized access.
8. Ensures Compliance: Helps meet industry standards and best practices
for error handling.

5.Write a program to demonstrate use of try-catch blocks.

public class TryCatchExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
}
}

6. Explain use of finally block and its combinations in exception handling.

The finally block in Java is used to guarantee that certain code is always
executed, regardless of whether an exception occurs or not. It is typically used
for cleanup tasks like closing resources (files, database connections, etc.) to
ensure they are released properly.
Key Points about finally Block:
 Always Executes: The finally block is executed after the try block and
any catch block, whether an exception is thrown or not.
 Even After Return Statements: The finally block is executed even if a
return statement is encountered in the try or catch blocks, ensuring that
critical code runs.
Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 2; // No exception
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
System.out.println("This will always execute, whether exception occurs
or not.");
}
}
}

7. Specify the use of keyword throws in exception handling.

The throws keyword in Java is used to declare that a method may throw one or
more exceptions during its execution. It is placed in the method signature to
indicate that the method does not handle the exceptions but instead delegates
the responsibility to the calling method.

Example :
public class ThrowsExample {
// Method that throws an exception
public static void readFile() throws IOException {
FileReader file = new FileReader("file.txt"); // Might throw IOException
}
public static void main(String[] args) {
try {
readFile(); // The caller must handle IOException
} catch (IOException e) {
System.out.println("File not found or unable to read.");
}
}
}

8.How to handle user-defined exceptions using keyword throws? Also write


a program to justify your answer.

n Java, user-defined exceptions can be handled using the throws keyword in the
same way as built-in exceptions. You create a custom exception by extending
the Exception class (or one of its subclasses), and then you declare that your
method throws this custom exception using the throws keyword.

Example:
// Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class UserDefinedExceptionExample {

// Method that throws a user-defined exception


public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}

public static void main(String[] args) {


try {
checkAge(15); // This will throw InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

9.Write a short note on thread lifecycle.

The thread lifecycle in Java defines the various states a thread goes through
from its creation to its completion. A thread can be in one of the following
states:
1. New: The thread is created but not yet started.
2. Runnable: The thread is ready to run and waiting for CPU time.
3. Blocked: The thread is waiting to acquire a lock held by another thread.
4. Waiting: The thread is waiting indefinitely for another thread's action
(e.g., wait()).
5. Timed Waiting: The thread is waiting for a specific time (e.g.,
sleep(1000)).
6. Terminated: The thread has completed or stopped.
These states define how a thread is managed and how it transitions during its
lifecycle.

10.Explain following thread lifecycle methods:


a) start()
b) sleep()
c) suspend()
d) stop()

1. start():
o Purpose: Begins the execution of a thread. It invokes the run()
method of the thread in a separate call stack.
2. sleep(long millis):
o Purpose: Pauses the current thread for the specified time (in
milliseconds), allowing other threads to execute during this time.
3. suspend():
o Purpose: Suspends the thread's execution temporarily. It is unsafe
and deprecated due to the risk of causing deadlocks and
inconsistent states.
4. stop():
o Purpose: Terminates a thread forcefully. It is also deprecated due
to the risk of leaving shared resources in an inconsistent state.
11. Explain 2 ways to create thread. Also write a program on any one way
of creating thread.

Two Ways to Create a Thread in Java:


1. By Extending the Thread Class:
o A new thread is created by extending the Thread class and
overriding its run() method. Then, you can create an object of the
new class and call its start() method.
2. By Implementing the Runnable Interface:
o A new thread is created by implementing the Runnable interface
and overriding its run() method. Then, you pass the Runnable
object to a Thread object and call the start() method on the Thread
object.

Program to Create a Thread by Extending the Thread Class:


// Extending Thread class
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running.");
}
}

public class ThreadExample {


public static void main(String[] args) {
// Creating an instance of MyThread and starting it
MyThread t = new MyThread();
t.start(); // Calls the run() method in a separate thread
}}
12. Explain setPriority() method to set the priority of thread.

The setPriority() method is used to set the priority of a thread. It determines the
importance of a thread relative to other threads in the system. The thread with a
higher priority is more likely to be scheduled before a thread with a lower
priority, though this depends on the thread scheduler.
Example:
public class ThreadPriorityExample extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " with priority " +
Thread.currentThread().getPriority());
}

public static void main(String[] args) {


ThreadPriorityExample t1 = new ThreadPriorityExample();
ThreadPriorityExample t2 = new ThreadPriorityExample();

// Setting thread priorities


t1.setPriority(Thread.MAX_PRIORITY); // Highest priority
t2.setPriority(Thread.MIN_PRIORITY); // Lowest priority

t1.start();
t2.start();
}
}
13. Explain importance of thread synchronization.

Thread synchronization is essential in multi-threaded programming to ensure


that multiple threads can safely access shared resources without causing data
inconsistency or corruption. Without synchronization, if two or more threads try
to modify shared data at the same time, it can lead to unpredictable results and
errors.
Why Synchronization is Important:
1. Avoid Data Corruption: Ensures that only one thread can access the
shared resource at a time.
2. Prevent Race Conditions: A race condition occurs when two threads try
to update shared data simultaneously, leading to incorrect results.
3. Maintain Data Integrity: Guarantees that the operations on shared
resources are done in a controlled manner.

You might also like