LearnFrenzy
Sign in Take a free test

File Handling, IO and NIO · Find the Error · Question 5

Error: storing read() directly in a char Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) throws IOException {
        try (Reader r = new StringReader("hi")) {
            char c = r.read();
            System.out.println(c);
        }
    }
}
  • A StringReader cannot be used in try
  • B read() returns an int (so it can return -1 at the end); check for -1, then cast: char c = (char) value Correct
  • C Readers return bytes
  • D println cannot print chars
Correct Answer: Option B

javac: "incompatible types: possible lossy conversion from int to char".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links