When I try to compile this program, I get an "unreachable statement" error in line 21:
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.lang.StringBuilder;
class FilePrep {
public static void main(String args[]) {
}
public String getStringFromBuffer() {
try {
Path file = Paths.get("testfile2.txt");
FileInputStream fstream = new FileInputStream("testfile2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String inputLine = null;
StringBuffer theText = new StringBuffer();
while((inputLine=br.readLine())!=null) {
theText.append(inputLine+" ");
}
return theText.toString();
System.out.println(theText); // <-- line 21
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
return null;
}
}
}
The full compiler output is:
Main.java:21: error: unreachable statement
System.out.println(theText);
^
Main.java:28: error: missing return statement
}
^
2 errors
I think the return
statements are in the right places...they seem to be to me at least, and the program seems so simple compared to the one that I cloned it from, that I'm having a really hard time figuring out why this statement is unreachable.
What did I do wrong while copying the code, and how do I need to correct it?
You were right assuming that your problem is here:
the
return
function will terminate your method, meaning no line of code past it will be executed. If you want your print to go through, you should move it above the return statement.You've got a statement after the return statement. Here's the two offending lines:
Switch them around.
When the
return
statement is executed, the method relinquish control to its caller. That is why theprintln
will not run; that's why the compiler complains.Unreachable statements are certain and reliable indicators of a logical error in your program. It means that you put in statements that will not be executed, but you assume that they would be. The compiler analyzes the flow, and reports these statements to you as error messages.
The print statement comes after a return statement. The function will always exit before it gets to the print statement. "Unreachable"
Switch the order of the two lines around and it will work.
The
return
statement always should be at the end or last line of the definition block. If you keep any statements after thereturn
statement those statements are unreachable statements by the controller. By usingreturn
statement we are telling control should go back to its caller explicitly.For example
In this example we get compile time error as
unreachable code
because control cannot reach to last statement for execution.So, always
return
statement should be the last statement of a definition block.