The following is an example from https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html, the only change is that the content of the String inputLine is added up to the strAll String instead of printing it, see X_HERE.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
String strAll = "";
while ((inputLine = in.readLine()) != null)
// System.out.println(inputLine);
strAll = strAll + inputLine; // X_HERE
in.close();
}
}
This throws no warning. If you replace line X_HERE with
strAll += inputLine;
using "addition assignment" you get the warning:
The value of the local variable strAll is not used
If you replace the while condition with (true), the warning for strAll disappears. Why is "addition assignment" treated differently in this context?
Edited thanks to @Joni: I am using Visual Studio Code, the warning appears in the “Problems” Window.
This warning is not part of the Java language, or even the Java compiler. It's just visual studio code trying to be helpful.
This is a bug or a limitation in the static code analysis feature in vs code. It's counting strAll = strAll + inputLine
as a "use" of the variable strAll
, while it's not counting the equivalent strAll += inputLine
as a "use" of the variable. If the code analysis was smarter it would give you a "unused variable" warning for both cases.