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

MY NOTES

University Notes
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)
11 views

MY NOTES

University Notes
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/ 35

UNIT III: Exception Handling and Stream Files

1. Mark Questions (20 Questions)

1. Define exception handling.


It is the process of managing errors during program
execution.
2. What is an exception in programming?
An exception is an error that occurs during runtime.
3. State the purpose of the try block in exception handling.
It is used to write code that might cause an exception.
4. What is the role of the catch block?
It handles the exception if it occurs.
5. Name the three keywords commonly used in exception
handling.
try, catch, and finally.
6. What does the finally block do in exception handling?
It executes code after the try block, regardless of an
exception.
7. Differentiate between throw and throws.
throw is used to explicitly throw an exception; throws
declares exceptions a method might throw.
8. Can the finally block be omitted in exception handling?
Yes, it is optional.
9. What is a runtime exception?
It is an exception that occurs during program execution.
10. Give an example of a built-in exception in Java.
NullPointerException.
11. What happens if an exception is not handled in a
program?
The program crashes.
12. Define a checked exception.
An exception checked by the compiler.
13. What is an unchecked exception?
An exception not checked by the compiler.
14. State the syntax of the throw statement.
throw new ExceptionType();
15. Can multiple catch blocks be used with one try block?
Yes.
16. What is the default exception handler in Java?
The Java runtime environment.
17. Why is it important to handle exceptions?
To prevent program crashes and handle errors gracefully.
18. Can a try block exist without a catch block?
Yes, but it must have a finally block.
19. What does throws keyword specify in a method
declaration?
It declares exceptions that a method might throw.
20. Can we create custom exceptions?
Yes, by extending the Exception class.

3 Marks Questions (10 Questions)

1. Explain the difference between throw and throws


keywords with examples.

o throw: Used to explicitly throw an exception (e.g.,


throw new Exception();).

o throws: Used in method declarations to specify


exceptions (e.g., void method() throws Exception {}).

2. What is the purpose of the finally block, and when is it


executed?

o The finally block is for cleanup code.

o It is executed after try and catch, no matter what.

3. Describe the syntax and use of multiple catch blocks.

o Syntax:

java

Copy code

