Unit 3
1. Write a short note on exception handling in java.
1) Exception handling in Java is a mechanism to handling handle runtime errors, ensuring normal
program flow.
2)Types of Exception
* Checked Exception: Must be handled at compile time (e.g. IOException).
* Unchecked Exception: Occurs at runtime (e.g. NullPointerException).
* Errors: Serious issues that should be caught (e.g. OutOfMemoryError).
3) Keywords used:
* try: Defines a block where exceptions might occur.
* catch: Handles exceptions thrown in the try block.
4) Example:
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
5) Java allows the creation of user-defined exception by extending the Exception class.
2. SN on built-in exception in java with eg.
1)In Java, built-in exceptions are predefined exceptions that are part of the Java Exception Handling
mechanism.
2) These exceptions are part of the java lang package.
3) They are categorized into two types:
i. Checked (or Force) Exceptions -
These are exceptions that must be handled using try-catch or declared using throws.
Examples:
* IOException - Occurs during input/output operations.
* SQL Exception - Related to database operations.
* FileNotFoundException - Related to when a file is not found.
ii. Unchecked Exceptions (Runtime Exceptions) -
These occur at runtime and do not need to be explicitly handled.
Examples:
* NullPointerException - When accessing a null object.
* ArrayIndexOutOfBoundsException - When an array index is out of bounds.
* ArithmeticException - When dividing by zero.
3. Difference b/w throw & throws.
4. What is thread and explain the concept of multithreading
"A thread is the smallest unit of execution within a process. It runs independently and performs a
specific task. Multithreading is a technique that allows multiple threads to run concurrently
within a single process. This offers several advantages:
It improves performance by utilizing the CPU more efficiently.
It reduces overall execution time by running tasks in parallel.
Java provides various methods to control threads, such as start(), run(), sleep(), and
join(). Multithreading is widely used in real-world applications like gaming, web servers, and
GUI applications to enhance responsiveness and performance."
5. What are the difference ways of creating thread in java.
In Java, you can create a new thread by either extending the Thread class or implementing the Runnable
interface.
1) Extending Thread class:
* Create a new class that inherits from the Thread class.
* Override the run() method within your new class to define the thread's functionality.
* Instantiate an object of your new class and call the start() method to begin the thread execution.
2) Implementing Runnable interface:
* Create a class that implements the Runnable interface.
* Implement the run() method within your class to define the thread's task.
* Create a Thread object, passing an instance of your Runnable class to its constructor.
* Call the start() method on the Thread object to begin the thread execution.
6. Explain the life cycle of thread.
The life cycle of a thread in Java describes the various states a thread can transition
through from its creation to its termination. Here's a breakdown:
1
1. New: When a Thread object is created, it's in the "new" state. It exists, but hasn't started
executing its code yet.
2. Runnable: Calling start() puts the thread into the "runnable" state. It's now eligible to
run, but the thread scheduler decides when it actually gets CPU time.
3. Running: The thread scheduler has selected the thread, and it's actively executing its
run() method. It remains in this state until it yields control or its time slice is up.
4. Waiting/Blocked: The thread temporarily pauses execution. This happens when it's
waiting for a resource, another thread, or a timer (e.g., wait(), sleep(), synchronized
blocks). It will return to the runnable state when the condition is met.
5. Terminated (Dead): The thread's run() method finishes, or an uncaught exception
occurs. The thread can no longer be restarted and releases its resources.
Visual Representation:
It's helpful to visualize the thread life cycle with a state diagram:
New --> Runnable --> Running --> Waiting/Blocked --> Runnable --> Running
--> Terminated
^ |
|________________|
7. SN on Synchronisation.Explain wait(), notify(), notify all method.
Synchronization: Ensures that only one thread at a time can access a shared resource,
preventing data corruption and race conditions. Achieved using synchronized blocks or
methods, which acquire a lock on an object.
wait(): A thread calls wait() within a synchronized block to release the object's lock and
enter a waiting state. It remains paused until another thread calls notify() or notifyAll()
on the same object.
notify(): Wakes up a single thread that is waiting on the object's lock. If multiple threads
are waiting, the JVM chooses one arbitrarily.
notifyAll(): Wakes up all threads waiting on the object's lock. They compete to reacquire
the lock. Using notifyAll() is generally safer than notify().
Key Requirement: All three methods (wait(), notify(), notifyAll()) must be called
from within a synchronized block or method that holds the lock on the object.
8. What is package?write steps to create a package in java.
A namespace in Java that groups related classes and interfaces, providing organization and
preventing naming conflicts.
Steps to Create a Package:
1. Choose a Unique Name: Select a descriptive, lowercase name, ideally using reverse
domain name notation (e.g., com.yourcompany.project). This ensures uniqueness
across projects.
2. Create Directory Structure: Establish a directory structure that mirrors the package
name. For com.yourcompany.project, create directories com/yourcompany/project.
3. Place Java Source Files: Put your .java files within the corresponding directory. Each
file in the package should reside in this structure.
4. Add package Declaration: At the very top of each .java file, add the package keyword
followed by the package name, ending with a semicolon (e.g., package
com.yourcompany.project;). This tells the compiler which package the class belongs
to.
5. Compile with -d Option: Use the javac command with the -d option to specify the
output directory for compiled .class files. For example, javac -d .
com/yourcompany/project/MyClass.java compiles MyClass.java and places the
.class file in the correct directory structure relative to the current directory (represented
by .).
6. Import or Use Fully Qualified Names: To use classes from your package in other Java
files, either use the import keyword (e.g., import
com.yourcompany.project.MyClass;) or refer to the class using its fully qualified
name (e.g., com.yourcompany.project.MyClass). The import statement lets you use
the class name directly without the package prefix.
9. Explain array & string class with Ex.
Arrays in Java:
An array is a data structure that stores a fixed-size, sequential collection of elements of
the same type. It's like a container holding multiple values of the same kind.
Characteristics:
Fixed Size: Once an array is created, its size cannot be changed.
Homogeneous: All elements in an array must be of the same data type.
Indexed: Elements are accessed using zero-based indices (0, 1, 2, ...).
Example:
Java
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
System.out.println("First element: " + numbers[0]);
System.out.println("Third element: " + numbers[2]);
System.out.println("All elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
}
}
String Class in Java:
The String class represents character strings. Strings are immutable, meaning their
values cannot be changed after they are created.
Characteristics:
Immutable: Once a String object is created, its content cannot be modified.
Object: String is a class, so string literals are objects.
Methods: The String class provides numerous methods for string manipulation.
Example:
Java
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = str1 + " " + str2;
System.out.println("Concatenated string: " + str3);
System.out.println("Length of str1: " + str1.length());
System.out.println("Uppercase str2: " + str2.toUpperCase());
System.out.println("Substring of str3: " + str3.substring(0, 5));
System.out.println("Does str1 equals Hello? "+
str1.equals("Hello"));
}
}