Professional Documents
Culture Documents
(ii)
(b) Two Questions of 3 Marks
(i) Differentiate between the StringBuffer and StringBuilder classes in Java.
StringBuilder=>
- Non synchronized so it’s not thread safe
- Builder is faster than buffer bcs it’s not synchronized
- Builder is more efficient than buffer
StringBuffer=>
- Synchronized so thread safe i.e 2 thread cannot call the method of stringBuffer at the
same time
- Buffer is less efficient than stringbuilder
- Buffer introduced in java 1.0
OR
(b) Answer the following.
What is the purpose of SequenceInputStream in Java I/O? Provide an example.
SequenceInputStream is used to read multiple file at the same time because for example
FileInputStream or BufferedInputStream is only capable of reading a file on a time. The
sequenceinputstream can be for example used to concate 2 or more file into one by reading
both of the files at the same time.
======================================================================
==============================================================--------------
----------------------------------------------------------------------------------------------------------
Q.B
import java.util.regex.Pattern;
import java.util.regex.Matcher;
if (matcher.matches()) {
System.out.println("Valid phone number!");
} else {
System.out.println("Invalid phone number.");
}}
FileWriter:
● FileWriter is used to create a file and write characters into it. It’s part of
the Character Stream classes.
● Avoid using FileInputStream and FileOutputStream for textual
information, as they are Byte Stream classes.
import java.io.FileWriter;
import java.io.IOException;
System.out.println("Writing successful");
fw.close();
}
}
FileReader:
try {
reader = new FileReader("input.txt");
int ch;
import java.io.PrintStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
ps.println("Hello, PrintStream!");
ps.close(); }}
PrintWriter:
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
pw.println("Hello, PrintWriter!");
pw.close();
}}
1. Key Differences:
○ PrintStream writes raw bytes, while PrintWriter processes
characters.
○ PrintStream is a byte stream, and PrintWriter is a character
stream.
○ PrintStream does not throw checked exceptions, whereas
PrintWriter does.
○ Use PrintStream for binary data or console output, and
PrintWriter for text data.
1. FileOutputStream and FileInputStream classes in Java I/O are used for writing
and reading bytes to and from files, respectively. FileOutputStream writes data
as a stream of bytes to a file, while FileInputStream reads data from a file as a
stream of bytes.
2. DataOutputStream and DataInputStream classes in Java are used for writing
and reading primitive data types as binary data streams. They provide
methods to write and read various primitive data types consistently across
different platforms.
Q.B