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

Java I/O Streams and Error Handling Guide

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 views5 pages

Java I/O Streams and Error Handling Guide

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

CHAPTER – 7

INPUT IN JAVA
PART – A VERY SHORT QUESTIONS
1. Name the stream that is used to handle binary I/O of primitive data type and
String values.
→ DataInputStream and DataOutputStream
2. What is the use of Buffered streams?
→ To improve efficiency of I/O operations by reducing disk access.
3. Give the commands used for simple output in Java.
→ [Link]() and [Link]()
4. Name the three predefined I/O streams that use the console - input, error and
output streams.
→ [Link], [Link], [Link]
5. What type of data are handled by Data Streams?
→ Primitive data types (int, char, float, etc.) and Strings.
6. What can you do with the Scanner class?
→ Read input from keyboard, files, or other input sources.
7. To which package do the Scanner and Printer class belong?
→ [Link] (Scanner), [Link] (Printer classes)
8. Write the syntax to create a Scanner object.
→ Scanner sc = new Scanner([Link]);
9. Name the package that contains Scanner class.
→ [Link]
[Link] is the use of the keyword import?
→ To access classes from other packages.
[Link] the type of error in each of the following:
(i) Division by a variable that contains zero → Runtime Error
(ii) Multiplication operator used when division required → Logical Error
(iii) Missing semicolon → Syntax Error
[Link] the code to create an object of scanner class
→ Scanner sc = new Scanner([Link]);
[Link] the type of error in each given case:
(i) [Link](36 – 45); → Runtime Error (square root of negative number)
(ii) int a; b; c; → Syntax Error
[Link] is the difference between the Scanner class element nextInt() and
next()?
→ nextInt() → Reads an integer value.
→ next() → Reads a single word (string without spaces).
PART – B SHORT QUESTIONS
Part B: Short Questions
1. What is a package? Give an example.
→ A package is a collection of related classes and interfaces.
Example: [Link] (contains Scanner, ArrayList, etc.)

2. Explain various usage/advantages of Java Packages.


 Avoids name conflicts
 Provides reusability of code
 Easier to maintain
 Provides access control
 Supports modular programming

3. Explain different types of errors.


 Syntax Error → Grammar/format mistakes in code.
 Runtime Error → Errors during execution (e.g., divide by zero).
 Logical Error → Program runs but gives wrong result.

4. How is runtime error different from other two types of errors?


→ Runtime errors occur while executing the program, not during compilation.
Example: Divide by zero.
(Syntax and logical errors don’t cause the program to crash at runtime.)

5. Write about the three predefined I/O streams.


 [Link] → Standard input stream (keyboard).
 [Link] → Standard output stream (console).
 [Link] → Standard error stream.

6. Explain the uses of Java Packages.


→ Organizes classes, prevents naming conflicts, allows reusability, makes searching and
maintenance easier, provides access control.

7. List the advantages of using Scanner class.


 Easy to use for input.
 Can read different types of data (int, float, string).
 Supports input from keyboard, files, and streams.

8. Write a program to find the Addition of three numbers using Scanner class.
import [Link].*;
class AddThree
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int c = [Link]();
[Link]("Sum = " + (a + b + c));
}
}

9. Program: Accept perpendicular and base of a Right Angled Triangle.


Display hypotenuse, area, perimeter.
import [Link].*;
class RightTriangle
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
double p = [Link]();
double b = [Link]();
double h = [Link](p*p + b*b);
double area = (p * b) / 2;
double perimeter = p + b + h;
[Link]("Hypotenuse: " + h);
[Link]("Area: " + area);
[Link]("Perimeter: " + perimeter);
}
}

10. Program: Accept length & breadth of rectangle. Display area & perimeter.
import [Link].*;
class Rectangle
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int l = [Link]();
int b = [Link]();
[Link]("Area = " + (l * b));
[Link]("Perimeter = " + (2 * (l + b)));
}
}

11. Program: Input 3 numbers & compute average.


import [Link].*;
class Average
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int a = [Link](), b = [Link](), c = [Link]();
double avg = (a + b + c) / 3.0;
[Link]("Average = " + avg);
}
}

12. Program: Input and swap two numbers using Scanner.


