-1

I have two string

String s1 = "";
String s2 = "";
Boolean check = s1 != null && s2 != null && s1.substring(1) != null;
 then return check;

Why this code is throwing StringIndexOutOfBoundException? If s1 ="" then why it is checking for s1.substring(1) != null when s1 != null is false ? It should return false not throw Exception? How to resolve this?

Rachit Munjal
  • 133
  • 1
  • 7
  • 4
    an empty string "" has a different meaning than a `null`, they are not same – Naman Jul 03 '20 at 10:58
  • would be easier to have your boolean check for StringUtils.isNotBlank(s1) && StringUtils.isNotBlank(s2) – Paul Jul 03 '20 at 11:00
  • 1
    Possibly related: [Difference between null and empty (“”) Java String](https://stackoverflow.com/q/4802015) – Pshemo Jul 03 '20 at 11:16

3 Answers3

2

A null string is not the same as an empty string. In Java, the String class possesses a method for checking if a String is empty. Rewrite your empty checks as !s1.isEmpty() && !s2.isEmpty().

Similarly, a substring doesn't return null. It can return an empty string if the index is the string's length, but otherwise will throw an exception for invalid indexes. Perhaps you meant to check s1.substring(1).isEmpty() in that last condition? In saying that, as far as I can tell that is equivalent to checking if s1.length() > 1, which is a bit clearer.

Tom
  • 355
  • 4
  • 11
0

You can use below two functions for an empty string check.

                StringUtils.isEmpty(str)
                StringUtils.isBlank(str)
Sounak Saha
  • 852
  • 1
  • 9
  • 21
0

The program is returning an error because the first 2 conditions of the boolean are true, "" and null are not the same, so the program keeps checking all the conditions, but maybe substring is returning an error because you can not substring a string with lenght 0.