I have a simple exercise where I call a Thread and subsequently the run() method.
I do however get a NullPointerException.
Struggling to figure out why this exception is there.
package practice;
import java.util.Date;
import java.text.SimpleDateFormat;
class IdDisplay implements Runnable
{
String idNumber;
IdDisplay(String ID)
{
this.idNumber = ID;
}
char [] idMine = this.idNumber.toCharArray();
public void run()
{
for(int i = 0; i < idMine.length; i++)
{
System.out.print(idMine[i] + " ");
try
{
Thread.sleep(1000);
}
catch(InterruptedException in){}
}
}
}
public class Practice
{
public static void main(String[]args)
{
String name = "Arian";
String age = "38";
String id = "7401195021087";
int ageInt;
int year;
int yearBorn;
System.out.println("Welcome " + name + " your age is " + age + " and your ID number " + id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Date date = new Date();
year = Integer.parseInt(sdf.format(date));
ageInt = Integer.parseInt(age);
yearBorn = year - ageInt;
System.out.println("You were born in " + yearBorn);
IdDisplay idClass = new IdDisplay(id);
Thread tt = new Thread(idClass);
tt.start();
}
}
Why do I get this NullPointerException.
Regards
You have two instance fields declared:
and
The initializer of the second one assumes the first one is not
null, which it is to start with, hence the exception. Instance initializers are processed prior to entry to the constructor.Instead, move that initialization into the constructor:
Also strongly recommend declaring all of your fields in one place (I prefer them at the beginning of the class, but where you put them is a matter of style; that you put them together is a more substantial maintenance consideration). (Caveat to the general rule: There is an argument, in the case of fields backing accessors, for declaring the field next to the accessor.) And some vertical whitespace between things can be useful.
The complete updated
IdDisplayclass: