File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes method to read a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "method to read a string" Watch "method to read a string" New topic

method to read a string

CH Low

Joined: Aug 25, 2001
Posts: 1
I tried writing a String input method and had a problem
with throwing IOException so i tried to use a try/catch statement, but then
the variable to be returned is said to be "not initialised" by the
compiler. wats the problem? can anyone help? here's the code;
public static String getString()
InputStreamReader input;
BufferedReader bR;
String s;
input = new InputStreamReader(;
bR = new BufferedReader(input);
s = bR.readLine();
catch (IOException e)
return s; // there seems to be a problem with returning s!
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
In a method, every variable must be assigned a value before being used. There are no default values, as there are for instance and class level fields. If BufferedReader.readLine() threw an IOException, s would never have been assigned a value. Now, we both know that the chances of that happening are slim to none, but the compiler only knows the Java Language Specification. Before you return 's', you must initialize it. To do that, replace 'String s;' with 'String s = null;'
I agree. Here's the link:
subject: method to read a string
It's not a secret anymore!