In: Computer Science
Basic JAVA Question
When we try to run this program, a problem occurs. What is this
problem called? And why does this problem occur here?
public class Main {
public static void main(String[] args) {
PhoneNumber pn = new PhoneNumber();
System.out.println(pn.isTollFree());
}
}
class PhoneNumber {
String number;
public boolean isTollFree() {
return number.charAt(1) == '8';
}
}
-The problem is called the NullPointer Exception.
-The problem occurs here because String number hasn't been assigned any value .It contains Null. But an object reference is being used here :
number.charAt(1) == '8'
If String Number contained some value, this error wouldn't occur.
Proof:
Without Assignment :
With Assignment :
Please comment
below if you have any queries.
Please do give a thumbs up if you liked the answer thanks
:)