java – Why is contains (".") 'True' but split (".") Gives me an empty array?

Question:

Let's take this method:

public static void getDecimalPart(double n) {
    int decimales = 0;

    // convertimos el valor a string
    String decimalPartString = String.valueOf(n);

    // comprobamos si contiene punto de decimales
    if (decimalPartString.contains(".")) { 
        // lo partimos y lo ponemos en un array
        String[] doubleArray = decimalPartString.split(".");
        // calculamos los decimales
        decimales = (int) (Double.valueOf(doubleArray[1]) * (Math.pow(10, doubleArray[1].length()-2)));
    }

    // imprimimos
    System.out.println("El numero " + n + " tiene " + decimales + " decimales");
}

It checks if the string contains(".") And if so it does split(".") … then …. why when I execute ?:

public static void main(String[] args) {
    getDecimalPart(1.25698);
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at q1607.Q38239413.getDecimalPart (Q38239413.java:25) at q1607.Q38239413.main (Q38239413.java:14)

Debugging even puzzles me even more since the array is completely empty, it does not give the IOOB for requesting position 1 and that it does not exist, but rather:

doubleArray = []

What am I not seeing or forgetting? , I am sure it is something totally obvious but I do not see it …


Things I have tried:

  • Use comma.
  • Use the system decimal symbol:

     DecimalFormat format=(DecimalFormat) DecimalFormat.getInstance(); DecimalFormatSymbols symbols=format.getDecimalFormatSymbols(); char sep=symbols.getDecimalSeparator();
  • In the end I have done the different method, but I continue with the intrigue of what is happening.

Answer:

Because in the split the string you are passing is a regular expression (regex) and within regular expressions the period "." it has a special meaning. If you want to use it as a period you have to escape it "\\."

While the contains method does not ask for a regex but a String and therefore it works as you expect.

In java it would look like this:

String[] palabras = linea.split("\\.");

To expand the answer a bit, in regular expressions the period is a wildcard, which means that it can be used to capture any character. You have more info at RegexOne

Scroll to Top