Home Ask Login Register

Developers Planet

Your answer is one click away!

Md. Rayhanuzzaman Roky February 2016

Copy all mobile Number From a text file java code error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
    at java.lang.String.charAt(Unknown Source)
    at pdfToExcel.FileRead.mobile_number(FileRead.java:15)
    at pdfToExcel.FileRead.remove_other(FileRead.java:45)
    at pdfToExcel.FileRead.main(FileRead.java:65)

import java.io.*;

public class FileRead {

  public static void mobile_number (String line){
    int len = line.length();
        for(int i=0;i<len;i++){
            String res = "88";
            if(line.charAt(i)=='0' && line.charAt(i+1)=='1'){
                if(line.charAt(i+2)>='5' && line.charAt(i+2)<='9' ){
                    if((line.charAt(i+10)>='0' && line.charAt(i+10)<='9')){
                        res+= line.substring(i+3, i+10);
                    }else if((line.charAt(i+11)>='0' && line.charAt(i+11)<='9')){
                        res+= line.substring(i, i+11);

                 }else if(line.charAt(i+2)=='1' && line.charAt(i+3)=='9') {
                        if((line.charAt(i+10)>='0' && line.charAt(i+10)<='9')){
                            res+= line.substring(i+4, i+10);
                        }else if((line.charAt(i+11)>='0' && line.charAt(i+11)<='9')){
                            res+= line.substring(i, i+11);
            if(res.length()>9) System.out.println(res);


public static void remove_other(String l){
    String str="";
    for(int i=0;i<l.length();i++){
        if(l.charAt(i)>='0' && l.charAt(i)<='9'){
        if(str.length()>9) mobile_number(str);

public static void main(String[] args) throws IOException {

    File f=new File("C:\\        


Ktchook February 2016

You use 'i' as an iteration counter, and it grows up to line.length:

int len = line.length();
for(int i=0;i<len;i++){...}

Imagine what happens when 'i' is at some point equals to line.length -1 and it encounters such instruction as

if(line.charAt(i+10) == '9') {...}

E.g. when line.length = 10 you try to get 19-th character of it.

Stefan Freitag February 2016

If I read your code and the stack trace right, I can assume that the method mobile_number is called with a string that has at least 10 characters. This line is doing so:

if(str.length()>9) mobile_number(str);

There are no assumptions about the maximum lenght of the string. You try to access separate character of the string like


but never check if the position (i.e. i+11) is pointing to a character within your string. For some positions this may hold, but for others you will receive the mentioned StringOutOfBoundsException.

Post Status

Asked in February 2016
Viewed 1,304 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life