Need help with java.lang.NullPointerException error

I’m working on a Java project and when I try to execute it, I receive a “java.lang.NullPointerException” error message.

public class MyClass {
    private String myString;

    public MyClass(String myString) {
        this.myString = myString;

    public void printMyString() {

    public static void main(String[] args) {
        MyClass myObject = new MyClass("Hello, world!");

When I attempt to execute this code, I receive the following error message:

Exception in thread "main" java.lang.NullPointerException
	at MyClass.printMyString(
	at MyClass.main(

I’m not sure why this error notice is appearing or how to resolve it. Can you assist me in troubleshooting this issue? I tried reading this article but couldn’t comprehend it well, and the outcome was not what I had hoped for. Could you please help me?

Hi, the error is because of calling the length() method on a null String object in the printMyString() method. The value of myString is null when called. You can either check if it is null in your code, or set myString to “” in the constructor. I hope this helps :grinning:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.