SlideShare a Scribd company logo
U-III
Other Utility classes: String Tokenizer, Date,
Calendar, Gregorian Calendar, Scanner
Java Input/Output: Exploring java.io, Java I/O
classes and interfaces, File, Stream classes,
byte stream, character stream, serialization
java.util.Scanner
• Scanner class in Java is found in the java.util package.
• public final class Scanner extends Object implements Iterator<String>, Closeable
• Java provides various ways to read input from the keyboard, the java.util.Scanner
class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various
primitive values.
• By the help of Scanner in Java, we can get input from the user in primitive types
such as int, long, double, byte, float, short, etc.
• To get the instance of Java Scanner which reads input from the user, we need to
pass the input stream (System.in) in the constructor of Scanner class. For
Example:
Scanner in = new Scanner(System.in);
•To get the instance of Java Scanner which parses the strings, we need to pass the
strings in the constructor of Scanner class. For Example:
Scanner in = new Scanner("Hello Javatpoint");
Using Scanner class methods
import java.util.*;
public class ScannerClassExample
{
public static void main(String args[])
{
String s = "Hello, This is Java class.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " +
scan.hasNext());
//Print the string
System.out.println("String:”+scan.nextLine());
//Using scanner class methods to read string,int,float
System.out.println("--------Enter Your Details--");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println(" Name: “ +name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
} }
Output:
Boolean Result: true
String: Hello, This is Java class.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
StringTokenizer
• The processing of text often consists of parsing a formatted input string. Parsing is
the division of text into a set of discrete parts, or tokens.
• StringTokenizer implements the Enumeration interface.
• To use StringTokenizer, you specify an input string and a string that contains
delimiters.
• Delimiters are characters that separate tokensfor example, “,;:” sets the delimiters
to a comma, semicolon,and colon.
• The default set of delimiters consists of the whitespace characters: space,
tab,newline, and carriage return.
• The StringTokenizer constructors are shown here:
• StringTokenizer(String str)
• StringTokenizer(String str, String delimiters)
• StringTokenizer(String str, String delimiters, boolean delimAsToken)
• In all versions, str is the string that will be tokenized.
• In the first version, the default delimiters are used.
• In the second and third versions, delimiters is a string that specifies the delimiters.
• In the third version, if delimAsToken is true, then the delimiters are also returned
as tokens when the string is parsed.
StringTokenizer to parse “key=value” pairs
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo {
String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=2007";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "t" + val);
} } }
The output from this program is shown here:
title Java: The Complete Reference
author Schildt
publisher Osborne/McGraw-Hill
copyright 2007
Java program that reads a line of integers, and displays each integer, and the sum
of all the integers
import java.util.*;
class StringTokenizerDemo {
public static void main(String args[]) {
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers
with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new
StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the
integers is: " + sum);
}
}
OUTPUT:
Enter integers with one space gap:
10 20 30 40 50
10 20 30 40 50
sum of the integers is: 150
java.util.Date class
• The java.util.Date class represents date and time in
java. It provides constructors and methods to deal
with date and time in java.
• java.util.Date Constructors
• Date() : Creates date object representing current
date and time.
• Date(int year, int month, int date)
• Deprecated. As of JDK version 1.1, replaced
by Calendar.set(year + 1900, month,
date) or GregorianCalendar(year + 1900, month,
date).
java.util.Date class
// Program to demonstrate methods of
Date class
import java.util.*;
public class DateDemo {
public static void main(String[] args) {
// Creating date
Date d1 = new Date(2000, 11, 21);
Date d2 = new Date(); // Current date
Date d3 = new Date(2010, 1, 3);
boolean a = d3.after(d1);
System.out.println("Date d1 " + d1);
System.out.println("Date d2 " + d2);
System.out.println("Date d3 " + d3);
System.out.println("Date d3 comes after
" + "date d1: " + a);
boolean b = d3.before(d2);
System.out.println("Date d3 comes
before "+ "date d2: " + b);
int c = d1.compareTo(d2);
System.out.println(c);
} }
Output:
Date d1 Fri Dec 21 00:00:00 IST 3900
Date d2 Mon Nov 28 13:09:03 IST 2022
Date d3 Thu Feb 03 00:00:00 IST 3910
Date d3 comes after date d1: true
Date d3 comes before date d2: false
1
int compareTo(Date date)
Compares the value of the invoking
object with that of date. Returns 0 if
the values are equal. Returns a
negative value if the invoking object is
earlier than date. Returns a positive
value if the invoking object is later
than date.
Java Calendar Class
• Java Calendar class is an abstract class
that provides methods for converting
date between a specific instant in
time and a set of calendar fields such
as MONTH, YEAR, HOUR, etc.
• It inherits Object class and
implements the Comparable
interface.
Output:
Sun Jul 29 07:42:05 PDT 2018
Thu Jul 29 07:42:05 PDT 2027
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
import java.util.Calendar;
public class CalendaraddExample {
public static void main(String[] args) {
// create a new calendar
Calendar cal = Calendar.getInstance();
// print the current date and time
System.out.println("" + cal.getTime());
// add 9 years
cal.add((Calendar.YEAR), 9);
// print the modified date and time
System.out.println("" + cal.getTime());
System.out.println("Current Calendar's Year: " +
calendar.get(Cal.YEAR));
System.out.println("Current Calendar's Day: " +
calendar.get(Cal.DATE));
System.out.println("Current MINUTE: " +
calendar.get(Cal.MINUTE));
System.out.println("Current SECOND: " +
calendar.get(Cal.SECOND));
}
}
Types of Streams
• In Java, a stream is a path along which the data flows. Every stream has
a source and a destination.
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's
called a stream because it is like a stream of water that continues to flow.
OutputStream
• Java application uses an output stream to write data to a destination; it
may be a file, an array, peripheral device or socket.
• InputStream
• Java application uses an input stream to read data from a source; it may be
a file, an array, peripheral device or socket.
• While an Writing streams writes data into a source(file) , an Reading
streams is used to read data from a source(file).
• The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data.
• These classes may be categorized into two groups based on the data type
on which they operate.
• Byte stream classes
• Character stream classes
U-III Prt-2.pptx0 for Java and hardware coding...
Byte Stream Classes
• Byte stream classes have been designed to provide functional
features for creating and manipulating streams and files for
reading and writing bytes.
• Java provides two kinds of byte stream classes: input stream
classes and output stream classes.
• The super class InputStream is an abstract class, and, therefore,
we cannot create instances of this class. Rather, we must use the
subclasses that inherit from this class.
• The super class OutputStream is an abstract class and therefore
we cannot instantiate it. The several subclasses of the
OutputStream can be used for performing the output operations.
Character Stream Classes
• Character streams can be used to read and write 16-bit Unicode
characters. Like byte streams, there are two kinds of character stream
classes, namely, reader stream classes and writer stream classes.
• The Reader class is the superclass for all character-oriented input stream
classes. Being an abstract class, the Reader class cannot be instantiated
hence its subclasses are used.
• Reader stream classes are functionally very similar to the input stream
classes, except input streams use bytes as their fundamental unit of
information, while reader streams use characters.
• The Writer class is an abstract class which acts as a base class for all the
other writer stream classes.
U-III Prt-2.pptx0 for Java and hardware coding...
Standard Streams
• All Java programs automatically import the java.lang package. This package
defines a class called System.
• System also contains three predefined stream variables: in, out, and err.
• These fields are declared as public, static, and final within System. This
means that they can be used by any other part of your program and
without reference to a specific System object.
• Java provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually
a keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output stream
and represented as System.out.
• Standard Error − This is used to output the error data produced by the
user's program and usually a computer screen is used for standard error
stream and represented as System.err.
• System.in is an object of type InputStream.
• System.out and System.err are objects of type PrintStream.
Reading Console Input
• The preferred method of reading console input is to use a character-oriented stream,
which makes your program easier to internationalize and maintain.
• In Java, console input is accomplished by reading from System.in. To obtain a
character based stream that is attached to the console, wrap System.in in a
BufferedReader object.
• BufferedReader supports a buffered input stream. Its most commonly used
constructor is shown here:
BufferedReader(Reader inputReader)
• Here, inputReader is the stream that is linked to the instance of BufferedReader that
is being created.
• Reader is an abstract class. One of its concrete subclasses is InputStreamReader.
• To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:
InputStreamReader(InputStream inputStream)
• Because System.in refers to an object of type InputStream, it can be used for
inputStream.
• Putting it all together, the following line of code creates a BufferedReader that is
connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
• After this statement executes, br is a character-based stream that is linked to the
console through System.in.
Use a BufferedReader to read characters from the console.
• int read( ) throws IOException : it reads a character from the input stream and
returns it as an integer value.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run:
Enter characters, 'q' to
quit.
123abcq
1
2
3
a
b
c
q
Read a string from console using a BufferedReader.
String readLine( ) throws IOException: To read a
string from the keyboard, use the version of
readLine( ) that is a member of the
BufferedReader class.
import java.io.*;
class BRReadLines
{
public static void main(String args[]) throws
IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
} }
Output:
Enter text.
Enter 'stop' to quit.
abc
abc
xyz
xyz
stop
stop
BufferedWriter Class
BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing
the efficient writing of single arrays, characters, and strings.
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to File writing.");
buffer.close();
System.out.println("Success");
}
}
Output:
success
A new file testout.txt is created and If you open you will find the below text in the file:
Welcome to File writing.
The PrintWriter Class
• PrintWriter supports the print( ) and println( ) methods for all types
including Object.
• Thus, you can use these methods with System.out.
• If an argument is not a simple type, the PrintWriter methods call the
object’s toString( ) method and then print the result.
• For real-world programs, the recommended method of writing to the
console when using Java is through a PrintWriter stream.
• PrintWriter is one of the character-based classes.
• Using a character-based class for console output makes it easier to
internationalize your program.
Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
} }
The output from this program is shown here:
This is a string
-7
4.5E-7
Java FileInputStream Class
• Java FileInputStream class obtains input bytes from a file. It is used
for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.
• For reading streams of characters, it is recommended to use
FileReader class.
• The declaration for java.io.FileInputStream class:
public class FileInputStream extends InputStream
• Its two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObj)
• Either can throw a FileNotFoundException. Here, filepath is the full
path name of a file, and
• fileObj is a File object that describes the file.
Java FileInputStream Class
import java.io.*;
class ReadFile {
public static void main(String args[]) throws IOException {
//attach the file to FileInputStream
FileInputStream fin= new FileInputStream("file1.txt");
//illustrating getChannel() method
System.out.println(fin.getChannel());
//illustrating getFD() method
System.out.println(fin.getFD());
//illustrating available method
System.out.println("Number of remaining bytes:"+fin.available());
//illustrating skip method
fin.skip(4);
System.out.println("FileContents :");
//read characters from FileInputStream and write them
int ch;
while((ch=fin.read())!=-1)
System.out.print((char)ch);
//close the file
fin.close(); }
ChannelImpl@1db974
java.io.FileDescriptor@10
6d69c
Number of remaining
bytes:38
FileContents :
efgh
ijkl
mnop
qrst
uvwx
yz
FileOutputStream
• Java FileOutputStream is an output stream
used for writing data to a file.
• If you have to write primitive values into a file,
use FileOutputStream class.
• But, for character-oriented data, it is preferred
to use FileWriter.
FileOutputStream
public void write(byte[])throws IOException
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("testout.txt");
String s="Welcome to java";
byte b[]=s.getBytes(); //converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to java.
testout.txt
Welcome to java.
Copying files or Reading and Writing Binary Files Using FileInputStream and FileOutputStream
import java.io.*;
public class CopyFilesOne {
public static void main(String[] args) {
if (args.length < 2)
System.out.println("Please provide input and output files");
String inputFile = args[0];
String outputFile = args[1];
try {
InputStream inputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile);
long fileSize = new File(inputFile).length();
byte[] allBytes = new byte[(int) fileSize]; // bytearray of input file
inputStream.read(allBytes);
outputStream.write(allBytes);
} catch (IOException ex) {
ex.printStackTrace();
} } }
U-III Prt-2.pptx0 for Java and hardware coding...
Files
• The File class is an abstract representation of
file and directory pathname. A pathname can
be either absolute or relative.
• The File class have several methods for
working with directories and files such as
creating new directories or files, deleting and
renaming directories or files, listing the
contents of a directory etc.
Files
• File(File parent, String child): It creates a new File instance
from a parent abstract pathname and a child pathname
string.
• File(String pathname):I t creates a new File instance by
converting the given pathname string into an abstract
pathname.
• File(String parent, String child): It creates a new File
instance from a parent pathname string and a child
pathname string.
• File(URI uri): I t creates a new File instance by converting
the given file: URI into an abstract pathname.
File Class methods program
// Demonstrate File.
import java.io.File;
class FileDemo {
static void p(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" :
"might be directory");
p("File last modified: " +
f1.lastModified());
p("File size: " + f1.length() + "
Bytes");
} }
Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: c:/java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified:
812465204000
File size: 695 Bytes
Serialization and Deserialization in Java
• Serialization is a mechanism of converting the state of an object into a byte
stream.
• Deserialization is the reverse process where the byte stream is used to recreate
the actual Java object in memory. This mechanism is used to persist the object.
• The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform.
• To make a Java object serializable we implement java.io.Serializable interface.
• The ObjectOutputStream class contains writeObject() method for serializing an
Object.
public final void writeObject(Object obj) throws IOException.
• The ObjectInputStream class contains readObject() method for deserializing an
object.
public final Object readObject() throws IOException, ClassNotFoundException
• Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
Serialization and Deserialization in Java
• The following code serializes a Demo object to a file named ‘file.txt’.
• And the following code deserializes a Demo object.
Here are some examples of using serialization:
• - Storing data in an object-oriented way to files on disk, e.g. storing a list
of Student objects.
• - Saving program’s states on disk, e.g. saving state of a game.
• - Sending data over the network in form objects, e.g. sending messages as objects
in chat application.
Serialization and Deserialization in Java
// Java code for serialization and deserialization of a Java object
import java.io.*;
class Demo implements java.io.Serializable {
public int a;
public String b;
// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
} }
class Test {
public static void main(String[] args) {
Demo Demoobject = new Demo(1, “CSE-A");
String filename = "file.txt";
// Serialization
try {
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of object
out.writeObject(Demoobject);
out.close();
file.close();
System.out.println("Object has been serialized"); }
Serialization and Deserialization in Java
catch(IOException ex) { System.out.println("IOException is caught"); }
Demo Demoobject1 = null;
// Deserialization
try {
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
Demoobject1 = (Demo)in.readObject();
in.close(); file.close();
System.out.println("Object has been deserialized ");
System.out.println("a = " + Demoobject1.a);
System.out.println("b = " + Demoobject1.b);
} catch(IOException ex) {
System.out.println("IOException is caught"); }
catch(ClassNotFoundException ex)
{ System.out.println("ClassNotFoundException is caught");
} } }
Output:
Object has been serialized
Object has been deserialized
a = 1 b = CSE-A
Primitive Data types and their
Corresponding Wrapper class
value Of() method : We can use valueOf() method to create Wrapper object for given primitive or
String.
public static Wrapper valueOf(String s);
public static Wrapper valueOf(primitive p);
// Java program to illustrate valueof()
class ABC1{
public static void main(String[] args)
{
Integer I = Integer.valueOf(10);
Double D = Double.valueOf(10.5);
Character C = Character.valueOf('a');
System.out.println(I);
System.out.println(D);
System.out.println(C);
}
}
10
10.5
a
• xxxValue() method: We can use xxxValue() methods to get the primitive for
the given Wrapper Object.
• Every number type Wrapper class( Byte, Short, Integer, Long, Float, Double)
contains the following 6 methods to get primitive for the given Wrapper
object:
• public byte byteValue()
• public short shortValue()
• public int intValue()
• public long longValue()
• public float floatValue()
• public float doubleValue()
Java program to illustrate typeValue()
class GFG {
public static void main(String[] args)
{
Integer I = new Integer(130);
System.out.println(I.shortValue());
System.out.println(I.intValue());
System.out.println(I.longValue());
System.out.println(I.floatValue());
System.out.println(I.doubleValue());
}
}
Output:
130
130
130
130.0
130.0
parseXxx() method : We can use parseXxx()
methods to convert String to primitive.
// Java program to illustrate parseXxx()
class ABC {
public static void main(String[] args)
{
int i = Integer.parseInt("10");
double d = Double.parseDouble("10.5");
System.out.println(i);
System.out.println(d);
}
}
10
10.5

More Related Content

PPS
Packages and inbuilt classes of java
PPTX
JAVA (UNIT 3)
PPT
Core java day1
PPT
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
PPT
Java stream
PPTX
Reading and writting v2
PPTX
Java Programming Comprehensive Guide.pptx
PDF
Lecture3.pdf
Packages and inbuilt classes of java
JAVA (UNIT 3)
Core java day1
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
Java stream
Reading and writting v2
Java Programming Comprehensive Guide.pptx
Lecture3.pdf

Similar to U-III Prt-2.pptx0 for Java and hardware coding... (20)

PPT
ppt on scanner class
PPTX
Buffer and scanner
PPTX
Stream In Java.pptx
PDF
Hp syllabus
PPTX
Java Basics 1.pptx
PDF
Core Java Volume I Fundamentals 12th Horstmann Cay
PDF
The Ultimate FREE Java Course Part 2
PPTX
L21 io streams
PPTX
OOP Using Java Ch2 all about oop .pptx
PPT
Basic elements of java
PPTX
Reading and writting
PPT
Chapter 2 - Getting Started with Java
PPT
Java căn bản - Chapter2
PDF
ch02-Java Fundamentals-Java Fundamentals.pdf
PPT
java tutorial 2
PPTX
Chapter 3.4
PPTX
Unit3 part3-packages and interfaces
DOCX
Class notes(week 5) on command line arguments
PDF
Programming in Java Unit 1 lesson Notes for Java
PDF
3.Lesson Plan - Input.pdf.pdf
ppt on scanner class
Buffer and scanner
Stream In Java.pptx
Hp syllabus
Java Basics 1.pptx
Core Java Volume I Fundamentals 12th Horstmann Cay
The Ultimate FREE Java Course Part 2
L21 io streams
OOP Using Java Ch2 all about oop .pptx
Basic elements of java
Reading and writting
Chapter 2 - Getting Started with Java
Java căn bản - Chapter2
ch02-Java Fundamentals-Java Fundamentals.pdf
java tutorial 2
Chapter 3.4
Unit3 part3-packages and interfaces
Class notes(week 5) on command line arguments
Programming in Java Unit 1 lesson Notes for Java
3.Lesson Plan - Input.pdf.pdf
Ad

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Structure & Organelles in detailed.
PDF
01-Introduction-to-Information-Management.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Sports Quiz easy sports quiz sports quiz
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Classroom Observation Tools for Teachers
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
GDM (1) (1).pptx small presentation for students
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
RMMM.pdf make it easy to upload and study
Cell Structure & Organelles in detailed.
01-Introduction-to-Information-Management.pdf
Basic Mud Logging Guide for educational purpose
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Sports Quiz easy sports quiz sports quiz
102 student loan defaulters named and shamed – Is someone you know on the list?
Classroom Observation Tools for Teachers
Microbial disease of the cardiovascular and lymphatic systems
GDM (1) (1).pptx small presentation for students
TR - Agricultural Crops Production NC III.pdf
Pre independence Education in Inndia.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Ad

U-III Prt-2.pptx0 for Java and hardware coding...