import [Link].*;
class Swap
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
int a = [Link](), b = [Link]();
int temp = a;
a = b;
b = temp;
[Link]("After swap: a = " + a + ", b = " + b);
}
}

13. What do you understand by ‘Run time error’? Explain with example.
→ Error that occurs during execution of a program.
Example:
int a = 5, b = 0;
[Link](a / b); // Division by zero → Runtime Error

14. What are the different types of errors that take place during execution of
a program?
 Runtime errors (e.g., divide by zero)
 Logical errors (e.g., wrong formula)

15. Distinguish between syntax error and logical error.


 Syntax Error → Violates Java grammar rules, caught at compile-time.
 Logical Error → Program runs but gives wrong result due to wrong logic.

Common questions

Powered by AI

The Scanner class in Java provides a simple and convenient way to parse primitive types and strings using regular expressions. Unlike traditional methods such as using BufferedReader with InputStreamReader, Scanner can directly read and parse different data types including integers, floats, and strings from an input source. Its main advantages are ease of use, ability to read from various input sources, and flexibility with underlining patterns. However, it may not be as performance-optimized for reading large datasets due to lower buffering capabilities compared to BufferedReader and can cause input-related exceptions if not handled properly .

Logical errors are identified by unexpected program output despite correct syntax. Debugging tools like integrated development environments (IDEs) and breakpoints help trace the execution path and variable states. Code reviews, unit testing, and logging approaches provide insight into where logic deviates from expectations. Properly understanding and validating the desired algorithmic approach is key to correcting these errors .

Developers prefer logical error checks when ensuring functionality correctness since syntax errors are automatically identified by the compiler. Logical errors, occurring within the algorithm or logic, require manual detection through testing and verification. The main advantage is ensuring that business logic aligns with requirements, mitigating runtime inaccuracies despite syntactically correct code .

Java packages support modular programming by organizing classes and interfaces into namespaces that prevent naming conflicts and enhance code readability and maintenance. They also offer access control, allowing developers to define the visibility of classes and members, which enhances encapsulation and security. These features promote cleaner design and facilitate the reusability and maintainability of code within larger systems .

The three predefined I/O streams in Java are System.in, System.out, and System.err, which facilitate basic interactions with the console. System.in is used for standard input, typically from the keyboard; System.out is the standard output stream for displaying results; and System.err is for error messages. These streams provide a foundation for handling input and output operations in a Java program and allow programmers to perform basic console interactions seamlessly, enhancing the user interface of applications .

Buffered streams in Java improve the efficiency of I/O operations by reducing the number of direct interactions with the disk, therefore minimizing disk access and increasing performance. They temporarily store data in a buffer, allowing for operations to be performed on large blocks of data at once instead of on each piece individually, thus conserving system resources and enhancing overall I/O speed .

Data streams, including DataInputStream and DataOutputStream, handle binary I/O of primitive data types and strings, enabling efficient processing of these formats in Java applications. In contrast, character streams, such as FileReader and FileWriter, manage I/O operations for text data using character encoding. The main difference is the focus: data streams are foundational for handling binary content, while character streams cater to textual data with attention to encoding and decoding .

The import keyword in Java allows the inclusion of classes from other packages into the current file, streamlining code and reducing namespace clutter. This is essential for accessing library functions and frameworks, enabling code reuse and modularization. Without imports, programmers have to use fully qualified class names, which increases complexity and hinders readability .

When using Math.sqrt() in Java, a runtime error can occur if the argument is negative, resulting in a NaN (Not a Number) value. This exemplifies the importance of handling runtime errors, as they occur during program execution and can cause unexpected behavior or program crashes if not properly addressed. Error checking mechanisms, such as conditional checks or try-catch blocks, are essential to ensure robustness in software applications .

The Scanner class can facilitate input collection for math operations on geometric shapes. For example, when calculating a triangle’s hypotenuse, the class reads side lengths to compute it using the Pythagorean theorem, as shown: 'Scanner sc = new Scanner(System.in); double p = sc.nextDouble(); double b = sc.nextDouble(); double h = Math.sqrt(p*p + b*b); System.out.println("Hypotenuse: " + h);'. This setup highlights Scanner’s utility in dynamically acquiring dimensions and performing on-the-fly computations .

You might also like