Thursday, September 11, 2014

Java 8 : Static Methods

From Java 8, you are allowed to add static methods to interfaces.

Up to Now, it has been common to place static methods in companion classes like Collections for 
Collection interface.

Simply, you will add utility methods to interface as static methods to avoid pairs of classes.

Sample Utility Class :

public interface NumberUtils {
       public static boolean isEven(int number) {
              return (number % 2 == 0);
       }

       public static boolean isOdd(int number) {
              return (number % 2 == 1);
       }

       public static boolean isDivisible(int number, int divisor) {
              return (number % divisor == 0);
       }

       public static boolean isPrime(int number) {
              if (number < 2 || (number > 2 && (number % 2 == 0))) {
                     return false;
              }
              int limit = number / 2;
              for (int i = 2; i < limit; i++) {
                     if (i * i >= number) {
                           limit = i;
                           break;
                     }
              }
              for (int i = 2; i <= limit; i++) {
                     if (number % i == 0) {
                           return false;
                     }
              }
              return true;
       }
}

No comments:

Post a Comment