  • 1. U-III Other Utility classes: String Tokenizer, Date, Calendar, Gregorian Calendar, Scanner Java Input/Output: Exploring java.io, Java I/O classes and interfaces, File, Stream classes, byte stream, character stream, serialization
  • 2. java.util.Scanner • Scanner class in Java is found in the java.util package. • public final class Scanner extends Object implements Iterator<String>, Closeable • Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them. • The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values. • By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc. • To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example: Scanner in = new Scanner(System.in); •To get the instance of Java Scanner which parses the strings, we need to pass the strings in the constructor of Scanner class. For Example: Scanner in = new Scanner("Hello Javatpoint");
  • 3. Using Scanner class methods import java.util.*; public class ScannerClassExample { public static void main(String args[]) { String s = "Hello, This is Java class."; //Create scanner Object and pass string in it Scanner scan = new Scanner(s); //Check if the scanner has a token System.out.println("Boolean Result: " + scan.hasNext()); //Print the string System.out.println("String:”+scan.nextLine()); //Using scanner class methods to read string,int,float System.out.println("--------Enter Your Details--"); Scanner in = new Scanner(System.in); System.out.print("Enter your name: "); String name = in.nextLine(); System.out.println(" Name: “ +name); System.out.print("Enter your age: "); int i = in.nextInt(); System.out.println("Age: " + i); System.out.print("Enter your salary: "); double d = in.nextDouble(); System.out.println("Salary: " + d); } } Output: Boolean Result: true String: Hello, This is Java class. -------Enter Your Details--------- Enter your name: Abhishek Name: Abhishek Enter your age: 23 Age: 23 Enter your salary: 25000 Salary: 25000.0
  • 4. StringTokenizer • The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens. • StringTokenizer implements the Enumeration interface. • To use StringTokenizer, you specify an input string and a string that contains delimiters. • Delimiters are characters that separate tokensfor example, “,;:” sets the delimiters to a comma, semicolon,and colon. • The default set of delimiters consists of the whitespace characters: space, tab,newline, and carriage return. • The StringTokenizer constructors are shown here: • StringTokenizer(String str) • StringTokenizer(String str, String delimiters) • StringTokenizer(String str, String delimiters, boolean delimAsToken) • In all versions, str is the string that will be tokenized. • In the first version, the default delimiters are used. • In the second and third versions, delimiters is a string that specifies the delimiters. • In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed.
  • 5. StringTokenizer to parse “key=value” pairs // Demonstrate StringTokenizer. import java.util.StringTokenizer; class STDemo { String in = "title=Java: The Complete Reference;" + "author=Schildt;" + "publisher=Osborne/McGraw-Hill;" + "copyright=2007"; public static void main(String args[]) { StringTokenizer st = new StringTokenizer(in, "=;"); while(st.hasMoreTokens()) { String key = st.nextToken(); String val = st.nextToken(); System.out.println(key + "t" + val); } } } The output from this program is shown here: title Java: The Complete Reference author Schildt publisher Osborne/McGraw-Hill copyright 2007
  • 6. Java program that reads a line of integers, and displays each integer, and the sum of all the integers import java.util.*; class StringTokenizerDemo { public static void main(String args[]) { int n; int sum = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter integers with one space gap:"); String s = sc.nextLine(); StringTokenizer st = new StringTokenizer(s, " "); while (st.hasMoreTokens()) { String temp = st.nextToken(); n = Integer.parseInt(temp); System.out.println(n); sum = sum + n; } System.out.println("sum of the integers is: " + sum); } } OUTPUT: Enter integers with one space gap: 10 20 30 40 50 10 20 30 40 50 sum of the integers is: 150
  • 7. java.util.Date class • The java.util.Date class represents date and time in java. It provides constructors and methods to deal with date and time in java. • java.util.Date Constructors • Date() : Creates date object representing current date and time. • Date(int year, int month, int date) • Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
  • 8. java.util.Date class // Program to demonstrate methods of Date class import java.util.*; public class DateDemo { public static void main(String[] args) { // Creating date Date d1 = new Date(2000, 11, 21); Date d2 = new Date(); // Current date Date d3 = new Date(2010, 1, 3); boolean a = d3.after(d1); System.out.println("Date d1 " + d1); System.out.println("Date d2 " + d2); System.out.println("Date d3 " + d3); System.out.println("Date d3 comes after " + "date d1: " + a); boolean b = d3.before(d2); System.out.println("Date d3 comes before "+ "date d2: " + b); int c = d1.compareTo(d2); System.out.println(c); } } Output: Date d1 Fri Dec 21 00:00:00 IST 3900 Date d2 Mon Nov 28 13:09:03 IST 2022 Date d3 Thu Feb 03 00:00:00 IST 3910 Date d3 comes after date d1: true Date d3 comes before date d2: false 1 int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
  • 9. Java Calendar Class • Java Calendar class is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. • It inherits Object class and implements the Comparable interface. Output: Sun Jul 29 07:42:05 PDT 2018 Thu Jul 29 07:42:05 PDT 2027 Current Calendar's Year: 2018 Current Calendar's Day: 28 Current MINUTE: 10 Current SECOND: 45 import java.util.Calendar; public class CalendaraddExample { public static void main(String[] args) { // create a new calendar Calendar cal = Calendar.getInstance(); // print the current date and time System.out.println("" + cal.getTime()); // add 9 years cal.add((Calendar.YEAR), 9); // print the modified date and time System.out.println("" + cal.getTime()); System.out.println("Current Calendar's Year: " + calendar.get(Cal.YEAR)); System.out.println("Current Calendar's Day: " + calendar.get(Cal.DATE)); System.out.println("Current MINUTE: " + calendar.get(Cal.MINUTE)); System.out.println("Current SECOND: " + calendar.get(Cal.SECOND)); } }
  • 10. Types of Streams • In Java, a stream is a path along which the data flows. Every stream has a source and a destination. • A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. OutputStream • Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket. • InputStream • Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket. • While an Writing streams writes data into a source(file) , an Reading streams is used to read data from a source(file). • The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. • These classes may be categorized into two groups based on the data type on which they operate. • Byte stream classes • Character stream classes
  • 12. Byte Stream Classes • Byte stream classes have been designed to provide functional features for creating and manipulating streams and files for reading and writing bytes. • Java provides two kinds of byte stream classes: input stream classes and output stream classes. • The super class InputStream is an abstract class, and, therefore, we cannot create instances of this class. Rather, we must use the subclasses that inherit from this class. • The super class OutputStream is an abstract class and therefore we cannot instantiate it. The several subclasses of the OutputStream can be used for performing the output operations.
  • 13. Character Stream Classes • Character streams can be used to read and write 16-bit Unicode characters. Like byte streams, there are two kinds of character stream classes, namely, reader stream classes and writer stream classes. • The Reader class is the superclass for all character-oriented input stream classes. Being an abstract class, the Reader class cannot be instantiated hence its subclasses are used. • Reader stream classes are functionally very similar to the input stream classes, except input streams use bytes as their fundamental unit of information, while reader streams use characters. • The Writer class is an abstract class which acts as a base class for all the other writer stream classes.
  • 15. Standard Streams • All Java programs automatically import the java.lang package. This package defines a class called System. • System also contains three predefined stream variables: in, out, and err. • These fields are declared as public, static, and final within System. This means that they can be used by any other part of your program and without reference to a specific System object. • Java provides the following three standard streams − • Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in. • Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out. • Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err. • System.in is an object of type InputStream. • System.out and System.err are objects of type PrintStream.
  • 16. Reading Console Input • The preferred method of reading console input is to use a character-oriented stream, which makes your program easier to internationalize and maintain. • In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. • BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here: BufferedReader(Reader inputReader) • Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. • Reader is an abstract class. One of its concrete subclasses is InputStreamReader. • To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) • Because System.in refers to an object of type InputStream, it can be used for inputStream. • Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); • After this statement executes, br is a character-based stream that is linked to the console through System.in.
  • 17. Use a BufferedReader to read characters from the console. • int read( ) throws IOException : it reads a character from the input stream and returns it as an integer value. import java.io.*; class BRRead { public static void main(String args[]) throws IOException { char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } } Here is a sample run: Enter characters, 'q' to quit. 123abcq 1 2 3 a b c q
  • 18. Read a string from console using a BufferedReader. String readLine( ) throws IOException: To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } } Output: Enter text. Enter 'stop' to quit. abc abc xyz xyz stop stop
  • 19. BufferedWriter Class BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings. import java.io.*; public class BufferedWriterExample { public static void main(String[] args) throws Exception { FileWriter writer = new FileWriter("D:testout.txt"); BufferedWriter buffer = new BufferedWriter(writer); buffer.write("Welcome to File writing."); buffer.close(); System.out.println("Success"); } } Output: success A new file testout.txt is created and If you open you will find the below text in the file: Welcome to File writing.
  • 20. The PrintWriter Class • PrintWriter supports the print( ) and println( ) methods for all types including Object. • Thus, you can use these methods with System.out. • If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result. • For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. • PrintWriter is one of the character-based classes. • Using a character-based class for console output makes it easier to internationalize your program.
  • 21. Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } } The output from this program is shown here: This is a string -7 4.5E-7
  • 22. Java FileInputStream Class • Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. • For reading streams of characters, it is recommended to use FileReader class. • The declaration for java.io.FileInputStream class: public class FileInputStream extends InputStream • Its two most common constructors are shown here: FileInputStream(String filepath) FileInputStream(File fileObj) • Either can throw a FileNotFoundException. Here, filepath is the full path name of a file, and • fileObj is a File object that describes the file.
  • 23. Java FileInputStream Class import java.io.*; class ReadFile { public static void main(String args[]) throws IOException { //attach the file to FileInputStream FileInputStream fin= new FileInputStream("file1.txt"); //illustrating getChannel() method System.out.println(fin.getChannel()); //illustrating getFD() method System.out.println(fin.getFD()); //illustrating available method System.out.println("Number of remaining bytes:"+fin.available()); //illustrating skip method fin.skip(4); System.out.println("FileContents :"); //read characters from FileInputStream and write them int ch; while((ch=fin.read())!=-1) System.out.print((char)ch); //close the file fin.close(); } ChannelImpl@1db974 java.io.FileDescriptor@10 6d69c Number of remaining bytes:38 FileContents : efgh ijkl mnop qrst uvwx yz
  • 24. FileOutputStream • Java FileOutputStream is an output stream used for writing data to a file. • If you have to write primitive values into a file, use FileOutputStream class. • But, for character-oriented data, it is preferred to use FileWriter.
  • 25. FileOutputStream public void write(byte[])throws IOException import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]){ try{ FileOutputStream fout=new FileOutputStream("testout.txt"); String s="Welcome to java"; byte b[]=s.getBytes(); //converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); }catch(Exception e){System.out.println(e);} } } Output: Success... The content of a text file testout.txt is set with the data Welcome to java. testout.txt Welcome to java.
  • 26. Copying files or Reading and Writing Binary Files Using FileInputStream and FileOutputStream import java.io.*; public class CopyFilesOne { public static void main(String[] args) { if (args.length < 2) System.out.println("Please provide input and output files"); String inputFile = args[0]; String outputFile = args[1]; try { InputStream inputStream = new FileInputStream(inputFile); OutputStream outputStream = new FileOutputStream(outputFile); long fileSize = new File(inputFile).length(); byte[] allBytes = new byte[(int) fileSize]; // bytearray of input file inputStream.read(allBytes); outputStream.write(allBytes); } catch (IOException ex) { ex.printStackTrace(); } } }
  • 28. Files • The File class is an abstract representation of file and directory pathname. A pathname can be either absolute or relative. • The File class have several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
  • 29. Files • File(File parent, String child): It creates a new File instance from a parent abstract pathname and a child pathname string. • File(String pathname):I t creates a new File instance by converting the given pathname string into an abstract pathname. • File(String parent, String child): It creates a new File instance from a parent pathname string and a child pathname string. • File(URI uri): I t creates a new File instance by converting the given file: URI into an abstract pathname.
  • 30. File Class methods program // Demonstrate File. import java.io.File; class FileDemo { static void p(String s) { System.out.println(s); } public static void main(String args[]) { File f1 = new File("/java/COPYRIGHT"); p("File Name: " + f1.getName()); p("Path: " + f1.getPath()); p("Abs Path: " + f1.getAbsolutePath()); p("Parent: " + f1.getParent()); p(f1.exists() ? "exists" : "does not exist"); p(f1.canWrite() ? "is writeable" : "is not writeable"); p(f1.canRead() ? "is readable" : "is not readable"); p("is " + (f1.isDirectory() ? "" : "not" + " a directory")); p(f1.isFile() ? "is normal file" : "might be directory"); p("File last modified: " + f1.lastModified()); p("File size: " + f1.length() + " Bytes"); } } Name: COPYRIGHT Path: /java/COPYRIGHT Abs Path: c:/java/COPYRIGHT Parent: /java exists is writeable is readable is not a directory is normal file is absolute File last modified: 812465204000 File size: 695 Bytes
  • 31. Serialization and Deserialization in Java • Serialization is a mechanism of converting the state of an object into a byte stream. • Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. • The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform. • To make a Java object serializable we implement java.io.Serializable interface. • The ObjectOutputStream class contains writeObject() method for serializing an Object. public final void writeObject(Object obj) throws IOException. • The ObjectInputStream class contains readObject() method for deserializing an object. public final Object readObject() throws IOException, ClassNotFoundException • Advantages of Serialization 1. To save/persist state of an object. 2. To travel an object across a network.
  • 32. Serialization and Deserialization in Java • The following code serializes a Demo object to a file named ‘file.txt’. • And the following code deserializes a Demo object. Here are some examples of using serialization: • - Storing data in an object-oriented way to files on disk, e.g. storing a list of Student objects. • - Saving program’s states on disk, e.g. saving state of a game. • - Sending data over the network in form objects, e.g. sending messages as objects in chat application.
  • 33. Serialization and Deserialization in Java // Java code for serialization and deserialization of a Java object import java.io.*; class Demo implements java.io.Serializable { public int a; public String b; // Default constructor public Demo(int a, String b) { this.a = a; this.b = b; } } class Test { public static void main(String[] args) { Demo Demoobject = new Demo(1, “CSE-A"); String filename = "file.txt"; // Serialization try { //Saving of object in a file FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); // Method for serialization of object out.writeObject(Demoobject); out.close(); file.close(); System.out.println("Object has been serialized"); }
  • 34. Serialization and Deserialization in Java catch(IOException ex) { System.out.println("IOException is caught"); } Demo Demoobject1 = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); // Method for deserialization of object Demoobject1 = (Demo)in.readObject(); in.close(); file.close(); System.out.println("Object has been deserialized "); System.out.println("a = " + Demoobject1.a); System.out.println("b = " + Demoobject1.b); } catch(IOException ex) { System.out.println("IOException is caught"); } catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException is caught"); } } } Output: Object has been serialized Object has been deserialized a = 1 b = CSE-A
  • 35. Primitive Data types and their Corresponding Wrapper class
  • 36. value Of() method : We can use valueOf() method to create Wrapper object for given primitive or String. public static Wrapper valueOf(String s); public static Wrapper valueOf(primitive p); // Java program to illustrate valueof() class ABC1{ public static void main(String[] args) { Integer I = Integer.valueOf(10); Double D = Double.valueOf(10.5); Character C = Character.valueOf('a'); System.out.println(I); System.out.println(D); System.out.println(C); } } 10 10.5 a
  • 37. • xxxValue() method: We can use xxxValue() methods to get the primitive for the given Wrapper Object. • Every number type Wrapper class( Byte, Short, Integer, Long, Float, Double) contains the following 6 methods to get primitive for the given Wrapper object: • public byte byteValue() • public short shortValue() • public int intValue() • public long longValue() • public float floatValue() • public float doubleValue()
  • 38. Java program to illustrate typeValue() class GFG { public static void main(String[] args) { Integer I = new Integer(130); System.out.println(I.shortValue()); System.out.println(I.intValue()); System.out.println(I.longValue()); System.out.println(I.floatValue()); System.out.println(I.doubleValue()); } } Output: 130 130 130 130.0 130.0
  • 39. parseXxx() method : We can use parseXxx() methods to convert String to primitive. // Java program to illustrate parseXxx() class ABC { public static void main(String[] args) { int i = Integer.parseInt("10"); double d = Double.parseDouble("10.5"); System.out.println(i); System.out.println(d); } } 10 10.5

Editor's Notes

  • #7: The close() method closes an open file. You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
  • #9: In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used: A year y is represented by the integer y - 1900. A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December. A date (day of month) is represented by an integer from 1 to 31 in the usual manner. An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12. A minute is represented by an integer from 0 to 59 in the usual manner. A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.
  • #11: The difference between Date and Calendar is that Date class operates with specific instant in time and Calendar operates with difference between two dates. The Calendar class gives you possibility for converting between a specific instant in time and a set of calendar fields such as HOUR, YEAR, MONTH, DAY_OF_MONTH
  • #13: FilterInputStream class implements the InputStream. It contains different sub classes as BufferedInputStream, DataInputStream for providing additional functionality. public class FilterOutputStream extends OutputStream   public class FileReader extends InputStreamReader  
  • #14: Pipes in Java IO provides the ability for two threads running in the same JVM to communicate. Therefore pipes can also be sources or destinations of data. The Java SequenceInputStream combines two or more other InputStream's into one. First the SequenceInputStream will read all bytes from the first InputStream, then all bytes from the second InputStream. That is the reason it is called a SequenceInputStream. Filtered streams are simply wrappers around underlying input or output streams that transparently provide some extended level of functionality. Typical extensions are buffering, character translation, and raw data translation.  
  • #18: Like output stream classes, the writer stream classes are designed to perform all output operations on files.
  • #20: These are byte streams, even though they typically are used to read and write characters from and to the console.
  • #23: Today, using a byte stream to read console input is still technically possible, but doing so is not recommended. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.
  • #27: PrintWriter(OutputStream outputStream, boolean flushOnNewline) outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewline istrue, flushing automatically takes place. If false, flushing is not automatic
  • #33: Defines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations NIO: New Input/Output
  • #35: binary files can also mean that they contain images, sounds, compressed versions.
  • #50: On the table in front of you. you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible. What you need is a way of instantly deciding which box you have put each object in. It works like an index. you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it. Now imagine that you don't want to bother with the index, you want to be able to find out immediately from the object which box it lives in. In the example, let's use a really simple way of doing this - the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. What about the rhinoceros, though? It has 10 characters, so we'll change our algorithm a little and "wrap around" so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object. Sometimes a box will have more than one object in it, but if you are looking for a rocket, it's still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas, banjos, and rhinoceroses. That's a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java, a hash code can be any integer, and each object type is responsible for generating its own. Lookup the "hashCode" method of Object.