JAVA Unit 3.Model questions
JAVA Unit 3.Model questions
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).
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.
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
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.");
}
}
}
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.");
}
}
}
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);
}
}
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.
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.
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());
}
t1.start();
t2.start();
}
}
13. Explain importance of thread synchronization.