This question might be asked in as interview to judge logic on how you are going to achieve without providing you the length() method to calculate the String length easily.

Tips to Think ....

1. As we know that in Java String doesn't end with the NULL character with in C it ends with the NULL character.
2. To get to the end of String we have nothing as a mark in Java but in C we can check for the NULL character.
3. Now have to think to get the mark to the end of the String.
4. One way of doing is to caught the Exception if JVM will throw "StringIndexOutOfBoundsException" if we try to access the extra index of the String.

Steps to do :

1.Initialize a count i.e c=0;
2. Run the while loop making it true ( goes infinite looping ).
3. Within the loop access the String using charAt() at each index.
4. After accessing it last index if it try to access the next index which is not actually present in the memory will will raise to "StringIndexOutOfBoundsException" and we need to caught the exception within try-catch block.
5. Keep Increasing the counter after each iteration.
6. Print the Counter at the catch block will give the length of the String.
7. Use the break statement to break the infinite looping with the while(true).

Program

public class Lab1 {

    public static void main(String[] args) {
  
        String s1="sushant";
 int count=0;
 int i=0;
 while(true){
        try{
    s1.charAt(i);
           i++;
    count++;
        }catch(StringIndexOutOfBoundsException e){
    System.out.println("String Length is : "+count);
    break;
       }
  }
     }
}





Related Posts:

  • Abstract class in java When we use an abstract modifier before the name of any user-define class then it is called as an abstract class. Abstract class in java has only method signature whose implementation must be in its sub-classes. Importan… Read More
  • Interface in Java Interface is a keyword in java and also a concept in java to over come the limitation of not supporting multiple inheritance by java. Now with the concept of interface we can have implement multiple interface full filing th… Read More
  • Abstract keyword in java Abstract is a keyword in java. So its a reserved word in java. general meaning of abstract is to hide the implementation, only show the outer structure. Now in computer science its meaning is that user can have their own i… Read More
  • Accessibility of access modifiers in java Read More
  • Dynamic Dispatch in Java It is a concept in java to achieve the Dynamic / Run-time polymorphism. It is the process of assigning sub-class object in super type reference later if needed that sub-class object can be type-caste into its super type. Dy… Read More

0 comments:

Post a Comment

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

201978

Online Members

Live Traffic