0% found this document useful (0 votes)
10 views12 pages

All Implemented Interfaces:: Java - Util.Stringtokenizer

The StringTokenizer class in Java allows for breaking a string into tokens using specified delimiters, with options to treat delimiters as tokens or not. Although it is a legacy class, its functionality is largely replaced by the String.split method and the java.util.regex package. The document also covers the Date, LocalDate, Calendar, and Scanner classes, highlighting their usage and modern alternatives in date and time handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

All Implemented Interfaces:: Java - Util.Stringtokenizer

The StringTokenizer class in Java allows for breaking a string into tokens using specified delimiters, with options to treat delimiters as tokens or not. Although it is a legacy class, its functionality is largely replaced by the String.split method and the java.util.regex package. The document also covers the Date, LocalDate, Calendar, and Scanner classes, highlighting their usage and modern alternatives in date and time handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Class StringTokenizer

• java.lang.Object
• java.util.StringTokenizer

• All Implemented Interfaces:


Enumeration<Object>

public class StringTokenizer


extends Object
implements Enumeration<Object>

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:

StringTokenizer st = new StringTokenizer("this is a test");


while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
prints the following output:
this
is
a
test
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code. It is recommended that anyone seeking this functionality use
the split method of String or the java.util.regex package instead.

The following example illustrates how the String.split method can be used to break up a string into
its basic tokens:

String[] result = "this is a test".split("\\s");


for (int x=0; x<result.length; x++)
System.out.println(result[x]);

prints the following output:

this
is
a
test
Constructor Summary

Constructors Constructor and Description


StringTokenizer(String str) Constructs a string tokenizer for the specified string.
StringTokenizer(String str, String delim) Constructs a string tokenizer for the specified string.
StringTokenizer(String str, String delim, boolean returnDelims) Constructs a string tokenizer for the
specified string.

Method Summary

Modifier and Type Method and Description


• Int countTokens()
Calculates the number of times that this tokenizer's nextToken method can be called before it
generates an exception.
• Boolean hasMoreElements()
Returns the same value as the hasMoreTokens method.
• Boolean hasMoreTokens()
Tests if there are more tokens available from this tokenizer's string.
• Object nextElement()
Returns the same value as the nextToken method, except that its declared return value is Object
rather than String.
• String nextToken()
Returns the next token from this string tokenizer.
• String nextToken(String delim)
Returns the next token in this string tokenizer's string.

Methods inherited from class java.lang.Object

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

public StringTokenizer(String str, String delim)

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

public boolean hasMoreTokens()


Tests if there are more tokens available from this tokenizer's string. If this method returns
true, then a subsequent call to nextToken with no argument will successfully return a token.
Returns: true if and only if there is at least one token in the string after the current position; false
otherwise.
• nextToken

public String nextToken()


Returns the next token from this string tokenizer.
Returns:
the next token from this string tokenizer.
Throws:
NoSuchElementException - if there are no more tokens in this tokenizer's string.

• nextToken

public String nextToken(String delim)


Returns the next token in this string tokenizer's string. First, the set of characters considered to be
delimiters by this StringTokenizer object is changed to be the characters in the string delim. Then the
next token in the string after the current position is returned. The current position is advanced beyond
the recognized token. The new delimiter set remains the default after this call.
Parameters:
delim - the new delimiters.
Returns:
the next token, after switching to the new delimiter set.
Throws:
NoSuchElementException - if there are no more tokens in this tokenizer's string.
NullPointerException - if delim is null

• hasMoreElements

public boolean hasMoreElements()


Returns the same value as the hasMoreTokens method. It exists so that this class can implement the
Enumeration interface.
Specified by:
hasMoreElements in interface Enumeration<Object>
Returns:
true if there are more tokens; false otherwise.

• nextElement

public Object nextElement()


Returns the same value as the nextToken method, except that its declared return value is Object
rather than String. It exists so that this class can implement the Enumeration interface.
Specified by:
nextElement in interface Enumeration<Object>
Returns:
the next token in the string.
Throws:
NoSuchElementException - if there are no more tokens in this tokenizer's string.

• 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;

