Day-74 Understanding Scanner Class and Exception Handling in Java



This content originally appeared on DEV Community and was authored by Tamilselvan K

Scanner Class in Java

The Scanner class in Java is a utility class that belongs to the java.util package. It is primarily used to read input from various sources like the keyboard (standard input), files, or other input streams.

How to Use the Scanner Class

To use the Scanner class, you first need to import it:

import java.util.Scanner;

Then, you can create a Scanner object and use it to read different types of input from the console or other sources.

Common Scanner Methods

Here are some commonly used methods of the Scanner class:

  • nextLine() – Reads an entire line
  • next() – Reads a single word
  • nextInt() – Reads an integer
  • nextFloat() – Reads a float
  • nextDouble() – Reads a double
  • nextBoolean() – Reads a boolean
  • nextByte(), nextShort(), nextLong() – Read respective data types
  • close() – Closes the scanner

Exception Handling in Java

An exception is an event that occurs during the execution of a program and disrupts the normal flow of instructions.

Why Exception Handling?

Exception handling helps separate the main logic of the program from the error-handling logic. This makes the code cleaner, more readable, and easier to manage.

Types of Exceptions

1.Checked Exceptions (Compile-time)
These exceptions must be either caught or declared in the method.
Examples: IOException, SQLException

2.Unchecked Exceptions (Runtime)
These occur during the execution of the program.
Examples: ArithmeticException, NullPointerException`

Errors in Java

Errors are serious problems that occur during the execution of a program. Unlike exceptions, errors typically indicate issues that are beyond the control of the programmer and are often not recoverable.

Types of Errors

1.Compile-time Errors

  • Syntax errors such as missing semicolons or incorrect statements

2.Runtime Errors

  • Serious issues like OutOfMemoryError, StackOverflowError

Summary

  • Compile-time errors can be fixed during development.
  • Both checked and unchecked exceptions can be handled using try-catch blocks in Java.
  • Errors, especially serious runtime errors, cannot be handled using standard exception-handling techniques.


This content originally appeared on DEV Community and was authored by Tamilselvan K