Sorting in Java

Sorting the numbers is easy in Java. Collections utility class provides the ‘sort’ method for sorting the numbers. [Don’t confuse with Collection which is an Interface]. To the Collections  Sort method you need to input numbers in List format. Though numbers present in Array also can be converted to List and then can be sorted. Java also provides another utility class ‘Arrays’ which has also Sort method. You can use either class methods for sorting on your convenience.

Collections.sort method expects List as input [array can also be send by converting to list object using Arrays.asList(arrayObj) method]

Arrays.sort method expects Array as input [List can also be send by converting to Array object using listObj.toArray() method]

Eg1: Sorting Numbers in List

List <Integer> numLst1 = new ArrayList<>();
numLst1.add(20);
numLst1.add(10);
numLst1.add(04);
Collections.sort(numLst1);
//Arrays.sort(numLst1.toArray());
int f = 0;
while(f< numLst1.size()){
System.out.println(numLst1.get(f));
f++;
}

o/p:   [4    10     20]

Eg2: Sorting Numbers in Array

Here we are converting Array to List and then sorting.

Integer[] numLst1 = {10, 30, 05};
Arrays.sort(numLst1);
//Collections.sort(Arrays.asList(numLst1));
int f = 0;
while(f<numLst1.length()){
System.out.println(numLst1[f].intValue());
f++;
}

o/p: [5    10     30]

Eg3: Sorting numbers and finding smallest number

Now let’s get into some deep by taking a requirement which returns the smallest number from the Array which should not be 0. Means if the Array contains numbers like [12, 20, 5, 30, 0, 50] then it should return smallest number as ‘5’ (not zero).

Integer[] returnVal = {10, 5, 20, 0};
Arrays.sort(returnVal);
//Collections.sort(Arrays.asList(returnVal));
int f= 0;
int smallValue = 0;
while(f < returnVal.length){
if (returnVal[f].intValue() !=0){
smallValue = returnVal[f].intValue();
break;
}
f++;
}
System.out.println("smallValue:"+smallValue);

o/p:   5

Sorting Numbers in HashSet & HashMap [not with the help of Sort method]

This can be achieved with the help of TreeSet. From TreeSet if you try to move to HashSet again then the insertion order will be lost. So keep the sorted result in TreeMap only or store them into LinkedHashSet where the insertion order is maintained. Similarly for HashMap sorting can be achieved with the help of TreeMap.


HashSet<Integer> hs = new HashSet<>();
hs.add(10);
hs.add(6);
hs.add(20);
hs.add(12);
System.out.println("hs:"+hs);
TreeSet<Integer> ts = new TreeSet<>();
ts.addAll(hs);
System.out.println("ts:"+ts);

o/p:     hs:[20, 6, 10, 12]      ts:[6, 10, 12, 20]

Advertisements

Exceptions in Java

There are many exceptions in Java. We can categorize them into two categories.

  1. Checked Exceptions (Which we can handle)
  2. UnChecked Exceptions (Which we can not handle- Run time)

Now let’s talk about each exception in Java.

Checked Exceptions: Remember that checked exceptions means the exceptions which we can handle. Few exceptions give error at compile time itself. Few exceptions doesn’t give exception at compile time but give at run time. But remember that what ever exceptions we can handle are checked exceptions. We do arithmetic operations and there might be a possibility to get exception if we pass zero to divide operation. So we can predict this error and can handle it with a catch block ArithmeticException or using throws ArithmeticException . We pass some values and execute some code and we have to predict what if the value passed is Null then we have to handle that using NullPointerException. So like these we have to predict the possibilities of getting and exception and have to handle them. If we can not predict the exceptions/ can not handle them then those are unchecked exceptions.

1. NoClassDefFoundException:

If the class reference is not available at runtime (though it is present at compile time and some how got deleted after that) then this error occurs. So this un cached exception as we can’t handle this exception.

2. ArithmeticException: Arithmetic error, such as divide-by-zero.

public static void main(String[] args) {
ArithMethod(40,0);
}
private static void ArithMethod(int a, int b) {
try{
int c = a/b;
}
catch(ArithmeticException ae){
System.out.println("Arithmetic Exception caught..");
}
}

3. NumberFormatException: Invalid conversion of a string to a numeric format.


