Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn’t the following code give error even if the substring function is given number higher than indexing

class HelloWorld 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello, World!"); 
        String a="hi hello";
        a = a.substring(8);
        System.out.println(a);
    }
}    

In this program I entered the value 8 in substring but that should give an error but in output it doesn’t give error and doesn’t even print anything except "Hello, World!"

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

String.substring(int begin) throws IndexOutOfBoundsException – if beginIndex is negative or larger than the length of this String object.

String a="hi hello";

That String has a length of 8. So when you call it, the first index is the 8’th index. As you have noticed it would be an index out of bounds exception if you did charAt(8). For substring you get a zero length string returned.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading