javafile-iocompiler-errors

Why am I getting an Unreachable Statement error in Java?


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?


Solution

  • You were right assuming that your problem is here:

    return theText.toString();
    System.out.println(theText);
    

    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.