Java 9 – @SafeVarargs Annotation

In this post, we will see about @SafeVarargs Annotation in Java 9.

The @SafeVarargs is an annotation that is used to perform safe operations. When a method takes variable arguments, then it may cause to unsafe operation, so the @SafeVarargs annotation tells to the compiler to perform safe operations. For example, if we don’t use the annotation the compiler reports warning: Type safety: Potential heap pollution via varargs parameter.

We can use this annotation to final and static and private (from Java 9) methods only of a class. See the example below.

@SafeVarargs annotation

Let’s see few examples with final and static methods.

@SafeVarargs with Final Method

In this example, we have a final methods that takes var-args parameters so we used @SafeVarargs annotation. See the example.

Output

[Python, Java]

@SafeVarargs with Static Method

Java allows using @SafeVarargs annotation with static methods as well. See the example with below.

Output

[Python, Java]

Java 9 @SafeVarargs Improvement

In Java 9, It is allowed to use @SafeVarargs annotation with private methods as well. Here, we have a private method displayString() that takes string type var-args.

Output

[Python, Java] Java
is
a
Awesome
Language

Please note that if you use @SafeVarargs in private method before Java 9, you will get a compilation error.

Without @SafeVarargs annotation

In case, we don’t use the annotation the compile will report a warning message to console with output.

Output

Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Java
is
a
Awesome
Language

That’s all about Java 9 @SafeVarargs Annotation.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *