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).
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;
}
}
}
}
0 comments:
Post a Comment