try {

// risky code
} catch (ExceptionType1 e) {

// handle type 1

} catch (ExceptionType2 e) {

// handle type 2

o Use: To handle different types of exceptions in one


try block.

4. Differentiate between checked and unchecked


exceptions with examples.

o Checked: Checked at compile time (e.g.,


IOException).

o Unchecked: Occur at runtime (e.g.,


NullPointerException).

5. Explain the structure of exception handling in Java with


the help of a simple example.

o Structure: try, catch, finally.

o Example:

java

Copy code

try {
int a = 5 / 0;

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero.");

} finally {

System.out.println("Execution complete.");

6. Discuss the importance of handling exceptions in


software development.

o Ensures program stability.

o Helps in graceful error recovery.

o Improves user experience.

7. Explain what happens when an exception is thrown but


not caught in a program.

o The program crashes, and the default exception


handler prints an error.

8. Describe how exceptions are propagated in a program.

o Exceptions move up the call stack until caught or


the program terminates.

9. What are custom exceptions, and how can they be


created in Java?
o Custom exceptions are user-defined exceptions.

o Created by extending the Exception class:

java

Copy code

class MyException extends Exception {

MyException(String message) {

super(message);

10. Explain how the try-catch-finally mechanism works


in exception handling.

o try: Executes risky code.

o catch: Handles the exception if thrown.

o finally: Always runs for cleanup actions.

10 Marks Questions (5 Questions)

Explain the hierarchy of exceptions in Java with examples for


different types.

• Hierarchy:
o Throwable: Root class for all exceptions.

▪ Error: Represents serious issues (e.g.,


OutOfMemoryError).

▪ Exception: Represents application errors.

▪ Checked Exceptions: (e.g., IOException,


SQLException).

▪ Unchecked Exceptions: (e.g.,


ArithmeticException,
NullPointerException).

• Example:

java

Copy code

try {

String str = null;

System.out.println(str.length()); // NullPointerException

} catch (NullPointerException e) {

System.out.println("Handled NullPointerException.");

Describe the steps for exception handling in Java with an


example using try, catch, throw, throws, and finally.
• Steps:

o Use try to wrap risky code.

o Use catch to handle exceptions.

o Use throw to explicitly throw exceptions.

o Use throws to declare exceptions in method


signatures.

o Use finally for cleanup code.

• Example:

java

Copy code

public class ExceptionExample {

void riskyMethod() throws ArithmeticException {

throw new ArithmeticException("Division by zero!");

public static void main(String[] args) {

try {

ExceptionExample obj = new ExceptionExample();

obj.riskyMethod();

} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());

} finally {

System.out.println("Cleanup complete.");

How are custom exceptions created in Java? Write a


program to demonstrate their creation and use.

• Steps:

1. Extend the Exception class.

2. Add constructors to pass custom messages.

3. Use try-catch to handle the exception.

• Example:

java

Copy code

class CustomException extends Exception {

CustomException(String message) {

super(message);

}
}

public class Main {

public static void main(String[] args) {

try {

validateAge(15);

} catch (CustomException e) {

System.out.println("Caught: " + e.getMessage());

static void validateAge(int age) throws CustomException {

if (age < 18) {

throw new CustomException("Age must be 18 or


above.");

Explain the significance and usage of the finally block in


Java with examples for different scenarios.

• Significance:
o Ensures cleanup code always runs, regardless of
exceptions.

• Scenarios:

o When no exception: Executes after try.

o When exception handled: Executes after catch.

o When exception not handled: Executes before the


program ends.

• Example:

java

Copy code

try {

int a = 5 / 0;

} catch (ArithmeticException e) {

System.out.println("Handled exception.");

} finally {

System.out.println("Always executes.");

Compare built-in exceptions and user-defined exceptions


with examples.
• Built-in Exceptions: Predefined by Java for common
errors.

o Example:

java

Copy code

try {

int arr[] = new int[2];

System.out.println(arr[5]); // Throws
ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Caught built-in exception.");

• User-defined Exceptions: Created for custom error


handling.

o Example:

java

Copy code

class MyException extends Exception {

MyException(String message) {
super(message);

public class Example {

public static void main(String[] args) {

try {

throw new MyException("Custom exception occurred!");

} catch (MyException e) {

System.out.println("Caught: " + e.getMessage());

• Comparison:

o Built-in: Ready to use, common errors.

o User-defined: Created for specific needs.


UNIT IV: Threads and Multi-threading, Applet, Application, and JDK

1 Mark Questions (20 Questions) Threads and Multi-threading

1. What is a thread in Java?

o A thread is a small unit of a process that runs


independently.

2. Define multithreading.

o Multithreading is running multiple threads simultaneously.

3. Which class is used to create threads in Java?

o The Thread class.

4. What is the difference between a process and a thread?

o A process is independent, but threads share the same


memory.

5. What is the entry point of a thread in Java?

o The run() method.

6. Name the two ways to create a thread in Java.

o Extend the Thread class or implement the Runnable


interface.

7. What is the run() method in Java threading?

o The method where the thread’s task is written.

8. State the use of the start() method in threading.

o It starts a new thread and calls run().


9. Define the thread life cycle.

o The stages: New, Runnable, Running, Blocked, and


Terminated.

10. What does the sleep() method do in threading?

o It pauses the thread for a specified time.

11. What is thread synchronization?

o It ensures only one thread accesses critical code at a time.

12. Which keyword is used for thread synchronization in Java?

o The synchronized keyword.

13. Can we call the run() method directly instead of start()?

o Yes, but it won’t create a new thread.

14. What is the purpose of the yield() method?

o It pauses the current thread to give others a chance.

15. What does the join() method do in threading?

o It waits for a thread to finish execution.

16. What is a daemon thread?

o A background thread supporting main threads.

17. Can a thread be restarted after it has finished execution?

o No, a finished thread cannot be restarted.

18. What is thread priority?

o The importance level of a thread, ranging from 1 to 10.


19. Name one method to stop a thread.

o Using the interrupt() method.

20. What is the purpose of the synchronized keyword?

o To prevent thread interference in shared resources.

Applets and Applications:

1. What is an applet in Java?

o An applet is a small program that runs in a web browser.

2. How is a Java application different from an applet?

o Applications run standalone, while applets run inside a


browser or viewer.

3. Define the Applet class.

o The Applet class is part of Java's java.applet package and is


used to create applets.

4. What is the significance of the init() method in applets?

o The init() method initializes the applet when it starts.

5. Which class is the base class for applets?

o The Applet class.

6. Name the lifecycle methods of an applet.

o init(), start(), stop(), destroy(), and paint().

7. What is JDK?
o JDK (Java Development Kit) is a toolkit for developing Java
applications.

8. What does HTML do for Java applets?

o HTML is used to embed and run applets in a web page.

9. Define the purpose of the paint() method in an applet.

o The paint() method is used to draw graphics or display


content in an applet.

10. What is the difference between an input stream and an


output stream?

o Input stream reads data, while output stream writes data.

3 Marks Questions (10 Questions) Threads and Multi-threading

1. Explain the differences between extending the Thread


class and implementing the Runnable interface.

o Extending Thread:

▪ Inherits Thread class directly.

▪ Can't extend another class.

▪ Example:

java

Copy code

class MyThread extends Thread {


public void run() {

System.out.println("Thread running");

new MyThread().start();

o Implementing Runnable:

▪ Implements Runnable interface.

▪ Can extend another class.

▪ Example:

java

Copy code

class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread running");

new Thread(new MyRunnable()).start();

2. Describe the thread life cycle with a diagram.

o Life Cycle:
▪ New: Thread created but not started (Thread t =
new Thread()).

▪ Runnable: Ready to run after calling start().

▪ Running: Actively executing run() method.

▪ Blocked/Waiting: Waiting for resources or other


threads.

▪ Terminated: Thread completes execution.

o Diagram:

sql

Copy code

New → Runnable → Running → Terminated

↑ ↓

Waiting/Blocked

3. Explain the join() and yield() methods in threading with


examples.

o join(): Waits for a thread to finish.

java

Copy code

Thread t1 = new Thread(() -> {


System.out.println("Thread 1 running");

});

t1.start();

t1.join(); // Main thread waits for t1

o yield(): Pauses the current thread to let others run.

java

Copy code

Thread.yield(); // Current thread gives CPU to others

4. Discuss how thread synchronization is achieved in Java.

o Use the synchronized keyword to allow one thread


at a time to access critical code.

java

Copy code

synchronized void display() {

System.out.println("Synchronized block");

5. What are thread priorities, and how can they be set in


Java?

o Thread priorities range from 1 (MIN) to 10 (MAX).


o Use setPriority() method.

java

Copy code

Thread t1 = new Thread();

t1.setPriority(Thread.MAX_PRIORITY);

Applets and Applications

6. Compare Java applets and Java applications.

o Applets:

▪ Runs in a browser.

▪ Uses Applet class.

▪ No main() method.

o Applications:

▪ Runs standalone.

▪ Uses main() method.

7. What are the key lifecycle methods of an applet? Explain


each briefly.

o init(): Initializes the applet.


o start(): Executes when applet starts or browser
refreshes.

o stop(): Stops the applet when not visible.

o destroy(): Cleans up resources.

o paint(): Draws graphics.

8. Describe how HTML tags are used to embed a Java applet


in a web page.

o Use the <applet> tag.

html

Copy code

<applet code="MyApplet.class" width="300"


height="300"></applet>

9. Explain the steps to create an application using JDK.

o Steps:

▪ Write code in a .java file.

▪ Compile with javac MyApp.java.

▪ Run with java MyApp.

10. Discuss how Java handles input-output streams in


applications.
o Input Stream: Reads data using classes like
FileInputStream.

o Output Stream: Writes data using classes like


FileOutputStream.

o Example:

java

Copy code

FileOutputStream fos = new FileOutputStream("file.txt");

fos.write("Hello".getBytes());

fos.close();

10 Marks Questions (5 Questions)

1. Explain in detail the thread life cycle and the methods used
for thread control in Java.

• Thread Life Cycle in Java:


In Java, a thread undergoes several states during its life
cycle, managed by the JVM:

1. New (Born):

▪ A thread is created but not yet started.

▪ Example:
java

Copy code

Thread t = new Thread();

2. Runnable:

▪ The thread is ready to run and can be executed


by the JVM.

▪ When the start() method is invoked, it moves to


this state.

▪ Example:

java

Copy code

t.start(); // Moves thread to runnable state

3. Running:

▪ The thread is actively running, executing the


run() method.

▪ Once the thread starts, it enters the running


state where it executes the code in the run()
method.

▪ Example:

java
Copy code

public void run() {

System.out.println("Thread is running.");

4. Blocked:

▪ The thread is blocked and waiting for a


resource or lock that is held by another thread.

▪ The thread cannot move to the running state


until it gets the resource.

5. Waiting:

▪ A thread can enter the waiting state when it


calls methods like wait(), join(), or sleep().

▪ The thread waits for another thread to perform


a particular action or signal.

6. Terminated:

▪ The thread has completed execution or was


terminated by the JVM.

▪ This state is reached when the run() method


finishes, or the thread is killed.

• Thread Control Methods:


o start(): Starts a thread, moving it to the Runnable
state.

o sleep(long millis): Pauses the thread for a specified


duration.

o join(): Causes the current thread to wait for the


thread to finish.

o interrupt(): Interrupts a thread.

o setPriority(int priority): Sets the thread's priority to


control its execution order.

o yield(): Suggests to the JVM that it should give other


threads a chance to execute.

2. Discuss the concept of thread synchronization in Java with


examples of synchronized methods and blocks.

• Thread Synchronization:

o Thread synchronization is a mechanism to ensure


that two or more threads do not access shared
resources simultaneously. This prevents data
inconsistency and race conditions.

o In Java, synchronization can be achieved using the


synchronized keyword.
• Synchronized Methods:

o A method can be synchronized by using the


synchronized keyword. When a method is
synchronized, only one thread can access it at a
time.

o Example:

java

Copy code

public synchronized void increment() {

count++;

o Here, increment() is synchronized, ensuring that


only one thread at a time can increment the count
variable.

• Synchronized Blocks:

o Instead of synchronizing the entire method,


synchronization can be applied to a specific block of
code inside a method to reduce the overhead.

o Example:

java
Copy code

public void increment() {

synchronized(this) {

count++;

o This allows the thread to hold the lock only on the


specific block of code that modifies count.

• Explanation:
Synchronized methods and blocks ensure that only one
thread can access a shared resource at a time. When one
thread enters a synchronized method or block, it holds
the lock on the object until it exits.

3. Compare and contrast Java applets and Java applications,


highlighting their use cases, lifecycle, and features.

Feature Java Applet Java Application

Embedded in web
Standalone programs
Use Case pages for small,
for desktops or servers.
interactive programs.
Feature Java Applet Java Application

init(), start(), stop(),


Begins execution from
Lifecycle destroy(), paint()
main() method.
methods.

Runs inside a web


Execution Runs directly on a
browser or an applet
Environment machine (standalone).
viewer.

Restricted access to Full access to system


Security
system resources. resources.

No main() method, Always has a main()


Use of main()
uses init(). method as entry point.

Typically used for Can be used for any


Graphics graphics and UI application, including
components. console or GUI-based.

• Java Applets:

o Use Cases: Historically used for creating small


games, tools, and interactive applications for web
browsers.

o Lifecycle:

▪ init(): Initializes the applet.


▪ start(): Starts or resumes the applet execution.

▪ stop(): Halts the applet temporarily.

▪ destroy(): Cleans up resources.

▪ paint(): Renders graphics.

o Security: Runs inside a sandbox to limit access to


the file system and network for security.

• Java Applications:

o Use Cases: Used for general-purpose standalone


applications, ranging from console-based to
graphical desktop applications.

o Lifecycle: Runs from the main() method, and the


execution is independent of a browser or external
environment.

o Security: No security restrictions like applets,


allowing access to system resources such as the file
system and network.

4. Explain the steps to create, compile, and run a Java applet


using JDK, including embedding the applet in an HTML page.

• Steps to Create an Applet:


1. Write the Applet Code:
Create a Java file (e.g., MyApplet.java).

java

Copy code

import java.applet.Applet;

import java.awt.Graphics;

public class MyApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Hello Applet", 50, 50);

2. Compile the Applet:

▪ Compile the .java file using javac.

bash

Copy code

javac MyApplet.java

3. Embed the Applet in an HTML Page:

▪ Create an HTML file to embed the applet.


html

Copy code

<html>

<body>

<applet code="MyApplet.class" width="300" height="300">

</applet>

</body>

</html>

4. Run the Applet:

▪ Use appletviewer to run the applet without a


browser.

bash

Copy code

appletviewer MyApplet.html

5. Describe Java's input-output stream management in detail


with examples of commonly used classes and methods.

• Input and Output Streams:


o Java provides a set of classes for handling input and
output (I/O) operations. These classes are divided
into byte streams and character streams.

• Byte Streams:

o InputStream and OutputStream are the root classes


for byte-based I/O operations. They deal with raw
binary data.

o FileInputStream: Used to read bytes from a file.

java

Copy code

FileInputStream fis = new FileInputStream("input.txt");

int data;

while ((data = fis.read()) != -1) {

System.out.print((char) data);

fis.close();

o FileOutputStream: Used to write bytes to a file.

java

Copy code

FileOutputStream fos = new FileOutputStream("output.txt");


fos.write("Hello World".getBytes());

fos.close();

• Character Streams:

o Reader and Writer classes are used for character-


based I/O. These streams handle text data and are
more efficient for character encoding/decoding.

o BufferedReader: Reads text from an input stream.

java

Copy code

BufferedReader reader = new BufferedReader(new


FileReader("input.txt"));

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

reader.close();

o PrintWriter: Writes formatted text.

java

Copy code
PrintWriter writer = new PrintWriter(new
FileWriter("output.txt"));

writer.println("Hello, PrintWriter!");

writer.close();

• Explanation:

o Byte Streams: Useful for binary data such as images


and audio files.

o Character Streams: Preferred for reading and writing


text files, providing automatic character encoding.

o Both streams provide classes to read/write data,


and buffering improves performance.

You might also like