Saturday, 9 September 2017

Determine if a String has all unique character or not in JAVA

We can determine a String has all unique characters or not by several ways.
Suppose you are given a String like "abcdef10&g" and our program should return TRUE as it contains all unique characters, but for a String like "abccdefg", the output would be FALSE.

I am going to use a boolean array to solve this approach. Initially each element of the array would be FALSE. We will find out the ASCII value of each character and check the current value for that index in boolean array, if the value is FALSE that means the character is unique and make the value TRUE.

If the value is TRUE that means character is already present and the String contains non-unique characters.

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class UniqueString {
public static void main(String[] args) {
String uniqueTest="abcdef10gg";
if(isUniqueChanracter(uniqueTest))
System.out.println("Yes, Unique String.");
else
System.out.println("No, its not unique ");
}

private static boolean isUniqueChanracter(String uniqueTest) {

boolean unique_set[]=new boolean[256];
for(int i=0;i<uniqueTest.length();i++)
{
int val=uniqueTest.charAt(i);
if(unique_set[val])
return false;
else
unique_set[val]=true;
}
return true;
}

Friday, 8 September 2017

Converting String to Integer without using any Standard Library in JAVA

This question can be asked in both service and product based company as well.
Suppose you are given a String like "12345" and after converting it should be "12345".
Normally using standard library we can convert this using Integer.parseInt("") or Integer.valueOf("").

Without using standard library, we will find out ASCII code of each character and subtract it with '0' which will give current int value and finally multiply by 10 to get actual result.

Initially we will check it starts with negative or not, if negative then substract the result from 0 at last else do nothing.

Input: "12345"
Output: 12345

Input: "-12345"
Output: -12345

Sample Code:

/**
 * 
 * @author Sourin M
 *
 */
public class StringToInteger {

public static void main(String[] args) {

String number="-1234567";
System.out.println("Number is: "+ getNumber(number));

}
public static int getNumber(String number) {
   int result = 0;
   boolean isNegative=false;
   if(number.charAt(0)=='-')
   {
    isNegative=true;    
   }else
   {
    result=number.charAt(0)-'0';
   }
   for (int i = 1; i < number.length(); i++) {
    result = result * 10 + number.charAt(i) - '0';
   }
   if(isNegative)
    result=0-result;
   return result;

}



}

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...