Sunday, June 28, 2015

Generics Methods and Varargs

Generics Methods and Varargs

This is third post in Java Generics tutorials. In previous post we discussed Introduction to Java Generics and cast-iron guarantee provided in Generics.

In this post we will see how to write Generic Methods and Varargs.

Generic Methods

Let us write a generic method that will accept the array of any type and return the list for that type.

      public static <T> List<T> toList(T[] arr) {

            List<T> list = new ArrayList<T>();
            for (T t : arr) {
                  list.add(t);
            }
            return list;
      }

<T> means a type parameter. It is passed as the method argument and appears in return type too. Also we use as type resolving.

You can call this method by using different types.

      String[] str = { "Monday", "Tuesday", "Wednesday", "Thursday" };
      List<String> list = ArrayToListDemo.toList(str);
     
      Integer[] ints = { 1, 2, 3, 4 };
      List<Integer> intsList = ArrayToListDemo.toList(ints);


Now if you see the parameter for the method toList(T[] arr) it is an array of type T. Now if we want to pass one or two parameters then we need to write like this

List<Integer> intsList = ArrayToListDemo.toList(new Integer[] { 1, 2 });
                                
List<String> strlist = ArrayToListDemo.toList(new String[] { "Monday" });

This is a clumsy process.

There is another way to pass variable number of arguments to the method. It is called Varargs. It has a special syntax which is more convenient to use. It must be used only as last parameter to any method.

      public static <T> List<T> toList(T... arr) {

            List<T> list = new ArrayList<T>();
            for (T t : arr) {
                  list.add(t);
            }
            return list;
      }

See the method parameter toList(T... arr). We can call this method like this

List<Integer> intsList = ArrayToListDemo.toList(1, 2);
      List<String> strlist = ArrayToListDemo.toList("Monday", "Tuesday");

At runtime, the Varargs are filled in array and then passed to method. So using Varargs can be used to reduce some clutter in code.


Monday, June 22, 2015

Spring Framework StringUtils class trimLeadingWhiteSpace(..) method

Spring Framework StringUtils class trimLeadingWhiteSpace(..) method

Previously we saw methods like isEmpty(), hasLength(), hasText(), containsWhiteSpace(), trimWhiteSpace() & trimAllWhiteSpace() of StringUtils class of Spring Framework.

You can find entire list here.

In this post we will see the method trimLeadingWhiteSpace(..) which is used to trim only the leading whitespace from the String.

Below is the code take from StringUtils class of Spring Framework. I have also commented the code so it will be easier to understand it.

      /**
       * This method is used to trim all the leading whitespace from String.
       * */
      public static String trimLeadingWhitespace(String str) {
            /**
         * First, check for the length.
         * If input string is null or length == 0 then
         * return the str.
         * */
            if (!hasLength(str)) {
                  return str;
            }
           
            /**
             * Fill the StringBuilder with the input String.
             * */
            StringBuilder sb = new StringBuilder(str);
            /**
             * StringBuilder is mutable sequence of characters.
             * If the length of StringBuilder is greater than 0 and
             * is first character is whitespace then delete that character.
             *
             * using deleteCharAt(int index) method the length of Sequence is shortened
             * by 1. Remaining characters are shifted using System.arrayCopy(..)
             * */
            while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
                  sb.deleteCharAt(0);
            }
            /**
             * Convert StringBuilder to String and return it.
             * */
            return sb.toString();
      }

Driver Class

public class SpringTrimLeadingWhiteSpaceDemo {

      public static void main(String[] args) {
            trimLeadingWhiteSpaceDemo(null);
      }

      public static String trimLeadingWhiteSpaceDemo(String str) {

            str = StringUtils.trimLeadingWhitespace(str);
            return str;
      }
}

     
Test Cases on Driver Method

Input

Output
null

null
“”

“”
“  ”

“”
“   Java”

“Java”
“Java   ”

“Java   ”
“  Java  ”

“Java  ”
“Ja  va”

“Ja  va”
“  Ja  va  ”

“Ja  va  ”

Test cases
package stringutils;

import junit.framework.Assert;

import org.junit.Test;

public class SpringTrimLeadingWhiteSpaceDemoTest {
     
      @Test
      public void testForNull(){
            Assert.assertEquals(null, SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo(null));
      }
     
      @Test
      public void testForAllEmpty(){
            Assert.assertEquals("", SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo("   "));
      }
     
      @Test
      public void testForLeadingEmpty(){
            Assert.assertEquals("Java", SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo("    Java"));
      }
     
      @Test
      public void testForNullTrailingEmpty(){
            Assert.assertEquals("Java   ", SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo("Java   "));
      }
     
      @Test
      public void testForLeadingAndTrailingEmpty(){
            Assert.assertEquals("Java  ", SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo("  Java  "));
      }
     
      @Test
      public void testForInMidEmpty(){
            Assert.assertEquals("Ja va", SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo("Ja va"));
      }
     
      @Test
      public void testForLeadingTrailingAndInMidEmpty(){
            Assert.assertEquals("Ja va  ", SpringTrimLeadingWhiteSpaceDemo.trimLeadingWhiteSpaceDemo("  Ja va  "));
      }

}

 Test Cases Execution





Sunday, June 21, 2015

Java Generics

Java Generics

In previous post we saw Introduction to Java Generics. In this post we will see what cast-iron guarantee is.

For instance let us take the following code (Java 1.5 or greater)

            List<String> names = new ArrayList<String>();
            names.add("String1 ");
            names.add("String2");
            String result = names.get(0) + names.get(1);
            System.out.println(result);

ArrayList<E> class implements List<E> interface. So we wrote List<String> names = new ArrayList<String>();

Then we add two strings into the list names.add("String1 "); names.add("String2");

After that we concat both the strings using “+” operator.

Now, before Java Generics (before Java 1.5) were introduced same code was written as

            List names = new ArrayList();
            names.add("String1 ");
            names.add("String2");
            String result = ((String) names.get(0)) + ((String) names.get(1));
            System.out.println(result);

The difference between both the piece of code is that before Java 5 we need to explicitly cast the elements and type parameters “<E>” were eliminated.

But the identical part is that they byte code compiled from both the piece of code is same. Reason is type erasure. If it is List<String>, List<Integer> or List<List<Integer>> all of them are represented as List in run-time. The process erases the type parameters hence the name type erasure.

As we saw that we need to cast explicitly before Java 1.5. Now, Generics does the same cast implicitly in compile time. Hence there won’t be ClassCastException at run-time. The implicit cast added by generics will never fail. This is a cast-iron guarantee provided to us.

Now the questions comes why compiler take List<String> as List? The reason is backward compatibility. Developers who developed code prior to Java 5 need not change their code according to the new syntax provided in Java 5. So at the byte code level the code that uses generics and the code that doesn’t looks same. So the developers need not shift their syntax overnight.



Friday, June 19, 2015

Spring framework StringUtils trimAllWhiteSpace(..) method

Spring Framework trimAllWhiteSpace(..) method

Previously we saw methods like isEmpty(), hasLength(), hasText(), containsWhiteSpace() and trimWhiteSpace() of StringUtils class of Spring Framework.

In this post we will see the method trimAllWhiteSpace(..) which is used to trim leading and trailing white space from the String.

Below is the code take from StringUtils class of Spring Framework. I have also commented the code so it will be easier to understand it.
      /**
       * This method is used to trim all the white spaces from the String.
       * */
      public static String trimAllWhitespace(String str) {
            /**
             * First, check for the length.
             * If input string is null or length == 0 then
             * return the str.
             * */
            if (!hasLength(str)) {
                  return str;
            }
            //Take the length of the String
            int len = str.length();
            StringBuilder sb = new StringBuilder(str.length());
           
            /**
             * run the loop till length of the input string.
             * */
            for (int i = 0; i < len; i++) {
                  char c = str.charAt(i);
                  /**
                   * If the character is not white space then append it
                   * to the StringBuilder
                   */
                  if (!Character.isWhitespace(c)) {
                        sb.append(c);
                  }
            }
            /**
             * Convert StringBuilder to String and return it.
             * */
            return sb.toString();
      }

Driver method
      public static String trimAllWhiteSpaceDemo(String str){
           
            String s=StringUtils.trimAllWhitespace(str);
            return s;
      }

Test cases on Driver method


Input
Output

null
null

“”
“”

“   ”
“”

“    Java”
“Java”

“Java   ”
“Java”

“    Java    ”
“Java”

“Java”
“Java”

“Ja  va”
“Java”



package stringutils;

import org.junit.Assert;
import org.junit.Test;

public class SpringTrimAllWhiteSpaceDemoTest {

      @Test
      public void testForNull() {
            Assert.assertEquals(null, SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo(null));
      }
     
      @Test
      public void testForEmptyString() {
            Assert.assertEquals("", SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo(""));
      }
     
      @Test
      public void testForAlBlanks() {
            Assert.assertEquals("", SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo("   "));
      }
     
      @Test
      public void testForLeadingSpaces() {
            Assert.assertEquals("Java", SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo("    Java"));
      }
     
      @Test
      public void testForTrailingSpaces() {
            Assert.assertEquals("Java", SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo("Java    "));
      }

      @Test
      public void testForLeadingAndTrailingSpaces() {
            Assert.assertEquals("Java", SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo("    Java   "));
      }
     
      @Test
      public void testForNoWhiteSpace() {
            Assert.assertEquals("Java", SpringTrimAllWhiteSpaceDemo.trimAllWhiteSpaceDemo("Java"));
      }
}

Test cases execution


That’s all on trimAllWhiteSpace(..) method.

Navigate to String Interview Questions or Main Page to read more.


Google Guava Preconditions class

Google Guava Preconditions class

This class can be used to check the state or arguments passed. As the name says Preconditions, this class is used to check for preconditions and see whether method can process the data or not.

We will walk through the methods of Preconditions class.

Each method has total 3 overloaded versions
1.       No extra arguments: Exceptions are thrown without any messages
2.       Object Argument: Exception are thrown with String.valueOf(message) which eventually ends up calling obj.toString()
3.       Additional Object arguments: they are error message arguments that are substituted into message template.

Method checkArgument

1.       checkArgument(boolean expression)

      public static void doubleEven(final int a) {

            boolean isEven = (a % 2 == 0);
            Preconditions.checkArgument(isEven);
               int multiply = a * 2;
            System.out.println(multiply);
         }
Output: Assume a = 11
Exception in thread "main" java.lang.IllegalArgumentException
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:76)

2.  checkArgument(boolean expression, @Nullable Object errorMessage)

         public static void doubleEven(final int a) {

               boolean isEven = (a % 2 == 0);
               Preconditions.checkArgument(isEven, "Input should be even");
               int multiply = a * 2;
               System.out.println(multiply);
         }
         Output: Assume a = 11
Exception in thread "main" java.lang.IllegalArgumentException: Input should be even
               at com.google.common.base.Preconditions.checkArgument(Preconditions.java:92)

3.  checkArgument(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs)

         public static void doubleEven(final int a) {

               boolean isEven = (a % 2 == 0);
               Preconditions.checkArgument(isEven, "Input %s should be even", a);
               int multiply = a * 2;
               System.out.println(multiply);
         }
Output: Assume a = 11    
Exception in thread "main" java.lang.IllegalArgumentException: Input 11 should be even
         at com.google.common.base.Preconditions.checkArgument(Preconditions.java:119)


The two methods with extra arguments are used to format the exception message. Now we will see which other methods are. I will not repeat the two overloaded versions of exception message formatting as they are same to use as above 2nd and 3rd method of checkArgument(..).


Method checkNotNull

      public static int length(final String str) {

            Preconditions.checkNotNull(str);
            return str.length();
      }

                Output: Assuming str is null.
Exception in thread "main" java.lang.NullPointerException
            at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)


Method checkPositionIndex

                public static void checkIndex(final int index, final int size){
            Preconditions.checkPositionIndex(index, size);
      }
     
      Output: Assuming index is 11 and size is 10
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (11) must not be greater than size (10)
            at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:355)
            at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:334)


Method checkPositionIndexes

      public static void checkPositionIndexes(final int start, final int end, final int size){
            Preconditions.checkPositionIndexes(start, end, size);
      }
                Output: Assuming start =  11, end = 13, size = 10

Exception in thread "main" java.lang.IndexOutOfBoundsException: start index (11) must not be greater than size (10)
      at com.google.common.base.Preconditions.checkPositionIndexes(Preconditions.java:388)


Method checkElementIndex

public static void checkElementIndex(final int index, final int size){
            Preconditions.checkElementIndex(index, size);
      }
      Output: Assuming index = 12, size = 11
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (12) must be less than size (11)
      at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:305)


Method checkState

      public static void checkState(){
            Preconditions.checkState(field.isEmpty());
      }
checkState method is used to check the state of the object or iterator or anything that can pass boolean as parameter.

That’s all on 6 methods of Preconditions class.


In next post we will learn about Predicates of Google Guava.


Ads Inside Post