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

Java Preparation Unit - 4-1

Uploaded by

Vighnesh Pote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Preparation Unit - 4-1

Uploaded by

Vighnesh Pote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Java Preparation

Unit-4
Exception Handling AND Multithreading
2 Marks
1. Define error. List types of error.
Ans) An error in programming refers to any mistake in the code that prevents it from
executing successfully.
Types of errors in Java include:
• Compile-time errors (Syntax errors): These occur due to violations of the rules
of the programming language, such as missing semicolons, mismatched
parentheses, or incorrect variable names. These errors are detected by the
compiler during the compilation phase and must be fixed before the program can
be executed.
• Runtime errors: These occur during program execution and may lead to
abnormal termination. Runtime errors include exceptions such as
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
and others. These errors occur when the program is running and encountering
unexpected conditions that it cannot handle.

2. Write the syntax of cry catch finally block.


Ans) Syntax:
try {
// Code that may throw an exception
}
catch (ExceptionType1 e1)
{
// Handle ExceptionType1
}
catch (ExceptionType2 e2)
{
// Handle ExceptionType2
}
finally
{
// Code that will always execute regardless of exceptions
}
3. Give a syntax of following thread method
i) Notify ( )
ii) Sleep ( )
Ans) i) notify()
The notify() method of thread class is used to wake up a single thread. This method gives
the notification for only one thread which is waiting for a particular object.
Syntax: public final void notify()

ii) sleep()
Sleep() causes the current thread to suspend execution for a specified period.
Syntax: public static void sleep(long milliseconds)

4. Define thread. Mention 2 ways to create thread.


Ans) 1. Thread is a smallest unit of executable code or a single task is also called as thread.
2. Each tread has its own local variable, program counter and lifetime.
3. A thread is similar to program that has a single flow of control.

There are two ways to create threads in java:


1. By extending thread class
Syntax: -
class Mythread extends Thread
{
-----
}

2. Implementing the Runnable Interface


Syntax:
class MyThread implements Runnable
{
public void run()
{
------
}
4 Marks
1. Define exception. State Built-in exceptions.
Ans) Exception:
An exception in Java represents an abnormal condition that disrupts the normal flow of
program execution.

Built-in exceptions in Java include:

1. ArithmeticException: Occurs when an arithmetic operation fails, such as division by


zero.

2. ArrayIndexOutOfBoundsException: Occurs when attempting to access an array


element at an invalid index.

3. ClassNotFoundException: Occurs when trying to load a class through its string


name using Class.forName(), but the class is not found in the classpath.

4. FileNotFoundException: Occurs when attempting to access a file that does not exist.

5. IOException: General I/O exception that occurs during input or output operations.

6. NullPointerException: Occurs when trying to access or modify an object reference


that is null.

7. NumberFormatException: Occurs when converting a string into a numerical format,


but the string does not contain a valid number.

8. StringIndexOutOfBoundsException: Occurs when attempting to access a character


at an invalid index in a string.

9. OutOfMemoryError: Occurs when the Java Virtual Machine (JVM) runs out of
memory to allocate new objects.
10. SecurityException: Occurs when an applet tries to perform an operation not allowed
by the security settings.

11. StackOverflowError: Occurs when the call stack exceeds its maximum size due to
infinite recursion or excessive method calls.

2. Explain life cycle of thread with suitable Diagram.


Ans) Diagram:

1. New:
• A thread enters the new state when it is instantiated but has not yet started its
execution.
• At this stage, the thread is considered alive, but it has not been started yet.
2. Runnable:
• A thread enters the runnable state when the start() method is called on it.
• In this state, the thread is ready to run, but the scheduler has not yet selected it to
be executed.
• The thread scheduler selects threads from the runnable pool and moves them to
the running state based on priority and other factors.
3. Running:
• A thread enters the running state when the scheduler selects it from the runnable
pool for execution.
• In this state, the thread is actively executing its task or code.
• The thread remains in the running state until it completes its task, is preempted
by a higher-priority thread, or voluntarily yields its execution by calling yield()
or sleep() methods.
4. Blocked/Waiting:
• A thread enters the blocked or waiting state when it is temporarily inactive or
waiting for a certain condition to be fulfilled.
• The thread remains in this state until the condition it is waiting for is satisfied, at
which point it moves back to the runnable state.
• Some methods are:
✓ suspend(): Suspends the execution of the current thread until it is resumed
by calling resume()
✓ sleep(long milliseconds): Pauses the execution of the current thread for the
specified number of milliseconds before resuming execution.
✓ wait(): Causes the current thread to wait until another thread invokes the
notify.
✓ resume(): Resumes the execution of a suspended thread that was previously
suspended using suspend().
✓ notify(): Wakes up a single thread that is waiting on the same object by
invoking the wait() method.
5. Terminated:
• A thread enters the terminated state when it completes its task or is explicitly
terminated by calling the stop() method (not recommended) or when the run()
method exits.
• Once a thread is terminated, it cannot be restarted or moved to any other state.

3. Explain a ways to create a threads in java.