try{
String v ="12j";
Integer inte = Integer.parseInt(v);
System.out.println("inte:"+inte);
}
catch(NumberFormatException nume){
System.out.println("NumberFormatException Caught...");
}

4. SecurityException: Attempt to violate security.

5. SqlException

6. ArrayIndexOutOfBoundsException: Array index is out-of-bounds


public static void main(String[] args) {

arrayBound();
}

private static void arrayBound() {
try{
int[] g = new int[3];
g[0] = 32;
g[1] = 26;
g[2] = 43;
g[3] = 61;
}
catch(ArrayIndexOutOfBoundsException AIOe){
System.out.println("ArrayIndexOutOfBoundsException Caught...");
}
}

7. StringIndexOutOfBoundsException: 

8. IndexOutOfBoundsException: Some type of index is out-of-bounds.

9. NullPointerException: Invalid use of a null reference.

Eg:


String s3=null;
try{
String s31 = new String(s3);
}
catch(Exception ne){
System.out.println("Null Pointer Exception Caught..");
}

I’ve listed few mostly used exceptions and There are few more catched exceptions in Java.

UnChecked Exceptions:

1. ClassNotFoundException:

If the class reference is not available at the time of compilation then this error occurs. So this is a compile time exception.

2. CloneNotSupportedException

Attempt to clone an object that does not implement the Cloneable interface.

3. IllegalAccessException

Access to a class is denied.

4. InstantiationException

Attempt to create an object of an abstract class or interface.

5. InterruptedException

One thread has been interrupted by another thread.

6. NoSuchFieldException

A requested field does not exist.

7. NoSuchMethodException

A requested method does not exist.

8. ResourceNotFoundException:

9. ResourceUnAvailableException:

Hexa to Decimnal conversion in Java

Have you ever tried to print the value of int i=0xbb; ? Do you think it’ll give numeric exception? No it works well and gives you the output of ‘187’. What is this value? It’s a decimal value of ‘bb’.

Well now coming to the point if you give value to integer starts with 0x (zero alphabet x) then jvm will convert the next value after prefix (assumes it as hex value) to decimal value. In the above example the hex value is ‘bb’ and its decimal value is ‘187’ which is then stored into integer. Want to cross check ? You can also do that calculation like below.

eg1: bb -> 11 X 160 + 11 X 161 = (11+176)= 187

eg2: bd -> 13 X 160 + 11 X 161 =(13+176)=189

Confused with Decimal and Hex values? Check below.

Hex             0     1     2     3     4     5     6     7     8     9     A       B     C       D      E       F
Decimal     0     1     2     3     4     5     6     7     8     9     10     11     12     13     14     15

Note: You can see decimal values for the alphabets a to f only. If you give any alphabet other than a to f then it’ll syntax error.

Leave your comments and suggestions in below comment section. Hope you enjoyed the post 🙂

Mask data like XXX XX 8743

If your requirement is to mask some part of the data and show only last few digits then this solution helps you to fix your requirement.

We can do this in a simple way if we knew the number of digits passed are fixed and want to hide fixed number of digits and show fixed number of digits.

eg: You always pass 9 digit number and want to mask first 6 numbers and show last 3 numbers.

String s ="123456789"; //Fixed 9 digit length of number
String mask = "XXXXXX"; //Fixed 6 digit length of number to be masked
s= s.substring(6) + mask; // output: XXXXXX789

Let’s take an example where the number of digits vary and also the number of digits we have to show also vary then the below code will help you.


public static void main(String[] args) {
mask(1234567,2);
}

private static String mask(int maskData, int unmaskCount){
try{
int  masksize_length = (int) (Math.log10(maskData)+1)-unmaskCount;
System.out.println("masksize_length:"+masksize_length);
Integer maskData1 = new  Integer(maskData);
String fixMask = "";
int i =1;
while(i<= masksize_length){
fixMask = fixMask.concat("X");
//System.out.println("fixMask:"+fixMask);
i++;
}
String maskedData = maskData1.toString();
maskedData = fixMask.concat(maskedData.substring(masksize_length));
System.out.println("maskedData:"+maskedData);
return maskedData;
}
catch(Exception e){
}
return null;

}

For the above code if you pass input as

mask(1234567,2); then output would be: XXXXX67
mask(1234567891,4); then output would be: XXXXXX7891 mask(1236432,3); then output would be: XXXX432
If you’ve any doubts or better solution..please leave  your suggestion in the comment section.