22EC360 – OBJECT ORIENTED
PROGRAMMING
Module 4: Libraries: String Handling - Methods, I/O –
File Reading and Writing, StringTokenizer, Collections –
Arraylist, linked list, HashSet, Linked Hashset, Tree Set,
JDBC
Dr.J.Shanthi
Assistant Professor
Department of ECE
Thiagarajar College of Engineering
String Handling
• As is the case in most other programming languages, in Java a string is a sequence of characters.
• But, unlike some other languages that implement strings as character arrays, Java implements strings
as objects of type String.
• Implementing strings as built-in objects allows Java to provide a full complement of features that
make string handling convenient.
• For example, Java has methods to compare two strings, search for a substring, concatenate two
strings, and change the case of letters within a string.
• Also, String objects can be constructed a number of ways, making it easy to obtain a string when
needed.
• Each time you need an altered version of an existing string, a new String object is created that
contains the modifications.
• The original string is left unchanged.
• For those cases in which a modifiable string is desired, Java provides two options: StringBuffer and
StringBuilder.
• Both hold strings that can be modified after they are created.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 2
• The String, StringBuffer, and StringBuilder classes are defined in java.lang.
Thus, they are available to all programs automatically.
• All are declared final, which means that none of these classes may be
subclassed. T
• his allows certain optimizations that increase performance to take place on
common string operations.
• All three implement the CharSequence interface.
• One last point: To say that the strings within objects of type String are
unchangeable means that the contents of the String instance cannot be
changed after it has been created.
• However, a variable declared as a String reference can be changed to point
at some other String object at any time.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 3
The String Constructors
• The String class supports several constructors. To create an empty String, call the
default constructor.
• For example,
• String s = new String();
• will create an instance of String with no characters in it.
• The String class provides a variety of constructors to handle this. To create a String
initialized by an array of characters, use the constructor shown here:
• String(char chars[ ])
• Here is an example:
• char chars[] = { 'a', 'b', 'c' };
• String s = new String(chars);
• This constructor initializes s with the string "abc".
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 4
• You can specify a subrange of a character array as an initializer using the
following constructor:
String(char chars[ ], int startIndex, int numChars)
• Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
• This initializes s with the characters cde.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 5
You can construct a String object that contains the same character sequence as another String object
using this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a’};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 6
• Even though Java’s char type uses 16 bits to represent the basic Unicode
character set, the typical format for strings on the Internet uses arrays of 8-bit
bytes constructed from the ASCII character set.
• Because 8-bit ASCII strings are common, the String class provides constructors
that initialize a string when given a byte array.
• Two forms are shown here:
String(byte chrs[ ])
String(byte chrs[ ], int startIndex, int numChars)
• Here, chrs specifies the array of bytes.
• The second form allows you to specify a subrange.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 7
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
This program generates the following output:
ABCDEF
CDE
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 8
String Length
• The length of a string is the number of characters that it contains. To
obtain this value, call the length( ) method, shown here:
int length( )
• The following fragment prints "3", since there are three characters in the
string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 9
String Literals
For each string literal in your program, Java automatically constructs a String
object.
Thus, you can use a string literal to initialize a String object.
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
or
String s2 = "abc"; // use string literal
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 10
String Concatenation
• In general, Java does not allow operators to be applied to String objects.
• The one exception to this rule is the + operator, which concatenates two strings,
producing a String object as the result.
• This allows you to chain together a series of + operations.
• For example, the following fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
• This displays the string "He is 9 years old."
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 11
String Concatenation with Other Data Types
• You can concatenate strings with other types of data.
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
• In this case, age is an int rather than another String, but the output produced is the same as
before.
• This is because the int value in age is automatically converted into its string representation within
a String object.
• This string is then concatenated as before.
• The compiler will convert an operand to its string equivalent whenever the other operand of the +
is an instance of String.
String s = "four: " + 2 + 2;
System.out.println(s);
four: 22
String s = "four: " + (2 + 2);
four: 4
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 12
Character Extraction
• The String class provides a number of ways in which characters can be extracted from a String
object.
• Although the characters that comprise a string within a String object cannot be indexed as if they
were a character array, many of the String methods employ an index (or offset) into the string for
their operation.
• Like arrays, the string indexes begin at zero.
• charAt( )
• To extract a single character from a String, you can refer directly to an individual character via the
charAt( ) method. It has this general form:
char charAt(int where)
• Here, where is the index of the character that you want to obtain. The value of where must be
nonnegative and specify a location within the string. charAt( ) returns the character at the specified
location. For example,
char ch;
ch = "abc".charAt(1);
• assigns the value b to ch.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 13
Character Extraction
getChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method. It
has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 14
getBytes( )
• There is an alternative to getChars( ) that stores the characters in an array of bytes.
• This method is called getBytes( ), and it uses the default character-to-byte conversions
provided by the platform.
byte[ ] getBytes( )
toCharArray( )
• If you want to convert all the characters in a String object into a character array, the
easiest way is to call toCharArray( ). It returns an array of characters for the entire
string. It has this general form:
char[ ] toCharArray( )
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 15
String Comparison
The String class includes a number of methods that compare strings or
substrings within strings.
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> "
+s1.equalsIgnoreCase(s4));
Hello equals Hello -> true
} Hello equals Good-bye -> false
} Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 16
compareTo( ) int compareTo(String str)
public class CompareStrings {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
String str3 = "apple";
int result1 = str1.compareTo(str2); // Negative value because "apple" comes before "banana" lexicographically.
int result2 = str2.compareTo(str1); // Positive value because "banana" comes after "apple" lexicographically.
int result3 = str1.compareTo(str3); // Zero because the two strings are equal.
System.out.println("Result 1: " + result1); Result 1: -1
System.out.println("Result 2: " + result2); Result 2: 1
System.out.println("Result 3: " + result3); Result 3: 0
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 17
}
// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men","to", "come", "to",
"the", "aid", "of", "their", "country"
}; Now
public static void main(String args[]) { aid
for(int j = 0; j < arr.length; j++) { all
for(int i = j + 1; i < arr.length; i++) { come
if(arr[i].compareTo(arr[j]) < 0) { country
String t = arr[j]; for
arr[j] = arr[i]; good
arr[i] = t; is
} men
} of
System.out.println(arr[j]); the
} the
} their
} time
to
11/15/2023 to
Altera VLSI Lab, Thiagarajar College of Engineering 18
Searching Strings
• The String class provides two methods that allow you to search a string for a specified
character or substring:
indexOf( ) Searches for the first occurrence of a character or substring.
lastIndexOf( ) Searches for the last occurrence of a character or substring.
• the methods return the index at which the character or substring was found, or –1 on failure.
int indexOf(int ch, int startIndex)
int indexOf(String str)
int lastIndexOf(int ch, int startIndex)
int lastIndexOf(String str)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 19
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " + "to come to the aid of their
country.";
System.out.println(s);
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
Now
} is the time for all good men to come to the aid of their
country.
indexOf(t) = 7 lastIndexOf(t, 60) = 55
lastIndexOf(t) = 65 indexOf(the, 10) = 44
indexOf(the) = 7 lastIndexOf(the, 60) = 55
lastIndexOf(the) = 55
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 20
indexOf(t, 10) = 11
public class IndexOfExample {
public static void main(String[] args) {
String text = "Hello, world! Hello, Java!";
String searchString = "Hello";
int firstIndex = text.indexOf(searchString);
System.out.println("First occurrence of 'Hello' is at index: " + firstIndex);
// Searching from a specific index
int secondIndex = text.indexOf(searchString, firstIndex + 1);
System.out.println("Second occurrence of 'Hello' is at index: " + secondIndex);
}
}
First occurrence of 'Hello' is at index: 0
Second occurrence of 'Hello' is at index: 13
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 21
public class LastIndexOfExample {
public static void main(String[] args) {
String text = "Hello, world! Hello, Java!";
String searchString = "Hello";
int lastIndex = text.lastIndexOf(searchString);
System.out.println("Last occurrence of 'Hello' is at index: " + lastIndex);
// Searching from a specific index
int secondLastIndex = text.lastIndexOf(searchString, lastIndex - 1);
System.out.println("Second last occurrence of 'Hello' is at index: " + secondLastIndex);
}
}
Last occurrence of 'Hello' is at index: 13
Second last occurrence of 'Hello' is at index: 0
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 22
Modifying a String
substring( )
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String text = "Hello, World!";
String sub = text.substring(7); // "World!"
String sub2 = text.substring(0, 5); // "Hello"
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 23
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = ""; This is a test. This is, too.
int i; Thwas is a test. This is, too.
do { // replace all matching substrings Thwas was a test. This is, too.
System.out.println(org); Thwas was a test. Thwas is, too.
i = org.indexOf(search); Thwas was a test. Thwas was, too.
if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 24
concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents
of str appended to the end. concat( ) performs the same function as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
puts the string "onetwo" into s2.
It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 25
replace( )
• The replace( ) method has two forms.
• The first replaces all occurrences of one character in the invoking string with another
character. String replace(char original, char replacement)
• Here, original specifies the character to be replaced by the character specified by
replacement.
• The resulting string is returned. For example,
• String s = "Hello".replace('l', 'w');
• puts the string "Hewwo" into s.
• The second form of replace( ) replaces one character sequence with another.
String replace(CharSequence original, CharSequence replacement)
String text = "Hello, World!";
String replaced = text.replace("Hello", "Hi");
// "Hi, World!"
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 26
trim( )
• The trim( ) method returns a copy of the invoking string from which any leading
and trailing whitespace has been removed.
String trim( )
String s = " Hello World ".trim();
String text = " Java Programming ";
String trimmed = text.trim();
// "Java Programming"
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 27
Changing the Case of Characters Within a String
• The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase.
• The toUpperCase( ) method converts all the characters in a string from lowercase to
uppercase. Nonalphabetical characters, such as digits, are unaffected
String toLowerCase( )
String toUpperCase( )
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 28
Joining Strings
• It is used to concatenate two or more strings, separating each string with a delimiter,
such as a space or a comma.
static String join(CharSequence delim, CharSequence . . . strs)
// Demonstrate the join() method defined by String.
class StringJoinDemo {
public static void main(String args[]) {
String result = String.join(" ", "Alpha", "Beta", "Gamma");
System.out.println(result);
result = String.join(", ", "John", "ID#: 569","E-mail:
[email protected]");
System.out.println(result);
}
}
Alpha Beta Gamma
John, ID#: 569, E-mail:
[email protected] 11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 29
File
• Although most of the classes defined by java.io operate on streams, the File class
does not.
• It deals directly with files and the file system.
• That is, the File class does not specify how information is retrieved from or stored
in files; it describes the properties of a file itself.
• A File object is used to obtain or manipulate the information associated with a disk
file, such as the permissions, time, date, and directory path, and to navigate
subdirectory hierarchies.
• Files are a primary source and destination for data within many programs.
• Although there are severe restrictions on their use within applets for security
reasons, files are still a central resource for storing persistent and shared
information.
• A directory in Java is treated simply as a File with one additional property—a list of
filenames that can be examined by the list( ) method.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 30
The following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Here, directoryPath is the path name of the file;
filename is the name of the file or subdirectory;
dirObj is a File object that specifies a directory;
and uriObj is a URI object that describes a file.
File f1 = new File("/");
File f2 = new File("/","autoexec.bat");
File f3 = new File(f1,"autoexec.bat");
• File defines many methods that obtain the standard properties of a File object.
• For example, getName( ) returns the name of the file;
• getParent( ) returns the name of the parent directory; and
• exists( ) returns true if the file exists, false if it does not.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 31
• isFile( ) returns true if called on a file and false if called on a directory.
• isFile( ) returns false for some special files, such as device drivers and named pipes,
so this method can be used to make sure the file will behave as a file.
• The isAbsolute( ) method returns true if the file has an absolute path and false if its
path is relative.
• The boolean renameTo(File newName) -used to rename a file or directory.
• It renames the current file or directory to the name specified by the newName
parameter, and it returns true if the renaming was successful or false if it failed.
• It's important to note that the success of the operation can depend on various
factors, such as file permissions, file existence, or platform-specific restrictions.
• boolean delete( ) - to delete a directory if the directory is empty. delete( )
returns true if it deletes the file and false if the file cannot be removed.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 32
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("C:/Users/Shanthi/Desktop/COPYRIGHT.txt");
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 a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 33
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 34
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 35
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 36
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 37
import java.io.File;
public class RenameFileExample {
public static void main(String[] args) {
// Create a File object for the current file or directory.
File currentFile = new File("oldname.txt");
// Create a File object for the new name.
File newName = new File("newname.txt");
// Attempt to rename the file.
boolean renamed = currentFile.renameTo(newName);
if (renamed) {
System.out.println("File successfully renamed to 'newname.txt'");
} else {
System.out.println("File renaming failed.");
}
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 38
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
// Create a File object for the file or directory to be deleted.
File fileToDelete = new File("fileToDelete.txt");
// Check if the file exists before attempting to delete.
if (fileToDelete.exists()) {
// Attempt to delete the file.
boolean deleted = fileToDelete.delete();
if (deleted) {
System.out.println("File deleted successfully.");
} else {
System.out.println("File deletion failed.");
}
} else {
System.out.println("File does not exist. No deletion performed.");
}
}
} 11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 39
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 40
The Stream Classes
• Java’s stream-based I/O is built upon four abstract classes:
• InputStream, OutputStream - designed for byte streams
• Reader, and Writer- designed for character streams
FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes
from a file.
Two commonly used constructors are shown here:
FileInputStream(String filePath)
FileInputStream(File fileObj)
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 41
Input/Output: Exploring java.io
• Java’s I/O system, including basic techniques for reading and writing files, handling
I/O exceptions, and closing a file.
The I/O Classes and Interfaces
The I/O classes defined by java.io are listed here:
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 42
The I/O Classes and Interfaces
The I/O classes defined by java.io are listed here:
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 43
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 44
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 45
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
// Create a FileInputStream for the file you want to read.
FileInputStream inputStream = new FileInputStream("C:/Users/Shanthi/Desktop/example.txt");
int data;
// Read bytes from the file and print them to the console.
while ((data = inputStream.read()) != -1) {
System.out.print((char)data); // Assuming the file contains text data
}
// Close the FileInputStream when you're done with it.
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} 11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 46
• when you use the FileInputStream class in Java to read data from a file, you should use it within a
try-catch block or handle exceptions in some way.
• This is because FileInputStream can throw checked exceptions, specifically FileNotFoundException
and IOException, which must be handled to ensure your program can handle potential errors
gracefully.
• If you don't use a try-catch statement or handle exceptions in some way when working with a
FileInputStream, your Java program will not compile because FileInputStream can throw checked
exceptions.
• Checked exceptions, such as FileNotFoundException and IOException, must be either caught using
try-catch blocks or declared to be thrown in the method's signature.
If you ignore these exceptions, the Java compiler will produce an error, and your program will not
compile. You'll receive a compilation error similar to the following:
Uncaught exception: java.io.FileNotFoundException; must be caught or declared to be thrown
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 47
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 48
FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file.
It implements the AutoCloseable, Closeable, and Flushable interfaces. Four of its
constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is
a File object that describes the file. If append is true, the file is opened in append mode.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 49
import java.io.*;
public class FileOutputStreamExample {
public static void main(String[] args) {
String data = "Hello, World! This is an example of FileOutputStream in Java.";
try {
// Specify the file name and path where you want to write the data
String fileName = "output.txt";
// Create a FileOutputStream for the specified file
FileOutputStream fos = new FileOutputStream(fileName);
// Convert the data string into bytes and write it to the file
byte[] dataBytes = data.getBytes();
fos.write(dataBytes);
// Close the FileOutputStream to release system resources
fos.close();
System.out.println("Data has been written to " + fileName);
} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
}
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 50
The Character Streams
• While the byte stream classes provide sufficient functionality to handle any type of
I/O operation, they cannot work directly with Unicode characters.
• Since one of the main purposes of Java is to support the "write once, run
anywhere" philosophy, it was necessary to include direct I/O support for characters.
• In this section, several of the character I/O classes are discussed.
• As explained earlier, at the top of the character stream hierarchies are the Reader
and Writer abstract classes.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 51
Reader
• Reader is an abstract class that defines Java’s model of streaming character input.
• It implements the AutoCloseable, Closeable, and Readable interfaces.
• All of the methods in this class (except for markSupported( )) will throw an
IOException on error conditions.
The Methods Defined by Reader (FEW)
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 52
Writer
• Writer is an abstract class that defines streaming character output.
• It implements the AutoCloseable, Closeable, Flushable, and Appendable
interfaces.
• All of the methods in this class throw an IOException in the case of errors.
The Methods Defined by Writer
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 53
FileReader
The FileReader class creates a Reader that you can use to read the contents of a file.
Two commonly used constructors are shown here:
FileReader(String filePath)
FileReader(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.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 54
// Demonstrate FileReader.
// This program uses try-with-resources. It requires JDK 7 or later.
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) {
try ( FileReader fr = new FileReader("output.txt") )
{
int c;
// Read and display the file.
while((c = fr.read()) != -1) System.out.print((char) c);
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 55
FileWriter
FileWriter creates a Writer that you can use to write to a file. Four commonly used
constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can all throw an IOException.
Here, filePath is the full path name of a file, and
fileObj is a File object that describes the file.
If append is true, then output is appended to the end of the file.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 56
import java.io.*;
public class FileWriterExample {
public static void main(String[] args) {
String data = "This is an example of FileWriter in Java.";
String fileName = "output1.txt";
try {
// Create a FileWriter for the specified file
FileWriter fileWriter = new FileWriter(fileName);
// Write the data to the file
fileWriter.write(data);
// Close the FileWriter to release system resources
fileWriter.close();
System.out.println("Data has been written to " + fileName);
} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 57
}
java.util - More Utility Classes
StringTokenizer
• In Java, a StringTokenizer is a class provided in the java.util package that allows
you to break a string into smaller pieces or tokens.
• It's primarily used for splitting a string into substrings based on a specified
delimiter (e.g., a comma, space, or any other character).
• You create an instance of the StringTokenizer class, providing the string you want to
tokenize and the delimiter (or delimiters) that you want to use to split the string.
• You can iterate through the tokens using methods like nextToken(), which returns
the next token as a string.
• You can also use methods like hasMoreTokens() to check if there are more tokens
left in the string.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 58
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
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 59
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" + "author=Schildt;" + "publisher=McGraw-Hill;" +"copyright=2014";
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 McGraw-Hill
copyright 2014
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 60
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String text = "This is a sample text for StringTokenizer example";
StringTokenizer tokenizer = new StringTokenizer(text);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
} This
} is
} a
sample
text
for
StringTokenizer
example
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 61
The Methods Defined by StringTokenizer
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 62
java.util Part 1: The Collections Framework
• java.util is an important package contains a large assortment of classes and interfaces
that support a broad range of functionality.
• For example, java.util has classes that generate pseudorandom numbers, manage
date and time, observe events, manipulate sets of bits, tokenize strings, and handle
formatted data.
• The java.util package also contains one of Java’s most powerful subsystems: the
Collections Framework.
• The Collections Framework is a sophisticated hierarchy of interfaces and classes that
provide state-of-the-art technology for managing groups of objects.
ArrayList, LinkedList, HashSet, LinkedHashSet, and TreeSet i
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 63
ArrayList:
ArrayList is a dynamic array-based data structure in Java. It allows you to store elements of
the same data type and automatically resizes itself when elements are added or removed.
It provides fast access to elements by their index.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(); First element: Apple
Apple
// Adding elements Banana
list.add("Apple"); Cherry
list.add("Banana");
list.add("Cherry");
// Accessing elements by index
System.out.println("First element: " + list.get(0));
// Iterating through elements
for (String fruit : list) {
11/15/2023
System.out.println(fruit); Altera VLSI Lab, Thiagarajar College of Engineering 64
}
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
// Add elements to the array list. Initial size of al: 0
al.add("C"); Size of al after additions: 7
al.add("A"); Contents of al: [C, A2, A, E, B, D, F]
al.add("E"); Size of al after deletions: 5
al.add("B"); Contents of al: [C, A2, E, B, D]
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 65
System.out.println("Contents of al: " + al);
The LinkedList Class
• The LinkedList class extends AbstractSequentialList and implements the List,
Deque, and Queue interfaces.
• In Java, LinkedList is a class that implements the List interface and represents a
doubly-linked list.
• Unlike arrays, linked lists do not have a fixed size, and elements can be easily
inserted or removed from any position in the list.
• Each element in a linked list is represented by a node, and each node contains a
reference (or link) to the next and previous nodes in the list.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 66
// Adding an element at the beginning of the LinkedList
import java.util.LinkedList;
linkedList.addFirst("JavaScript");
public class LinkedListExample {
// Adding an element at the end of the LinkedList
public static void main(String[] args) {
linkedList.addLast("Ruby");
// Creating a LinkedList
LinkedList<String> linkedList = new LinkedList<>();
// Displaying the modified LinkedList
System.out.println("Modified LinkedList: " + linkedList);
// Adding elements to the LinkedList
linkedList.add("Java");
// Removing an element from the LinkedList
linkedList.add("Python");
linkedList.remove("Python");
linkedList.add("C++");
// Displaying the final LinkedList
// Displaying the LinkedList
System.out.println("Final LinkedList: " + linkedList);
System.out.println("LinkedList: " + linkedList);
// Accessing elements using a loop
System.out.println("Elements in the LinkedList:");
for (String language : linkedList) {
System.out.println(language);
}
}
11/15/2023 }
Altera VLSI Lab, Thiagarajar College of Engineering 67
The HashSet Class
In Java, the HashSet class is part of the java.util package and implements the Set
interface.
It is a collection that does not allow duplicate elements and does not guarantee the
order of elements.
The HashSet class is based on the hash table data structure.
Characteristics:
No Duplicate Elements:
The HashSet does not allow duplicate elements. If you attempt to add an element that is already
present, the add method will return false, and the set will remain unchanged.
No Order Guarantee:
The order of elements in a HashSet is not guaranteed. If you need to maintain the order in which
elements were inserted, you can use a LinkedHashSet instead.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 68
Characteristics:
Null Values:
A HashSet allows one null element. If you attempt to add more than one null, a NullPointerException
will be thrown.
Performance:
The performance of basic operations (add, remove, contains) is constant time, assuming a good hash
function and an appropriate initial capacity.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 69
import java.util.HashSet;
// Displaying the HashSet
System.out.println("HashSet: " + hashSet);
public class HashSetExample {
public static void main(String[] args) {
// Removing an element
// Creating a HashSet
hashSet.remove("Banana");
HashSet<String> hashSet = new HashSet<>();
// Displaying the modified HashSet
// Adding elements to the HashSet
System.out.println("Modified HashSet: " + hashSet);
hashSet.add("Apple");
hashSet.add("Banana");
// Checking if an element is present
hashSet.add("Orange");
System.out.println("Contains 'Orange': " + hashSet.contains("Orange"
hashSet.add("Apple"); // Duplicate element, will not
be added
// Iterating through the HashSet
System.out.println("Elements in the HashSet:");
for (String fruit : hashSet) {
System.out.println(fruit);
}
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 70
The LinkedHashSet Class
• The LinkedHashSet class extends HashSet and adds no members of its own. It is a
generic class that has this declaration:
• class LinkedHashSet<E>
• Here, E specifies the type of objects that the set will hold. Its constructors parallel
those in HashSet.
• In Java, LinkedHashSet is a class that extends HashSet and implements the Set
interface.
• Similar to HashSet, it does not allow duplicate elements, but it maintains the order of
elements based on the order in which they were inserted.
• This makes LinkedHashSet a hybrid data structure that combines the features of a
linked list and a hash table.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 71
The TreeSet Class
• TreeSet extends AbstractSet and implements the NavigableSet interface.
• It creates a collection that uses a tree for storage. Objects are stored in sorted,
ascending order.
• Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
Characteristics:
Sorted Elements:
TreeSet stores elements in sorted order.
No Duplicate Elements:
Like other implementations of Set, TreeSet does not allow duplicate elements. If you attempt to add an element that
is already present, the add method will return false, and the set will remain unchanged.
Null Values:
TreeSet does not allow null elements. If you attempt to add a null element, a NullPointerException will be thrown.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 72
// Demonstrate TreeSet.
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet<String> ts = new TreeSet<String>();
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 73
import java.util.TreeSet;
public class TreeSetExample { // Displaying the modified TreeSet
public static void main(String[] args) { System.out.println("Modified TreeSet: " + treeSet);
// Creating a TreeSet
TreeSet<String> treeSet = new TreeSet<>(); // Checking if an element is present
System.out.println("Contains 'Orange': " + treeSet.contains("Orange"));
// Adding elements to the TreeSet
treeSet.add("Apple"); // Iterating through the TreeSet
treeSet.add("Banana"); System.out.println("Elements in the TreeSet:");
treeSet.add("Orange"); for (String fruit : treeSet) {
treeSet.add("Apple"); // Duplicate element, System.out.println(fruit);
will not be added }
}
// Displaying the TreeSet }
System.out.println("TreeSet: " + treeSet);
// Removing an element
treeSet.remove("Banana");
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 74
Java Database Connectivity (JDBC)
• Java Database Connectivity (JDBC) is a Java-based API that provides a standard interface for
connecting to relational databases and executing SQL queries.
• JDBC allows Java programs to interact with databases and perform various operations such as
querying data, updating records, and executing stored procedures.
key components and concepts of JDBC:
1. JDBC Drivers:
JDBC uses drivers to connect to different types of databases. There are four types of JDBC drivers:
Type 1 (JDBC-ODBC Bridge Driver): This driver uses ODBC (Open Database Connectivity) to connect to
databases. It is platform-dependent and requires a bridge to communicate with the database.
Type 2 (Native-API Driver): This driver uses database-specific native API to connect to databases. It is
also platform-dependent.
Type 3 (Network Protocol Driver): This driver communicates with a middleware server that then
connects to the database. It is platform-independent and database-independent.
Type 4 (Thin Driver or Direct-to-database Driver): This driver communicates directly with the database
using a protocol provided by the database. It is platform-independent and database-independent.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 75
2. JDBC API:
The JDBC API provides a set of classes and interfaces for database connectivity. Some key interfaces include:
DriverManager:
DriverManager: Manages a list of database drivers. It is used to establish a connection to the database.
Connection: Represents a connection to the database. It provides methods for creating statements and managing
transactions.
Statement: Represents an SQL statement that can be executed against the database. There are different types of
statements, including Statement, PreparedStatement, and CallableStatement.
ResultSet: Represents the result set of a query. It provides methods for retrieving data from the query result.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 76
3. JDBC Steps:
The typical steps to use JDBC in a Java program are as follows:
Load the JDBC Driver: Use Class.forName() to load the JDBC driver.
Establish a Connection: Use DriverManager.getConnection() to establish a connection to the database.
Create a Statement: Use the createStatement() method of the Connection interface to create a
statement.
Execute SQL Queries: Use the statement to execute SQL queries using methods like executeQuery().
Process the ResultSet: If the query returns a result set, process the result set using the ResultSet
interface.
Close Resources: Close the ResultSet, Statement, and Connection objects to release database
resources.
11/15/2023 Altera VLSI Lab, Thiagarajar College of Engineering 77