@SafeVarargs annotation for private methods in Java 9?


The @SafeVarargs annotation was introduced in Java 7. This annotation applies to both final and static methods or constructors that take varargs parameters. This annotation used to make sure that a method does not perform unsafe operations on its varargs parameters. Since Java 9, @SafeVarargs annotation also applies to private instance methods.

Syntax

@SafeVarargs
private void methodName(...) {
   // some statements
}

Example

import java.util.ArrayList;
import java.util.List;
public class SafevarargsTest {
   @SafeVarargs     // Apply @SafeVarargs to private methods
   private void display(List<String>... names) {
      for(List<String> name : names) {
         System.out.println(name);
      }
   }
   public static void main(String args[]) {
      SafevarargsTest test = new SafevarargsTest();
      List<String> list = new ArrayList<String>();
      list.add("TutorialsPoint");
      list.add("Tutorix");
      test.display(list);
   }
}

Output

[TutorialsPoint, Tutorix]

Updated on: 21-Feb-2020

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements