Char Array to String with classes

Viewed 63

I am trying to write a class that has methods according to a homework assignment. The class input is a string that is turned into an char array. I want to return the char array as a string inside the method originalChar. Here is my code:

public class Problem5 {
    public static void main(String[] args) {
        CharacterArray array1 = new CharacterArray("Cool");
        System.out.println(array1.originalChar());
    }
}

class CharacterArray {
    char[] storage;
    String formForReturn;

    CharacterArray() {
    }

    CharacterArray(String s) {
        char[] storage = new char[s.length()];
        for (int i = 0; i < s.length(); i++) {
            storage[i] = s.charAt(i);
        }
    }

    public String originalChar() {
        String formForReturn = new String(storage);
        return formForReturn;
    }
}

The error I get is NullPointerException, which to my understanding means I am trying to reference something that doesn't exist. I'm not sure how I troubleshoot this and how to resolve this problem. Some help would be much appreciated.

1 Answers

The way to access instance variable char[] storage; is to use this keyword which represents current object. Otherwise, with your current solution, what you return is empty which causes NullPointerException. Because you create another storage instead of using existing one in the class.

Also you can write your originalChar() method in a shorter way:

class CharacterArray {
    char[] storage;

    CharacterArray() { }

    CharacterArray(String s) {
        this.storage = new char[s.length()];
        for (int i = 0; i < s.length(); i++) {
            storage[i] = s.charAt(i);
        }
    }

    public String originalChar() {
        return new String(this.storage);
    }
}
Related