9 Dec 2017

Write a program in java to find the length of given String.


Here is the three way to find the length of given string.these are given following.

Method #1



class StringLength
{
          public static void main(String[] args)
          {
                   String str="hi this is String";
                   int count=0;
                   for(char c:str.toCharArray())
                   count++;
   System.out.println("Length of string by userdefined method ::"+count);
          }
}                

Output:
Method #2



class StringLength
{
       public static void main(String[] args)
       {
              String str="hi this is String";
              System.out.println("Length of string library function ::"+str.length());
       }
              
Output:
Method #3


class StringLength
{
       public static void main(String[] args)
       {
              String str="hi this is String";
              int i=0,cc=0;
              try{
                    for(i=0,cc=0;0<=i;i++,cc++)
                    str.charAt(i);
                   }
             catch(Exception e){
                    System.out.println("Length of string by exception:: "+cc);
                     }
       }
              
Output: