Swap array elements

Java does not have any direct method to swap array elements. We have to create function like following. For primitive type array we have to create individual function for each type. Consider following function which swap elements in int array.

public void swap(int[] arr, int index1, int index2) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

Here we have to introduce one temporary variable to perform swap. But for array of wrapper classes we can create generic function for swapping. Following program illustrates the generic function for swapping elements of any Object array.

public <T> void swap(T[] arr, int index1, int index2) {
    T temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}

As above function should have checks to disallow operation for null array and for negative index value. Otherwise caller of the method may face IndexOutOfBoundsException or NullPointerException. Moreover, we can use Collections.swap(list, index1, index2) for swapping elements of list, if we can convert our array to list.

Following function will swap the elements with swap method of Collections. But it has extra overhead of converting array to list and then list to array.

@SuppressWarnings("unchecked")
public <T> void swap(T[] arr, int index1, int index2) {
    List<T> list = Arrays.asList(arr);
    Collections.swap(list, index1, index2);
    arr = (T[]) list.toArray();// Raise unchecked casting warning
}

Left Shift Operator

Java allows bit shifting feature on integral type data. Shift operators are not used much in everyday programming task. But for interviews, questions of shift operators might be there. Before understanding what left shift does we first have to understand that how does integral data stored in Java. Note once again that only integer values can be left shifted in Java. Left shift operator is declared as ‘<<‘  (two less than characters) in java.

For integer number 10, it is stored in 4-bytes.

00000000 00000000 00000000 00001010

Now when you use left shift operator i.e 10 << 1 it will shift one bit to left. Now, number is stored like this,

00000000 00000000 00000000 00001010 : 10
00000000 00000000 00000000 00010100 : 10 << 1 = 20

So, now value 10 becomes 20 (for binary 10100). If we want to shift by 2 bits like 10 << 2, then number will be 40 (for binary 101000),

00000000 00000000 00000000 00001010 : 10
00000000 00000000 00000000 00101000 : 10 << 2 = 40

Similarly if we shift number 10 by 3 bits it will become 80. So here we can conclude that left shift works according to following formula,

number * 2 ^ shiftBitCount

Note here that left shift operator is signed operator and so it preserves the sign of the number during shift. For negative number say -10 the binary representation in 4 bytes will be 2’s complement of 10,

For number 10 we will do 1’s complement and add 1 to it,

 11111111 11111111 11111111 11110101 : 1's complement of 10
+00000000 00000000 00000000 00000001 : +1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 11111111 11111111 11111111 11110110 : -10

Let’s perform shift operation on -10 << 1,

1111111 11111111 11111111 111101100 : -10 << 1 = -20

Notice that while shifting we are padding zeros to the right and the shifted bits are lost in the space forever. Here the same formula applies and other than that the sign of the number is preserved by the left shifting operation.

Following Java program can elaborate the stated logic, kindly visit to my Number To Binary Hexa Octa String for basic introduction about Integer#toBinaryString.

public class LeftShiftOperator {
    public static void main(String[] args) {
          int ten = 10;
          System.out.println("Binary of " + ten + " : " + Integer.toBinaryString(ten));
          ten = ten << 1;
          System.out.println("Binary after left shift : " + Integer.toBinaryString(ten));
          System.out.println("Shift Result of positive : " + ten);

          int minusTen = -10;
          System.out.println("Binary of minus " + minusTen + " : "+ Integer.toBinaryString(minusTen));
          minusTen = minusTen << 1;
          System.out.println("Binary after left shift : "+ Integer.toBinaryString(minusTen));
          System.out.println("Shift Result of negative : " + minusTen);
    }
}

Above program will give us following output,

Binary of 10 : 1010
Binary after left shift : 10100
Shift Result of positive : 20
Binary of minus -10 : 11111111111111111111111111110110
Binary after left shift : 11111111111111111111111111101100
Shift Result of negative : -20

Left shift can only be performed on integer value we can do the shift on byte, short and char as well after casting them to int value. Because all the stated types are internally represented as an integer data.

Apparently, for shifting the auto-unboxing also takes place for wrapper class of int, Integer.

Integer ten = new Integer(10);
ten = ten << 1;//It's valid due to auto-unboxing

One more thing to note is that the left shifted bits are gone and never return back or can not be used any further for our integer value. So for large number if we shift them left the value may give you small negative value.

For example Integer.MAX_VALUE,

01111111111111111111111111111111 : Integer.MAX_VALUE
1111111111111111111111111111110 : Integer.MAX_VALUE << 1 = -2

Comparator in Java8

Comparator is comparatively easy to use in Java8. Functional style of programming in Java8 has introduced new way to use the comparator.

This is what we we do before Java8. Kindly note that getDob() method returns date of birth of a Student, which is java.util.Date instance.

studentList.sort(new Comparator<Student>() {

     @Override
     public int compare(Student o1, Student o2) {
         return o1.getDob().compareTo(o2.getDob());
     }
});

Here we can see that we have to create the anonymous class of comparator and then we provide the sorting logic.  With Java8 we can use Lambada expression to reduce the extra boiler plate code of comparator declaration and compare method declaration.

studentList.sort((o1, o2) ->  {
    return o1.getDob().compareTo(o2.getDob());
});

You can see how it is reduced in size. Even more there are lot of default methods has been introduced in Comparator interface. For example,

studentList.sort(Comparator.comparing(Student::getDob));

Here comparing method will prepare the comparator based on the method reference we have provided. Moreover, we can also simply reverse the order of sorting,

studentList.sort(Comparator.comparing(Student::getDob).reversed());

Lot more default methods are there in Comparator interface to reduce the extra code of comparator declaration and speed up the development.

 

Format Date

In real life application we have to format the Date as in user interface we have to display Date in some other format while our database stores it in a different format. To keep sync between those two formats we have to change the date format. Continue reading