Java Reference
In-Depth Information
Q The FileWriter class has a write( int ) method that's used to send a character
to a file. Shouldn't this be write( char ) ?
A The char and int data types are interchangeable in many ways; you can use an
int in a method that expects a char , and vice versa. This is possible because each
character is represented by a numeric code that is an integer value. When you call
the write() method with an int , it outputs the character associated with that inte-
ger value. When calling the write() method, you can cast an int value to a char
to ensure that it's being used as you intended.
15
Quiz
Review today's material by taking this three-question quiz.
Questions
1. What happens when you create a FileOutputStream using a reference to an exist-
ing file?
a. An exception is thrown.
b. The data you write to the stream is appended to the existing file.
c. The existing file is replaced with the data you write to the stream.
2. What two primitive types are interchangeable when you're working with streams?
a. byte and boolean
b. char and int
c. byte and char
3. In Java, what is the maximum value of a byte variable and the maximum value of
an unsigned byte in a stream?
a. Both are 255.
b. Both are 127.
c. 127 for a byte variable and 255 for an unsigned byte.
Answers
1. c. That's one of the things to look out for when using output streams; you can eas-
ily wipe out existing files.
2. b. Because a char is represented internally by Java as an integer value, you can
often use the two interchangeably in method calls and other statements.
3. c. The byte primitive data type has values ranging from 128 to 127 , whereas an
unsigned byte can range from 0 to 255 .
 
Search WWH ::




Custom Search