Unit 4
Unit 4
10. What is the difference between byte streams and character streams in Java I/O?
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.
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.
To import a package, use the import keyword followed by the package name:
Java
import java.util.Scanner;
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.
Packages in Java have access control mechanisms to control the visibility of classes and
interfaces:
The java.lang package is automatically imported into every Java program. It contains
fundamental classes that are essential for basic Java programming.
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?
Java
package com.example.utils;
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);
}
}
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;
try {
System.out.print("Enter a number: ");
int number = Integer.parseInt(scanner.nextLine());
Explanation:
Java
import java.util.Scanner;
To read and write to a file in Java, you can use the FileReader, FileWriter, BufferedReader,
and BufferedWriter classes:
Java
import java.io.*;
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.