All Implemented Interfaces:: Java - Util.Stringtokenizer
All Implemented Interfaces:: Java - Util.Stringtokenizer
• java.lang.Object
• java.util.StringTokenizer
The string tokenizer class allows an application to break a string into tokens. The tokenization
method is much simpler than the one used by the StreamTokenizer class.
The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor
do they recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at creation time or
on a per-token basis.
An instance of StringTokenizer behaves in one of two ways, depending on whether it was created
with the returnDelims flag having the value true or false:
• If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of
consecutive characters that are not delimiters.
• If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either
one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some
operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
The following is one example of the use of the tokenizer. The code:
The following example illustrates how the String.split method can be used to break up a string into
its basic tokens:
this
is
a
test
Constructor Summary
Method Summary
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Constructor Detail
StringTokenizer
• public StringTokenizer(String str, String delim, boolean returnDelims)
Constructs a string tokenizer for the specified string. All characters in the delim argument are the
delimiters for separating tokens.
If the returnDelims flag is true, then the delimiter characters are also returned as tokens. Each
delimiter is returned as a string of length one. If the flag is false, the delimiter characters are skipped
and only serve as separators between tokens.
Note that if delim is null, this constructor does not throw an exception. However, trying to invoke
other methods on the resulting StringTokenizer may result in a NullPointerException.
Parameters:
str - a string to be parsed.
delim - the delimiters.
returnDelims - flag indicating whether to return the delimiters as tokens.
Throws:
NullPointerException - if str is null
StringTokenizer
Constructs a string tokenizer for the specified string. The characters in the delim argument are the
delimiters for separating tokens. Delimiter characters themselves will not be treated as tokens.
Note that if delim is null, this constructor does not throw an exception. However, trying to invoke
other methods on the resulting StringTokenizer may result in a NullPointerException.
Parameters:
str - a string to be parsed.
delim - the delimiters.
Throws:
NullPointerException - if str is null
StringTokenizer
public StringTokenizer(String str)
Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set,
which is " \t\n\r\f": the space character, the tab character, the newline character, the carriage-return
character, and the form-feed character. Delimiter characters themselves will not be treated as tokens.
Parameters:
str - a string to be parsed.
Throws:
NullPointerException - if str is null
Method Detail:
• hasMoreTokens
• nextToken
• hasMoreElements
• nextElement
• countTokens
public int countTokens()
Calculates the number of times that this tokenizer's nextToken method can be called before it
generates an exception. The current position is not advanced.
Returns:
the number of tokens remaining in the string using the current delimiter set.
he Date class, located in the java.util package, represents a specific instant in time, with millisecond
precision. It is important to note that the Date class has been mostly replaced by the more modern
and comprehensive date and time API introduced in Java 8, which is part of the java.time package.
However, let's go over the Date class to understand its basic functionality:
Using java.util.Date:
1. Creation of Date objects: You can create a Date object representing the current date and
time or a specific date using its various constructors.
import java.util.Date;
// Creating a Date object with a specific timestamp (milliseconds since January 1, 1970, 00:00:00 GMT)
Date specificDate = new Date(1625241600000L); // July 2, 2021, 00:00:00 GMT
System.out.println("Specific Date: " + specificDate);
}
}
The Date class represents the date and time as the number of milliseconds since January 1, 1970,
00:00:00 GMT (the epoch). The long value passed to the constructor in the second example
represents the milliseconds elapsed since the epoch.
Common methods: The Date class provides various methods to work with dates. Some common
methods include:
• getTime(): Returns the number of milliseconds since the epoch.
• toString(): Returns a string representation of the date.
• before(Date when) and after(Date when): Compare two dates.
if (date1.before(date2)) {
System.out.println("Date 1 is before Date 2.");
} else {
System.out.println("Date 1 is after Date 2.");
}
Using java.time.LocalDate (Java 8 and later):
The java.time.LocalDate class provides a more modern and comprehensive way to represent a date
without the time component. It is immutable and provides numerous methods for date manipulation.
import java.time.LocalDate;
In Java, the Calendar class is part of the older date and time API in the java.util package. It
provides methods for working with dates, times, and time intervals. However, it's important to note
that the Calendar class has some limitations, and for more modern and flexible date and time
handling, the java.time package introduced in Java 8 is recommended.
Here's a basic example using the Calendar class:
import java.util.Calendar;
GregorianCalendar:
In Java, the GregorianCalendar class is a concrete implementation of the Calendar class and
represents the Gregorian calendar system. It provides methods for working with dates, times, and
time intervals. Here's a basic example using GregorianCalendar:
import java.util.GregorianCalendar;
Scanner:
The Scanner class in Java, which is part of the java.util package, provides a convenient way to parse
and read primitive data types and strings from various input sources. It is commonly used for reading
input from the console, files, or other input streams.
Here's an overview of the Scanner class:
1. Creating a Scanner Object:
You can create a Scanner object by passing an input source to its constructor. Common input
sources include System.in for reading from the console and File objects for reading from files.
import java.util.Scanner;
The next() method reads the next token (a sequence of characters separated by whitespace), and
nextLine() reads the entire line.
3. Handling Input Mismatch:
It's important to handle input mismatch exceptions when the user enters data of the wrong type.
4. Delimiter Customization:
By default, the Scanner uses whitespace as the delimiter. You can customize the delimiter to match
specific patterns.
scanner.close();
import java.util.Scanner;
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close();
}
}
In this example, the program prompts the user to enter their name and age, reads the input using a
Scanner.
Input/Output:
In Java, the java.io package provides classes for handling input and output operations. This package
includes a variety of classes and interfaces that allow you to work with files, streams, readers, and
writers.
Here's an overview of some key classes and interfaces in java.io:
1. InputStream and OutputStream:
• InputStream: This is an abstract class representing input streams of bytes. It's the superclass
of all classes representing input streams of bytes, such as FileInputStream and
ByteArrayInputStream.
• OutputStream: This is an abstract class representing output streams of bytes. It's the
superclass of all classes representing output streams of bytes, such as FileOutputStream and
ByteArrayOutputStream.
2. Reader and Writer:
• Reader: This is an abstract class representing input streams of characters. It's the superclass
of all classes representing input streams of characters, such as FileReader and StringReader.
• Writer: This is an abstract class representing output streams of characters. It's the superclass
of all classes representing output streams of characters, such as FileWriter and
StringWriter.
3. File Input and Output:
• File: Represents a file or directory path. You can use File to create, delete, or query
information about files and directories.
• FileInputStream and FileOutputStream: These classes are used for reading and writing
binary data to and from files.
4. Buffered Input and Output:
• BufferedReader and BufferedWriter: These classes provide buffering for reading and
writing characters, which can improve efficiency.
• BufferedInputStream and BufferedOutputStream: These classes provide buffering for
reading and writing binary data, which can enhance performance.
5. Data Input and Output:
• DataInputStream and DataOutputStream: These classes allow the reading and writing of
primitive data types (int, float, double, etc.) in a portable way.
6. Object Input and Output:
• ObjectInputStream and ObjectOutputStream: These classes allow the serialization and
deserialization of objects. They can be used to save and restore the state of objects.
Example: Reading from a File and Writing to a File:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
1. File Class:
The File class in Java represents a file or directory path. It provides methods to create, delete, or
query information about files and directories.
Example:
import java.io.File;
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
•
Character Streams (Reader and Writer):
• Deal with characters and provide higher-level abstractions for text-based I/O.
• FileReader and FileWriter are used for reading and writing characters from/to files.
Example:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
int data;
while ((data = reader.read()) != -1) {
writer.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. Serialization:
Serialization is the process of converting an object into a stream of bytes to store the object or
transmit it to memory, a database, or a file. Deserialization is the reverse process.
• ObjectInputStream and ObjectOutputStream:
• Used for reading and writing objects to streams.
• Objects must implement the Serializable interface.
import java.io.*;
// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person restoredPerson = (Person) ois.readObject();
System.out.println("Name: " + restoredPerson.name + ", Age: " + restoredPerson.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
In this example, the Person class is serialized to a file using ObjectOutputStream, and then it is
deserialized back using ObjectInputStream.