Ans) There are two main ways to create threads in Java:
1. Extending the Thread class:
• Create a subclass of the Thread class and override the run() method with
the code that the thread will execute.
• Instantiate an object of your subclass and call its start() method to begin
execution of the thread.
Example:
class MyThread extends Thread {
public void run() {
// Thread execution code
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}

2. Implementing the Runnable interface:


• Create a class that implements the Runnable interface and define the
thread's task in the run() method.
• Instantiate an object of your class and pass it as a parameter to a Thread
object's constructor.
• Call the start() method on the Thread object to start execution of the
thread.
Example:
class MyRunnable implements Runnable {
public void run() {
// Thread execution code
}
}

public class Main {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}

4. Explain exception handling mechanism w.r.t. try, catch, throw and finally.
Ans) ❖ Try:
• The try block encloses the code that might throw an exception.
• It is followed by one or more catch blocks or a finally block.
• The code inside the try block is monitored for exceptions.
Syntax:
try {
// Code that might throw an exception
// This block is monitored for exceptions
}

❖ Catch:
• A catch block follows a try block and is used to handle specific types of
exceptions.
• It catches the exception thrown by the try block and executes the corresponding
code to handle the exception.
• A single try block can have multiple catch blocks to handle different types of
exceptions.
Syntax:
catch (ExceptionType exceptionVariable) {
// Handle the exception
// Code to execute when the specified exception occurs
}

❖ Throw:
• The throw keyword is used to explicitly throw an exception within a method or
block of code.
• It allows you to create and throw custom exceptions or propagate existing ones.
Syntax:
throw new ExceptionType("Error message");

❖ Finally:
• The finally block follows the try and catch blocks (if any).
• It contains code that is always executed, regardless of whether an exception is
thrown or caught.
• The finally block is often used to perform cleanup tasks, such as closing resources
(e.g., files, database connections) or releasing locks.
Syntax:
finally {
// Cleanup code or code that always needs to be executed
}
6 Marks
1. Define thread priority? Write default priority values and the methods to set and
change them.
Ans) Thread Priority:
Thread priority in Java determines the importance of a thread relative to other threads.
Threads with higher priority are given preference in accessing the CPU resources over
threads with lower priority. However, it's important to note that thread priority is only a
suggestion to the thread scheduler and may not be strictly followed by all JVM
implementations.
Default Priority Values:
• The default priority value for a thread is 5.
• Thread priorities range from 1 to 10, where 1 is the lowest priority and 10 is the
highest priority.
Methods to Set and Change Thread Priority:
1. getPriority():
• This method is used to retrieve the current priority of the thread.
• Syntax: int getPriority()
2. setPriority(int priority):
• This method is used to set the priority of the thread.
• Syntax: void setPriority(int priority)
• Note: The priority parameter must be an integer value between 1 and 10
inclusive.
Example:
public class PriorityExample extends Thread {
public void run()
{
System.out.println("Thread name: " + Thread.currentThread().getName() + ",
Priority: " + Thread.currentThread().getPriority());
}

public static void main(String[] args) {


PriorityExample thread1 = new PriorityExample();
PriorityExample thread2 = new PriorityExample();

// Setting priority for thread1


thread1.setPriority(7); // Higher priority

// Default priority for thread2

// Starting the threads


thread1.start();
thread2.start();
}
}
2. i)Explain Errors and its types in detail.
ii)Explain thread methods to get and set priority.
Ans) i) Errors and its Types:
An error in programming refers to any mistake in the code that prevents it from
executing successfully.
Errors in Java can be broadly categorized into two types: compile-time errors and
runtime errors.
1. Compile-time Errors:
• Compile-time errors occur during the compilation of the code. These errors
prevent the code from being compiled into bytecode and are detected by the
compiler.
• Examples of compile-time errors include syntax errors, type errors, and missing
semicolons.
Example:
public class Example {
public static void main(String[] args) {
int x = 10
System.out.println(x); // Missing semicolon
}
}
2. Runtime Errors:
• Runtime errors occur during the execution of the code. These errors cause the
program to terminate abnormally and are typically caused by invalid input or
unexpected conditions.
• Examples of runtime errors include division by zero, array index out of bounds,
and null pointer dereference.
Example:
public class Example {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // ArrayIndexOutOfBoundsException
}
}

ii) Thread Methods to Get and Set Priority:


• In Java, threads have priorities that help the thread scheduler determine the order
in which threads should be executed.
• Thread priority is represented by an integer value ranging from 1 (lowest
priority) to 10 (highest priority).
• The default priority of a thread is inherited from its parent thread.

The following methods are used to get and set the priority of a thread:
1. getPriority() Method:
• This method returns the priority of the thread as an integer value.
• Syntax:
public int getPriority()

2. setPriority(int newPriority) Method:


• This method sets the priority of the thread to the specified integer value.
• Syntax:
public void setPriority(int newPriority)
Example:
public class PriorityExample
{
public static void main(String[] args)
{
Thread thread = Thread.currentThread();

System.out.println("Default priority of main thread: " + thread.getPriority());

thread.setPriority(Thread.MAX_PRIORITY);

System.out.println("Updated priority of main thread: " + thread.getPriority());


}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy