Search This Blog

Sunday, November 4, 2012

startsWith,endsWith Methods of String Class in Java


In this article, I am going to explains about endsWith,startsWith method in java String Class.
Let start explain about the two methods functionality.

startsWith(String arg)
                true, when the argument string is  matched with the “Prefix” of the another String, Otherwise false.
                Example :
                                String dbValue="s";
            boolean startValue="start".startsWith(dbValue);
            if(startValue)
            {
                  System.out.println("execute block of statement");
            }
            Here the value of variable startValue is “true”. So if statement will be executed and print as execute block of statement.

In real time variable dbvalue we used to get from the database/User interface. If we get the “empty” string value from the DB/UI than wired behavior will start.

I.e. we think that variable startValue is false and if statement won’t get executed, but variable  startValue will be  true and if statement get executed.


String dbValue="";
            boolean startValue="start".startsWith(dbValue);
            if(startValue)
            {
                  System.out.println("execute block of statement");
            }
Reason:
      The reason for return value true is comparison will be taken care by character sequence.so first character is consider as “empty character”.

endsWith(String arg)
true, when the argument string is  matched with the “Suffix” of the another String, Otherwise false.

            String dbValue="";
            boolean endValue="end".endsWith(dbValue);
if(endValue)
            {
                  System.out.println("execute block of statement");
            }
As same as the startsWith method variable  endValue will be  true and if statement get executed.

No comments:

Post a Comment