I didn't understand this feature of Java. I know it makes coding easier and sometimes looks neater, but what is the actual use of this? On contrary i feel, its better to display the warnings, as in future any one can refer them before making modifications to code. Does this @SuppressWarnings increases compliling efficiency OR is this according to any coding standards?
The @SuppressWarnings annotation disables certain compiler warnings. In this case, the warning about deprecated code ( "deprecation" ) and unused local variables or unused private methods ( "unused" ).
@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.
Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
Annotation Type SuppressWarnings As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective. If you want to suppress a warning in a particular method, you should annotate that method rather than its class.
While programming you should watch out for compiler warnings and in best case compile your code with no warnings (and errors of course).
But sometimes you can't get rid of a warning and you KNOW the code is correct or can't be changed. Then you don't want to be bothered every time from the compiler that there is something wrong.
So you can suppress it with the command you mentioned.
Other answers already explained use cases of @SuppressWarnings
a lot, but I want to emphasize the point that sometimes you absolutely need to use @SuppressWarnings
to overcome limitations of the language itself, and in these cases use of @SuppressWarnings
is absolutely legal.
In other cases use of @SuppressWarnings
can be considered questionable, because in these cases you can always get rid of warnings by changing the code (though, obviously, it's not always acceptable).
Here are some common cases when you absolutely cannot get rid of warnings without @SuppressWarnings
:
Map
from classes to their implementations (since you cannot assign different values of generic type parameter to different map entires)When you are dealing with legacy code that does not support generics (Java <= 1.4) that is the only viable way of geting rid of cast warnings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With