-2
String[] splittedData = data.split("\\s+");
             
answerString = data + " :";

answerString = answerString +
    wordChecker.imperfectPalindrome(splittedData[0]);

answerString = answerString + 
    wordChecker.imperfectPalindrome(splittedData[1]);

answerString = answerString +
    wordChecker.superAnagrams(splittedData[0], splittedData[1]);

for splittedData[1], IDE throws an ArrayIndexOutOfBoundsException. Is this because of some mistake in array declaration or is this something else?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614

1 Answers1

2

Your splittedData array will take the exact required length to store the results of the .split. If entered data doesn't contain any space, then splittedData will have length 1. If entered data is empty, then it will have length 0.

So if after that you try and access splittedData[1], then the index will indeed be out of bounds

Clarification

In Java, array indices are from 0 (inclusive) to array length (exclusive)

julien.giband
  • 2,467
  • 1
  • 12
  • 19
  • Thank you. Well in that case I should use something other than `.split` because my `data` has a single space in each line. Any suggestions on how I might not exceed the index out of bounds for such `data`? – Obaidullah Ahmed Jun 15 '21 at 12:32
  • If you want to "cut" at space, then `.split` is exactly the operation you need (you can set a limit of 2 just in case there could be 2 spaces one day). then you can either copy the results to a fixed-size array of length 2, or test `if (splittedData.length > 1)` before accessing `splittedData[1]` – julien.giband Jun 15 '21 at 12:52