Sunday 5 June 2016

wordEnds

Goto Problem

Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

wordEnds("abcXY123XYijk", "XY") → "c13i"
wordEnds("XY123XY", "XY") → "13"
wordEnds("XY1XY", "XY") → "11"
public String wordEnds(String str, String word)
 {
    String res="";
    if(word.equals(str))
       return res;
    if(str.startsWith(word)) 
    res=res+str.charAt(word.length());
    int i=1;
    while(i<(str.length()-word.length()))
   {
      if(str.substring(i).startsWith(word))
      {
         res=res+str.charAt(i-1)+str.charAt(i+word.length()); i=i+word.length();
       }
      else
       {
          i++;
       }
    }
    if(str.endsWith(word))
    {
        res=res+str.charAt(str.length()-word.length()-1);
        }
     return res;
 }

countYZ

Goto Problem

Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)


countYZ("fez day") → 2

countYZ("day fez") → 2

countYZ("day fyyyz") → 2

public int countYZ(String str)
{
str=str.toLowerCase();
int count=0;
for(int i=0;i<str.length()-1;i++)
{
if(str.charAt(i)=='y' || str.charAt(i)=='z')
{
if(!Character.isLetter(str.charAt(i+1)))
count++;
}
}
if(str.charAt(str.length()-1)=='y' || str.charAt(str.length()-1)=='z') count++;
return count;
}

Friday 3 June 2016

NullPointerException - Every Java Developer’s Nightmare

NullPointerException is a nightmare for any java programmer. The moment you move form primitive variables to reference variables, NullPointerException will begin to haunt you. This exception is most common and most annoying.  If you are a java developer, there is no way that you can avoid it. When I started development through java, there is nothing that I fear more than NullPointerException in my code.
When I first got the NullPointerException in my program, it kept me wondering that when java doesn’t support pointer how a NullPointerException can occur. I think it should have been named as NullReference Exception.  But as I explored the depths of java, I came to know about pointers in java too. Although a programmer neither can control nor can access the pointers, since they are implicitly managed by the JVM.  I have faced this exception many times during my project and was able to remove it and therefore I decided to honor it by writing about it.

Why is NullPointerException considered as programmer’s nightmare?

The main reason for this is that error description for NullPointerException doesn’t tells about the name of the null reference which caused the exception. The programmers, mostly beginners spend a lot of time in finding the reason for this error. Also it happens to occur frequently that it gets you tilted! On checking the stack trace, the line where this exception actually occurs is shown at the last. The first error is shown in the line in main() where the method (causing NullPointerException) is called. Since in java, the propagation of exception is stack based, it is very difficult to trace the line of origin of exception especially when a chain of methods is formed.

   Scenarios when we get NullPointerException.

Java API documentation says that NullPointerException can be thrown, when there is an attempt to use null where an object is required. That is you are trying to access a reference where there is no value. In java the references are used in calling the instance methods of the class. When the reference is used before it is being initialized to a default value, or is initialized as null.  When you pass null to a method when it expects a real value. It means to say that null object is used illegally.
How to prevent or solve the NullPointerException?
The solution is very simple. Put a null check for the reference variable using the if statement before the is used.
if(object!=null)
{
    Perform task with object.
}
However using this check pollutes the code when the number of reference variable is high in the code. But to avoid the pitfall, one has to use this ugly code.  A simple example is to have proper ‘required field’ check at GUI level, when your business logic expects an operation on a given object. Then you can depend on your design and omit the if-null-check which beefs up your code.

Ways of handling NullPointerException.?

  • Always use if-null-check when you don’t have control over the object’s value. (Ugly but no choice!)
  • Put the string constant first from left when comparing values with a String variable.
  • Erroneously don’t declare a variable inside a constructor, it will hide the instance variable.
  • Religiously initialize (fill) arrays immediately after declaration. Arrays mostly causes NullPointerException.