0

My code is as follows. After the creation of MyThread object the control is going directly to line 1 ( commented in code ) and then throwing NullPointerException. What is the reason of this behavior ? i want to know why s is not initialized, i am using the constructor and passing the value while creating the object for it ?

public class ClassOne {

    public static void main(String[] args) {
        MyThread t = new MyThread("name");
        Thread tone = new Thread(t);
        tone.start();
        for (int i =0; i<=10;i++) {
            System.out.println(i);
        }
    }
}

class MyThread implements Runnable {
    String s;
    MyThread (String s) {
        this.s=s;
        System.out.println("Constructor");
    }

    char[] ch = s.toCharArray();             // line 1
    public void run() {
        for (char c : ch) {
            System.out.println(c);
        }
    }
}
  • 2
    You don't need a MyThread class. Use the JVM Thread and give it a Runnable. The answer is obvious: the String s is not set. – duffymo Jan 24 '18 at 15:19
  • @duffymo that is what exactly i want to know why s is not initialized, i am using the constructor and passing the value while creating the object for it ? – springcloudlearner Jan 24 '18 at 15:36
  • You asked this question 20 minutes ago. A debugging session in an IDE would have given you the answer in minutes. You declare a static string, which is associated with a class, but set it for this. I would suggest that you are assuming it's set, but it's not. Check your assumptions. Run in a debugger, see that it's null, and make changes to fix it. You're assuming that this code is correct. Believe the JVM. It's not. – duffymo Jan 24 '18 at 15:39
  • @duffymo - Bro please read it carefully, I am not wrapping a Thread inside Thread instead I am wrapping a object of class which implements Runnable inside a Thread object, this is exactly what is required to start and run a Thread using Runnable ( check example 2 https://www.javatpoint.com/creating-thread ) – springcloudlearner Jan 24 '18 at 15:46
  • @duffymo - I tried debugging and the control flow directly jumps from statement "MyThread t = new MyThread("name");" to line 1 ( commented ) and the constructor does not even gets executed. Correction - String s in non - static. – springcloudlearner Jan 24 '18 at 15:47
  • Gotta figure that out. Good luck. – duffymo Jan 24 '18 at 15:48
  • The ANSWER is that the line 1 is not inside any method and as soon as an object is created for MyThread class the instance flow gets executed in which line 1 is executed before the constructor and no value is assigned to s. – springcloudlearner Jan 26 '18 at 09:28

0 Answers0