0% found this document useful (0 votes)
8 views6 pages

Unit 4

The document provides an overview of Java packages, including their purpose, how to import them, and examples of commonly used packages. It also explains exception handling, including the differences between checked and unchecked exceptions, the use of the finally block, and the hierarchy of standard exception classes. Additionally, it includes practical examples of using the Scanner class for input, creating utility packages, and reading/writing files in Java.

Uploaded by

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

Unit 4

The document provides an overview of Java packages, including their purpose, how to import them, and examples of commonly used packages. It also explains exception handling, including the differences between checked and unchecked exceptions, the use of the finally block, and the hierarchy of standard exception classes. Additionally, it includes practical examples of using the Scanner class for input, creating utility packages, and reading/writing files in Java.

Uploaded by

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

1. What is a package in Java?

2. How do you import a package into a Java program?

3. Name some commonly used packages in Java SE.

4. What is the difference between checked and unchecked exceptions?

5. Explain the purpose of the finally block in exception handling.

6. Describe the concept of access control in packages.

7. What is the significance of the java.lang package?

8. How does autoboxing and auto-unboxing work in Java?

9. Explain the hierarchy of standard exception classes.

10. What is the difference between byte streams and character streams in Java I/O?

11. Create a Java package to encapsulate utility classes.

12. Write a Java program that uses the Math class to perform mathematical calculations.
13. Implement exception handling in a program to handle potential errors.

14. Use the Scanner class to read input from the user.

15. Write a Java program to read and write data to a file

1. What is a package in Java?

A package in Java is a mechanism used to organize a set of related classes and interfaces. It
provides a namespace to avoid naming conflicts and promotes code reusability and modularity.

2. How do you import a package into a Java program?

To import a package, use the import keyword followed by the package name:

Java
import java.util.Scanner;

3. Name some commonly used packages in Java SE.

 java.lang: Contains fundamental classes like Object, String, Math, etc.


 java.util: Provides utility classes like Date, Calendar, Random, Scanner, etc.
 java.io: Contains classes for input/output operations like File, FileReader,
FileWriter, etc.
 java.net: Provides classes for network programming like Socket, URL, ServerSocket,
etc.
 java.sql: Contains classes for database connectivity.

4. What is the difference between checked and unchecked exceptions?

 Checked Exceptions:
o Must be declared in the method signature using the throws keyword.
o Checked at compile time.
o Examples: IOException, SQLException, etc.
 Unchecked Exceptions:
o Don't need to be declared in the method signature.
o Checked at runtime.
o Examples: NullPointerException, ArrayIndexOutOfBoundsException, etc.

5. Explain the purpose of the finally block in exception handling.


The finally block is used to execute code that must be run regardless of whether an exception
is thrown or not. It's often used for cleanup tasks like closing files or database connections.

6. Describe the concept of access control in packages.

Packages in Java have access control mechanisms to control the visibility of classes and
interfaces:

 Public: Accessible from anywhere.


 Protected: Accessible within the package and subclasses.
 Default (package-private): Accessible within the package.
 Private: Accessible only within the class.

7. What is the significance of the java.lang package?

The java.lang package is automatically imported into every Java program. It contains
fundamental classes that are essential for basic Java programming.

8. How does autoboxing and auto-unboxing work in Java?

 Autoboxing: Automatically converts primitive data types to their corresponding wrapper


classes.
 Auto-unboxing: Automatically converts wrapper classes to their corresponding primitive
data types.

9. Explain the hierarchy of standard exception classes.

The Throwable class is the root of the exception hierarchy. It has two main subclasses: Error
and Exception. Exception is further divided into RuntimeException and checked exceptions.

10. What is the difference between byte streams and character streams in Java I/O?

 Byte Streams: Deal with raw bytes.


 Character Streams: Deal with characters.

11. Create a Java package to encapsulate utility classes.

Java
package com.example.utils;

public class MathUtils {


public static int factorial(int n) {
// ...
}
}

12. Write a Java program that uses the Math class to perform mathematical calculations.
Java
public class MathExample {
public static void main(String args) {
double pi = Math.PI;
double sqrt = Math.sqrt(25);
System.out.println("PI: " + pi);
System.out.println("Square root of 25: " + sqrt);
}
}

13. Implementing Exception Handling

Exception handling is a crucial aspect of robust programming. It allows you to anticipate and
gracefully handle errors that may occur during program execution. Here's a basic example:

Java
import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a number: ");
int number = Integer.parseInt(scanner.nextLine());

System.out.println("You entered: " + number);

// Potential division by zero error


int result = 10 / number;
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This block always executes.");
}
}
}

Explanation:

 try block: Encloses the code that might throw exceptions.


 catch blocks: Handle specific types of exceptions. In this case, we handle
NumberFormatException (for invalid input) and ArithmeticException (for division by
zero).
 finally block: Executes regardless of whether an exception is thrown or not. It's often
used for cleanup tasks like closing files or releasing resources.

14. Using the Scanner Class


The Scanner class is used to read input from various sources, including the keyboard. Here's
how to use it:

Java
import java.util.Scanner;

public class ScannerExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.println("Name: " + name);


System.out.println("Age: " + age);
}
}

15. Reading and Writing to a File

To read and write to a file in Java, you can use the FileReader, FileWriter, BufferedReader,
and BufferedWriter classes:

Java
import java.io.*;

public class FileReadWriteExample {


public static void main(String[] args) {
try {
// Write to a file
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, world!\nThis is a test.");
writer.close();

// Read from a file


FileReader reader = new FileReader("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
reader.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

Explanation:
1. Writing to a file:
o Create a FileWriter object to write to a file.
o Use the write() method to write content to the file.
o Close the FileWriter to release resources.
2. Reading from a file:
o Create a FileReader object to read from a file.
o Create a BufferedReader to read the file line by line.
o Use a while loop to read lines until the end of the file.
o Close the BufferedReader and FileReader to release resources.

Remember to handle potential IOExceptions that might occur during file operations.

You might also like