I wrote the following java code, and i expected the compiler would complain about it. but i didn’t get any errors. Why is this ?
public static void main(String[] args) {
Ba ba = new Ba();
ba.fetchSomeValues();
}
public String fetchSomeValues(){
return "Hello";
}
}
I am calling the method fetchSomeValues() which should return “Hello” (which is a string), and in the main method i have included ba.fetchSomeValues(); without initializing it to a String variable. The compiler doesn’t complain Why is this ?
You don’t have to assign return values to variables. You don’t have to do anything at all with them.
Although it is usually not recommended to just drop some return value of a method.
A counter example might be the
Map‘sputmethod which returns the previous value associated with the key. If you don’t care whether there was a previous value or not you just simply ignore the return value.So in a nutshell the compiler cannot tell whether you care about return values or not. It is only a problem if the value is significant in the context you are using the method and you ignore it.