Tuesday, March 24, 2015

String endsWith(str) API

String endsWith(str) API 

In this blog we will see how to use endsWith(str) method of String API.

              String str="Sony Playstation";
              str.endsWith("station"); //returns true
              str.endsWith("Sony"); //returns false

We will use this function in such a way that it handles few extra conditions
The following code explains that whether the string input or prefix is not present the method should return false.

              if ((!hasLength(str)) && !(hasLength(prefix))) {
               return false;
             }

Now, if the length of prefix is greater than the length of string then we return false.

if (prefix.length() > str.length()) {
               return false;
             }

If above 2 conditions fail means we are ready to use endsWith(str) method.
Important: We are converting the input string and prefix to lowerCase because we are comparing them as case insensitive.

              if (str.toLowerCase().endsWith(prefix.toLowerCase())) {
                     return true;
              }

 Following is the code for entire method:
              // endsWith prefix (Ignore case)
              /**
               * Ends with ignore case.
               *
               * @param str
               *            the str
               * @param suffix
               *            the suffix
               * @return true, if successful
               */
              public static boolean endsWithIgnoreCase(String str, String suffix) {
                  if ((!hasLength(str)) && !(hasLength(suffix))) {
                      return false;
                  }
                  if (suffix.length() > str.length()) {
                      return false;
                  }
                  if (str.toLowerCase().endsWith(suffix.toLowerCase())) {
                      return true;
                  }
                  return false;
              }


Monday, March 23, 2015

String startsWith(str) API

String startsWith(str) usage and handling it right.

In this blog we will see how to use startsWith() method of String API.
              String str="Sony Playstation";
              str.startsWith("Sony"); //returns true
              str.startsWith("Playstation"); //returns false

We will use this function in such a way that it handles few extra conditions
The following code explains that whether the string input or prefix is not present the method should return false.
if ((!hasLength(str)) && !(hasLength(prefix))) {
                      return false;
              }

Now, if the length of prefix is greater than the length of string then we return false.
if (prefix.length() > str.length()) {
                      return false;
              }

If above 2 conditions fail means we are ready to use startsWith(str) method. Important :: We are converting the input string and prefix to lowercase because we are comparing them as case insensitive.
              if (str.toLowerCase().startsWith(prefix.toLowerCase())) {
               return true;
              }

Following is the code for entire method lowercase
              // startsWith prefix (Ignore case)
              /**
               * Starts with ignore case.
               *
               * @param str
               * @param prefix
               * @return true, if successful
               */
              public static boolean startsWithIgnoreCase(String str, String prefix) {

                  if ((!hasLength(str)) && !(hasLength(prefix))) {
                      return false;
                  }
                  if (prefix.length() > str.length()) {
                      return false;
                  }
                  if (str.toLowerCase().startsWith(prefix.toLowerCase())) {
                      return true;
                  }
                  return false;
              }

String has text?

How to see if String has text or not?

String is one of the most important concepts that we use in Java.

But using them properly is hard thing to do.

Sometimes we encounter a string with length > 0 but it does not have anything in it. It contains only space.

In this blog I will try to explain how to use such Strings in program.

Below is the utility method which is used to detect such Strings.

32 is ASCII for space. We use that to compare every character in string. 

If any character’s (if present) does not meet the ASCII of the space then it will return true. else it will return false;

return true: String has text in it. May or may not contain space. return false: String does not have text.
hasLength(str) con be found here

              // Checks if there is text in string(except space)
              /**
               * Checks for text.
               *
               * @param str
               *            the str
               * @return true, if successful
               */
              public static boolean hasText(String str) {
                     /**
                      * hasLength(str) is explained in previous blog
                      * it returns true if length of string is 1 or more
                      * return false if string is null or length is 0
                      * */
                     if (!hasLength(str)) {
                           return false;
                     }
                     // Check if any character exists except space
                     for (int i = 0; i < str.length(); i++) {
                           if (!(str.charAt(i) == 32)) {// 32 is ASCII for space
                                  return true;
                           }
                     }
                     return false;
              }


Does String has length?

How to checker whether string has length or not?

To check whether string has length or not we must check for 2 conditions:

1.       Is String null return false.
2.       Is length of String 0 return false.
3.       If both of above condition are false return true.

            /**
             * If the string is null then return false as null string
             * does not have length.
             * Caution if String is str="" then it will return true
             * instead it should return false.
             * */
            if(str==null){
                  return false;
            }
           
            if(str.length()==0){
                  return false;
            }
            /**Now we merge this two conditions in reverse way.
             * That is
             *    str != null and str.length() > 0
             *          return true
             *     otherwise
             *           return false
             *  */

            // Check if String has length or not
            /**
             * Checks for length.
             *
             * @param str
             *            the str
             * @return true, if successful
             */
            public static boolean hasLength(String str) {
                  return (str != null && str.length() > 0);
            }



Resolve Null String

How to Resolve Null String?

We often face problem for checking the null string in our projects or programs.
What we do is simple thing.

 //Some Code
        if(str==null){
           //Some Code
        }
        //Some Code

But is this enough?

There can be several strings coming into the program and what we can do is duplicate the above code several times.

But is it the Solution? No, it isn't.

What can be the better Solution?

Create a method that would handle it gracefully.
             //Always use this function to avoid NullPointerException on               //Strings
      /**
       * Resolve null string.
       *
       * @param str
       *            the str
       * @return the string
       */
      public static String resolveNullString(String str) {
            if (str == null) {
                  return "";
            }
            return str;

      }

Sunday, March 22, 2015

Number is EVEN or ODD?


Find whether a given number is EVEN or ODD.


Even odd numbers in number scale.


The above given question is simple. We can easily find whether a number is even or odd using ‘%’ operator.
What is even number?
Even numbers are integer of form 2k where k is integer. Following are even integers.
….,-4, -2, 0, 2, 4, 6, 8,..
What is odd number?
Even numbers are integer of form (2k+1) where k is integer. Following are even integers.
….,-3, -1, 1, 3, 5,..

So we know that number % 2 = 0 then it is even else it is odd.

Below is the image the shows evne and odd numbers on number line.

public class EvenOdd {

       public static void main(String[] args) {
             
      for (int i = -5; i < 5; i++) {
boolean isEven = EvenOdd.isEven(i);
                  if(isEven){
                        System.out.println(i+" is Even Number");
}else{
                        System.out.println(i+" is Odd Number");
                  }
      }
 }

       public static boolean isEven(int a) {
              /**
               * Check whether number is even or odd by using '%'
               * '%' is modules operator that will provide us remainder
               * If remainder is 0 then even
               * else number is odd
               * */
              if ((a % 2) == 0) {
                     return true;
              } else {
                     return false;
              }

       }
}

Ouput:
-5 is Odd Number
-4 is Even Number
-3 is Odd Number
-2 is Even Number
-1 is Odd Number
0 is Even Number
1 is Odd Number
2 is Even Number
3 is Odd Number
4 is Even Number

In the above program we check for the remainder of the number. We exploit the property that even number is divisible by 2 and remainder will be 0(zero). So we use ‘%’ to get remainder. If the remainder is 0(zero) then we say that number is even else it is odd.

Now ‘%’ is costly operation as it will divide the number constantly with the divisor in our case it is 2 and return output 0(zero) or 1.
We can use the bit operation as it will defiantly work faster than continuous division of modules (%).  

For bit operations we will now see binary numbers.
Decimal
Binary
0
0000
1
0001
2
0010
3
0011
4
0100
5
0101

In table even numbers are in bold. There is a pattern the number that is even does not have last bit 1. For additional information on binary number click here.

We can do bit operation & with 1If result is 0(zero) then number is even else odd.

public static boolean isEven(int a) {
              /**
               * Check whether number is even or odd by using '&'
               * If result is 0 then even
               * else number is odd
               * */
              if ((a & 1) == 0) {
                     return true;
              } else {
                     return false;
              }

       }

Output will be same as before.

Bit operations: example ‘& with 1’
Decimal 2 -> 0010
Decimal 1 -> 0001
Output          0000

Decimal 3 -> 0011
Decimal 1 -> 0001

Output          0001

Ads Inside Post