2

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
  • 2
    char[] storage is wrong. Because you create another storage which is just in that method. You should use this.storage or just remove char[] Commented Jul 5, 2020 at 20:11

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Thanks so much. I always get the this keyword messed up. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.