Java UNIT - 4 Material
Java UNIT - 4 Material
Unit - 4
UNIT IV: Packages and Java Library: Introduction, Defining Package, Importing Packages and
Classes into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang
Package and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and
Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class, Time Package,
Class Instant (java.time.Instant), Formatting for Date/Time in Java, Temporal Adjusters Class,
Temporal Adjusters Class. Exception Handling: Introduction, Hierarchy of Standard Exception
Classes, Keywords throws and throw, try, catch, and finally Blocks, Multiple Catch Clauses, Class
Throwable, Unchecked Exceptions, Checked Exceptions. Java I/O and File: Java I/O API, standard
I/O streams, types, Byte streams, Character streams, Scanner class, Files in Java
Java Package :
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package :
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
GATES-CSE(DS|CY) Page 1
Object Oriented Programming Through Java UNIT-3
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
GATES-CSE(DS|CY) Page 2
Object Oriented Programming Through Java UNIT-3
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
GATES-CSE(DS|CY) Page 3
Object Oriented Programming Through Java UNIT-3
10. }
Output:Hello
Note: Sequence of the program must be package then import then class.
GATES-CSE(DS|CY) Page 4
Object Oriented Programming Through Java UNIT-3
Subpackage in java :
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has defined a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are
for networking etc and so on. So, Sun has subcategorized the java package into subpackages such
as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket
classes in net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or
org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
GATES-CSE(DS|CY) Page 5
Object Oriented Programming Through Java UNIT-3
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive. For
example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells where
to look for class file. For example:
GATES-CSE(DS|CY) Page 6
Object Oriented Programming Through Java UNIT-3
e:\sources> java -classpath c:\classes mypack.Simple
Output: Welcome to package
GATES-CSE(DS|CY) Page 7
Object Oriented Programming Through Java UNIT-3
Wrapper Classes
Wrapper classes in Java are used to convert primitive data types into objects. Each of the eight
primitive data types (byte, short, int, long, float, double, char, and boolean) has a corresponding
wrapper class in the java.lang package. These classes provide a way to use primitive data types as
objects, which is useful when working with collections or when an object reference is required.
Here is a list of the primitive types and their corresponding wrapper classes:
1. byte -> Byte
2. short -> Short
3. int -> Integer
4. long -> Long
5. float -> Float
6. double -> Double
7. char -> Character
8. boolean -> Boolean
GATES-CSE(DS|CY) Page 8
Object Oriented Programming Through Java UNIT-3
• Value Retrieval:
o int intValue(), byte byteValue(), short shortValue(), long longValue(), float
floatValue(), double doubleValue(), char charValue(), boolean booleanValue()
o Example:
Integer obj = 10;
int primitive = obj.intValue();
• String Conversion:
o String toString()
o Example:
Integer obj = 10;
String str = obj.toString(); // "10"
• Parsing Strings:
o static int parseInt(String s), static double parseDouble(String s), etc.
o Example:
int num = Integer.parseInt("123"); // 123
• Comparisons:
o static int compare(int x, int y), boolean equals(Object obj)
o Example:
Integer obj1 = 10;
Integer obj2 = 20;
int result = Integer.compare(obj1, obj2); // -1 (since 10 < 20)
Examples
public class WrapperExample {
public static void main(String[] args) {
// Autoboxing
Integer intObj = 10;
Double doubleObj = 15.5;
// Unboxing
int intValue = intObj;
double doubleValue = doubleObj;
GATES-CSE(DS|CY) Page 9
Object Oriented Programming Through Java UNIT-3
int parsedInt = Integer.parseInt("123");
// Comparison
boolean areEqual = intObj.equals(10);
int comparison = Integer.compare(10, 20);
GATES-CSE(DS|CY) Page 10
Object Oriented Programming Through Java UNIT-3
2. Output Destinations:
o Formatter can output to Appendable objects (like StringBuilder), OutputStream, and
File.
3. Localization:
o Supports localization to format numbers, dates, and text in a locale-specific manner.
Common Format Specifiers
• %s: String
• %d: Decimal integer
• %f: Floating-point number
• %x: Hexadecimal integer
• %o: Octal integer
• %e: Scientific notation
• %c: Character
• %b: Boolean
• %t: Date and time
o %tH: Hour (24-hour clock)
o %tM: Minute
o %tS: Second
o %tY: Year
o %tm: Month
o %td: Day of month
Example Usage
Basic Formatting
import java.util.Formatter;
public class FormatterExample {
public static void main(String[] args) {
Formatter formatter = new Formatter();
// Formatting strings
formatter.format("Name: %s\n", "John Doe");
// Formatting integers
formatter.format("Age: %d\n", 30);
GATES-CSE(DS|CY) Page 11
Object Oriented Programming Through Java UNIT-3
formatter.format("Balance: %.2f\n", 12345.678);
// Formatting dates
formatter.format("Date: %tY-%tm-%td\n", System.currentTimeMillis(),
System.currentTimeMillis(), System.currentTimeMillis());
System.out.println(formatter);
Random Class
The Random class in Java, part of the java.util package, is used to generate pseudo-random numbers.
It can generate random integers, floating-point numbers, booleans, bytes, and can also be used to
generate random values within a specific range.
Key Features of the Random Class
1. Seeded Random Number Generation:
o The Random class can use a seed value to generate a sequence of random numbers.
If the same seed is used, the same sequence of numbers will be generated.
o If no seed is provided, the current time (in milliseconds) is used as the seed.
2. Thread Safety:
o Instances of Random are not thread-safe. If multiple threads need to generate random
numbers, it is recommended to use ThreadLocalRandom or ensure proper
synchronization.
Common Methods
1. Constructors:
o Random(): Creates a new random number generator using a unique seed based on
the current time.
o Random(long seed): Creates a new random number generator using a specified seed.
2. Number Generation Methods:
GATES-CSE(DS|CY) Page 12
Object Oriented Programming Through Java UNIT-3
o int nextInt(): Returns the next random int value.
o int nextInt(int bound): Returns a random int value between 0 (inclusive) and the
specified bound (exclusive).
o long nextLong(): Returns the next random long value.
o boolean nextBoolean(): Returns the next random boolean value.
o float nextFloat(): Returns the next random float value between 0.0 and 1.0.
o double nextDouble(): Returns the next random double value between 0.0 and 1.0.
o void nextBytes(byte[] bytes): Generates random bytes and places them into a user-
supplied byte array.
Example Usage
Basic Random Number Generation
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
GATES-CSE(DS|CY) Page 13
Object Oriented Programming Through Java UNIT-3
Time Package
The java.time package in Java, introduced in Java 8, provides a comprehensive set of classes for
handling dates, times, and time zones. It addresses many of the deficiencies of the older
java.util.Date and java.util.Calendar classes and provides a much cleaner and more powerful API
for date and time manipulation.
Key Classes and Interfaces in the java.time Package
1. LocalDate: Represents a date (year, month, day) without time and time zone.
2. LocalTime: Represents a time (hour, minute, second, nanosecond) without date and time
zone.
3. LocalDateTime: Represents both date and time without a time zone.
4. ZonedDateTime: Represents date and time with a time zone.
5. OffsetDateTime: Represents date and time with an offset from UTC/Greenwich.
6. Instant: Represents a point in time (timestamp) with nanosecond precision.
7. Duration: Represents a duration of time measured in seconds and nanoseconds.
8. Period: Represents a period of time in years, months, and days.
9. ZoneId: Represents a time zone identifier.
10. ZoneOffset: Represents a time zone offset from UTC.
11. DateTimeFormatter: Used for formatting and parsing date-time objects.
Example Usage
import java.time.LocalDate;
GATES-CSE(DS|CY) Page 14
Object Oriented Programming Through Java UNIT-3
public class LocalDateExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today);
Class Instant
Java Instant class is used to represent the specific moment on the time line. It inherits the Object
class and implements the Comparable interface.
Java Instant Class Declaration
Let's see the declaration of java.time.Instant class.
public final class Instant extends Object
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable
import java.time.Instant;
public class InstantExample1 {
public static void main(String[] args) {
Instant inst = Instant.parse("2017-02-03T10:37:30.00Z");
System.out.println(inst);
}
}
GATES-CSE(DS|CY) Page 15
Object Oriented Programming Through Java UNIT-3
TemporalAdjuster can be used in two ways. The first is by invoking the method on the interface
directly. The second is by using Temporal.with(TemporalAdjuster):
The following two ways of using TemporalAdjuster are equivalent, but it is recommended to use
the second approach, as it is cleaner and readable
temporal = thisAdjuster.adjustInto(temporal);
temporal = temporal.with(thisAdjuster);
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class TemporalAdjusterExample {
public static void main(String args[])
{
TemporalAdjusterExample gfg
= new TemporalAdjusterExample();
gfg.testAdjusters();
}
public void testAdjusters()
{
// to get the current date
LocalDate date1 = LocalDate.now();
System.out.println("Today's date is: " + date1);
// to get the next monday
LocalDate nextTuesday = date1.with(
TemporalAdjusters.next(DayOfWeek.MONDAY));
System.out.println("Next Monday is on : " + nextTuesday);
// to get the second saturday of next month
LocalDate firstInYear = LocalDate.of(
date1.getYear(), date1.getMonth(), 1);
GATES-CSE(DS|CY) Page 16
Object Oriented Programming Through Java UNIT-3
LocalDate secondSaturday = firstInYear.with(TemporalAdjusters.nextOrSame(
DayOfWeek.SATURDAY)).with(TemporalAdjusters.next(
DayOfWeek.SATURDAY));
// print date of second Saturday of next month
System.out.println("Second saturday is on : " + secondSaturday);
}
}
Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
GATES-CSE(DS|CY) Page 17
Object Oriented Programming Through Java UNIT-3
perform exception handling, the rest of the statements will be executed. That is why we use
exception handling in Java.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
GATES-CSE(DS|CY) Page 18
Object Oriented Programming Through Java UNIT-3
The classes that directly inherit the Throwable class except RuntimeException and Error are known
as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
GATES-CSE(DS|CY) Page 19
Object Oriented Programming Through Java UNIT-3
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
GATES-CSE(DS|CY) Page 20
Object Oriented Programming Through Java UNIT-3
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
GATES-CSE(DS|CY) Page 21
Object Oriented Programming Through Java UNIT-3
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
GATES-CSE(DS|CY) Page 22
Object Oriented Programming Through Java UNIT-3
System.out.println("finally block is always executed");
}
try {
GATES-CSE(DS|CY) Page 23
Object Oriented Programming Through Java UNIT-3
public class TestFinallyBlock2{
public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
GATES-CSE(DS|CY) Page 24
Object Oriented Programming Through Java UNIT-3
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
import java.io.IOException;
GATES-CSE(DS|CY) Page 25
Object Oriented Programming Through Java UNIT-3
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
GATES-CSE(DS|CY) Page 26
Object Oriented Programming Through Java UNIT-3
// Main class
class GFG {
// Main class
GATES-CSE(DS|CY) Page 27
Object Oriented Programming Through Java UNIT-3
class GFG {
The Java I/O API (Input/Output Application Programming Interface) is a fundamental part of Java
programming for handling input and output operations. Here are some key components and
concepts:
1. Streams: Streams are the core abstraction used in Java I/O. They represent sequences of
data. There are two types:
o Byte Streams: Handle I/O of raw binary data (InputStream, OutputStream).
o Character Streams: Handle I/O of character data (Reader, Writer).
2. Byte Streams:
o InputStream and OutputStream: Base classes for all byte stream classes.
GATES-CSE(DS|CY) Page 28
Object Oriented Programming Through Java UNIT-3
o FileInputStream and FileOutputStream: Read from and write to files.
o ByteArrayInputStream and ByteArrayOutputStream: Read from and write to byte
arrays.
o BufferedInputStream and BufferedOutputStream: Provide buffering for improved
performance.
3. Character Streams:
o Reader and Writer: Base classes for all character stream classes.
o FileReader and FileWriter: Read from and write to files using characters.
o BufferedReader and BufferedWriter: Provide buffering for improved performance.
o InputStreamReader and OutputStreamWriter: Bridge between byte streams and
character streams.
4. File I/O:
o File: Represents files and directories on the filesystem.
o FileInputStream, FileOutputStream, FileReader, FileWriter: Classes for reading
from and writing to files.
o RandomAccessFile: Allows reading from and writing to a file with random access.
5. Serialization:
o Serializable interface: Used to mark classes whose objects can be serialized.
o ObjectInputStream and ObjectOutputStream: Used for serializing and deserializing
objects.
6. Other useful classes:
o Scanner: Used for parsing primitive types and strings from input streams.
o PrintStream: Supports formatted output operations to a text output stream.
o Console: Provides access to character-based console device.
Java's I/O API is versatile and provides different classes to handle various I/O operations efficiently
GATES-CSE(DS|CY) Page 29
Object Oriented Programming Through Java UNIT-3
In Java, the standard I/O streams are used for interacting with the console, allowing the program to
read input from the user and print output to the screen. These streams are predefined in the System
class:
1. Standard Input (System.in):
o Used to read input from the console.
o It is an instance of InputStream.
o Commonly wrapped with Scanner or BufferedReader for easier handling.
import java.util.Scanner;
GATES-CSE(DS|CY) Page 30
Object Oriented Programming Through Java UNIT-3
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Byte Streams
Byte streams in Java are used for reading and writing binary data. They handle raw bytes, making
them suitable for processing any kind of I/O, including binary files and streams. Byte streams are
part of the java.io package. Here's a closer look at the key classes and their usage:
GATES-CSE(DS|CY) Page 31
Object Oriented Programming Through Java UNIT-3
Key Classes
1. InputStream: The abstract base class for all byte input streams. It defines methods like
read(), read(byte[] b), and close().
o FileInputStream: Reads bytes from a file.
import java.io.FileInputStream;
import java.io.IOException;
GATES-CSE(DS|CY) Page 32
Object Oriented Programming Through Java UNIT-3
e.printStackTrace();
}
}
}
OutputStream: The abstract base class for all byte output streams. It defines methods like write(int
b), write(byte[] b), and flush().
• FileOutputStream: Writes bytes to a file.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
GATES-CSE(DS|CY) Page 33
Object Oriented Programming Through Java UNIT-3
e.printStackTrace();
}
}
}
Buffered Streams:
• BufferedInputStream: Provides buffering for input streams to improve performance.
• BufferedOutputStream: Provides buffering for output streams to improve performance.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
GATES-CSE(DS|CY) Page 34
Object Oriented Programming Through Java UNIT-3
bos.write(data.getBytes()); // Write data to file
} catch (IOException e) {
e.printStackTrace();
}
}
}
Byte streams are ideal for handling binary data and are a fundamental part of Java's I/O system.
They are versatile and can be used to read from and write to files, byte arrays, and other byte-based
sources and destinations.
Character streams
Character streams in Java are designed to handle the reading and writing of data as characters. They
are built on top of byte streams but provide a more convenient way to process text data by handling
character encoding and decoding automatically. Character streams are part of the java.io package
and are designed to work with Unicode characters, making them suitable for internationalization.
Key Classes
1. Reader: The abstract base class for all character input streams. It defines methods like read(),
read(char[] cbuf), and close().
o FileReader: Reads characters from a file.
import java.io.FileReader;
import java.io.IOException;
GATES-CSE(DS|CY) Page 35
Object Oriented Programming Through Java UNIT-3
e.printStackTrace();
}
}
}
import java.io.StringReader;
import java.io.IOException;
Writer: The abstract base class for all character output streams. It defines methods like write(int c),
write(char[] cbuf), and flush().
• FileWriter: Writes characters to a file.
import java.io.FileWriter;
import java.io.IOException;
GATES-CSE(DS|CY) Page 36
Object Oriented Programming Through Java UNIT-3
} catch (IOException e) {
e.printStackTrace();
}
}
}
GATES-CSE(DS|CY) Page 37
Object Oriented Programming Through Java UNIT-3
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
GATES-CSE(DS|CY) Page 38
Object Oriented Programming Through Java UNIT-3
pw.println("Hello, World!"); // Print formatted output to file
} catch (IOException e) {
e.printStackTrace();
}
}
}
Character streams are designed for handling text data in a more human-readable form compared to
byte streams. They provide better support for character encoding and decoding, making them
suitable for reading from and writing to text files, processing strings, and handling internationalized
text.
Scanner Class
The Scanner class in Java, part of the java.util package, is used for parsing and reading input from
various sources, including keyboard input, files, and strings. It provides a convenient way to parse
primitive types and strings using regular expressions.
Key Features
• Versatile Input Sources: Can read from various sources such as InputStream, File, String,
and Readable.
• Parsing Methods: Provides methods to read and parse different data types like int, double,
boolean, etc.
• Delimiter Support: Supports custom delimiters and regular expressions for splitting input
data.
• Exception Handling: Handles input errors gracefully and can throw exceptions for invalid
input.
Commonly Used Constructors
1. From InputStream (e.g., System.in):
import java.util.Scanner;
GATES-CSE(DS|CY) Page 39
Object Oriented Programming Through Java UNIT-3
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}
From File:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
File Handling: In Java, working with files is a common task, and there are several classes and
methods available to handle file operations, ranging from basic file handling to more advanced
functionalities. Here's an overview of how to work with files in Java:
Basic File Operations
1. Creating a File Object
GATES-CSE(DS|CY) Page 40
Object Oriented Programming Through Java UNIT-3
o Use the File class from the java.io package to create a file object.
2. Creating and Deleting Files
3. Check File Properties
4. Reading and Writing Files
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
GATES-CSE(DS|CY) Page 41
Object Oriented Programming Through Java UNIT-3
}
}
}
import java.io.FileWriter;
import java.io.IOException;
GATES-CSE(DS|CY) Page 42