I am trying to iterate through a string and save the characters in a character array. It iterates perfectly and prints the characters but when I try to save the characters in the Array or in a List, it gives me NullPointerException. Can anyone point out the mistake I am doing here?

try {

                    List<String> result = Files.readAllLines(Paths.get("C:\\Users\\Rehan\\Documents\\NetBeansProjects\\Marks\\build\\classes\\marks\\input.txt"));
                    List<Character> marksC = null;                     
                    for(String line : result ){
                      System.out.println(line);
                      //Reversing each line of string                        
                      StringBuilder sb =  new StringBuilder(line);
                      sb.reverse();
                      String RS = sb.toString();
                      System.out.println(RS);
                      //To read first sequence of integers in reversed string                            
                      StringCharacterIterator si = new StringCharacterIterator(RS, 0);
                        for(int i = 0; i <= RS.length() ; i++){
                            while (si.current()!=' '){
                                char c = si.current();
                                marksC.add(c); //This line giving NullPointerException
                                System.out.println(c);
                                si.next();
                            }
                            break;
                        }
                    }
                    JOptionPane.showMessageDialog(null, result);

    }

Dani AI

Generated

correctly identified the immediate crash: the collection that receives characters was never created. Beyond that, there are a few fragile bits in the original approach worth fixing (loop bounds, iterator end condition, and relying on a single space as a terminator).

Initialize the collection before you add to it. A simple and robust alternative is to avoid StringCharacterIterator entirely and iterate the char array:

List<Character> marksC = new ArrayList<>();
for (char c : RS.toCharArray()) {
    if (Character.isWhitespace(c)) break;   // stop at first whitespace
    marksC.add(c);
}

If the goal is to capture the first run of digits, use a regex to extract them (safer and clearer than manual iteration) and then convert to characters or numeric values:

Matcher m = Pattern.compile("^\\d+").matcher(RS);
if (m.find()) {
    String digits = m.group();
    List<Integer> values = digits.chars()
                                 .map(ch -> ch - '0')
                                 .boxed()
                                 .collect(Collectors.toList());
}

If you must keep StringCharacterIterator, guard against the DONE sentinel and whitespace to avoid infinite loops:

List<Character> marksC = new ArrayList<>();
char ch = si.current();
while (ch != CharacterIterator.DONE && !Character.isWhitespace(ch)) {
    marksC.add(ch);
    ch = si.next();
}

Notes: avoid using <= on length checks (off‑by‑one); prefer Character.isWhitespace over comparing to a single space; and remember to initialize collections before use. These changes address the NullPointerException and make the extraction logic more robust for different inputs.

Looks like marksC has been declared but not initialised.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.