Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Amit Dhamankar
Amit Dhamankar
4,163 Points

Is this syntax of constructor Right?

public PezDispenser(String characterName){ String mCharacterName = characterName; mPezCount = 0; }

If yes when I pass a value from Example.java in this case "Yoda" it is returning null. i.e., instead of "Yoda" it is printing "null".

1 Answer

Hello Amit!

You want to make sure to declare String mCharacterName outside of the constructor, and then to just assign it as mCharacterName = characterName inside of the constructor. What you are doing now is scoping mCharacterName inside of the constructor only, so that when you call the instance member mCharacterName it is still null.

So, something like this is what you want:

public class PezDispenser{
    // instance members
    String mCharacterName;
    Integer mPezCount;

    public PezDispenser(String characterName){
        mCharacterName = characterName;
        mPezCount = 0;
    }
}
Amit Dhamankar
Amit Dhamankar
4,163 Points

Thank you Eric. I took the whole day to figure out. And u solved in a jiffy.