0

I am trying to figure out how to copy some elements from one array to newly created one.

I create an array arr, filter elements from another array str and if its elements match checkPalin condition I want to add them into arr, but I struggle to do so, my IDE underscores arr array.

String [] arr;
        for (int i=0; i<str.length; i++){
            if(checkPalin(str[i])==true){
                arr[i] = str[i];
            }
        }
        return arr;
JohnPix
  • 1,595
  • 21
  • 44
  • 1
    per your posted code, `arr` is and remains null, and so `arr[i]` should throw a NPE. Best to initialize it first, for example, something like: `arr = new String[str.length];` – Hovercraft Full Of Eels Jul 11 '21 at 15:05
  • 2
    Side note, this: `if(checkPalin(str[i])==true){` is better written as `if (checkPalin(str[i])) {` – Hovercraft Full Of Eels Jul 11 '21 at 15:05
  • 1
    You forgot to initialize variable `arr` that's why IDE is hightlighting line `arr[i] = str[i];` since variable `arr == null`. Your code should looks like this: ```java String[] arr = new String[str.length]; ``` – Martin Dendis Jul 11 '21 at 15:11

0 Answers0