public class DateExample {


public static void main(String[] args) {
// Creating a Date object representing the current date and time
Date currentDate = new Date();
System.out.println("Current Date and Time: " + currentDate);

// 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.

Date date1 = new Date();


Date date2 = new Date(System.currentTimeMillis() + 10000); // 10 seconds later

System.out.println("Date 1: " + date1);


System.out.println("Date 2: " + date2);

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;

public class LocalDateExample {


public static void main(String[] args) {
// Creating a LocalDate object representing the current date
LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);

// Creating a LocalDate object for a specific date


LocalDate specificDate = LocalDate.of(2021, 7, 2);
System.out.println("Specific Date: " + specificDate);
}
}
The java.time package includes other classes like LocalTime, LocalDateTime, ZonedDateTime,
and more, providing a rich set of tools for working with dates and times in a more intuitive and
robust manner.

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;

public class CalendarExample {


public static void main(String[] args) {
// Create a Calendar instance representing the current date and time
Calendar calendar = Calendar.getInstance();

// Get various components of the date and time


int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // Months are 0-based
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

System.out.println("Current Date and Time:");


System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
System.out.println("Hour: " + hour);
System.out.println("Minute: " + minute);
System.out.println("Second: " + second);
}
}
n the example above, Calendar.getInstance() is used to obtain a Calendar instance representing the
current date and time. Various constants like Calendar.YEAR, Calendar.MONTH, etc., are used to
retrieve specific components of the date and time.

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;

public class GregorianCalendarExample {


public static void main(String[] args) {
// Create a GregorianCalendar instance representing the current date and time
GregorianCalendar gregorianCalendar = new GregorianCalendar();

// Get various components of the date and time


int year = gregorianCalendar.get(GregorianCalendar.YEAR);
int month = gregorianCalendar.get(GregorianCalendar.MONTH) + 1; // Months are 0-based
int day = gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH);
int hour = gregorianCalendar.get(GregorianCalendar.HOUR_OF_DAY);
int minute = gregorianCalendar.get(GregorianCalendar.MINUTE);
int second = gregorianCalendar.get(GregorianCalendar.SECOND);

System.out.println("Current Date and Time (Gregorian Calendar):");


System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
System.out.println("Hour: " + hour);
System.out.println("Minute: " + minute);
System.out.println("Second: " + second);
}
}

this example, GregorianCalendar.getInstance() is used to obtain a GregorianCalendar instance


representing the current date and time. Components of the date and time are obtained using constants
like GregorianCalendar.YEAR, GregorianCalendar.MONTH, etc.

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;

// Reading from the console


Scanner consoleScanner = new Scanner(System.in);

// Reading from a file


File inputFile = new File("input.txt");
Scanner fileScanner = new Scanner(inputFile);

2. Reading Different Data Types:


The Scanner class provides methods to read different types of data, such as nextInt(), nextDouble(),
nextLine(), etc.

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int intValue = scanner.nextInt();

System.out.print("Enter a double: ");


double doubleValue = scanner.nextDouble();

System.out.print("Enter a string: ");


String stringValue = scanner.next();

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.

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter an integer.");
scanner.next(); // consume the invalid input
}
int intValue = scanner.nextInt();

4. Delimiter Customization:
By default, the Scanner uses whitespace as the delimiter. You can customize the delimiter to match
specific patterns.

Scanner scanner = new Scanner("John,Doe,25");


scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}

5. Closing the Scanner:


It's important to close the Scanner when it's no longer needed, especially if it's reading from system
resources like files.

scanner.close();
import java.util.Scanner;

public class ScannerExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

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;

public class FileReadWriteExample {


public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
// Writing to a file
writer.write("Hello, this is a line of text.");
} catch (IOException e) {
e.printStackTrace();
}

try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) {


// Reading from a file
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This example demonstrates writing a line of text to a file using a BufferedWriter and reading the
content of the file using a BufferedReader. The try-with-resources statement is used to ensure that
the resources are closed automatically after the try block finishes.

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;

public class FileExample {


public static void main(String[] args) {
// Creating a File object for a file
File file = new File("example.txt");

// Creating a File object for a directory


File directory = new File("exampleDirectory");
// Check if the file exists
System.out.println("File exists: " + file.exists());

// Check if it's a directory


System.out.println("Is a directory: " + directory.isDirectory());
}
}

2. Byte Streams and Character Streams:


• Byte Streams (InputStream and OutputStream):
• Deal with raw binary data.
• FileInputStream and FileOutputStream are used for reading and writing bytes
from/to files.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamExample {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {

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;

public class CharacterStreamExample {


public static void main(String[] args) {
try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt")) {

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.*;

class Person implements Serializable {


String name;
int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}

public class SerializationExample {


public static void main(String[] args) {
// Serialization
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("person.ser"))) {
Person person = new Person("John", 25);
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}

// 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.

You might also like