how to remove or avoid the error of "exception in thread main java.lang null pointer exception" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how to remove or avoid the error of "exception in thread main java.lang null pointer exception"

24th Jul 2016, 5:59 PM
Mohammad Bhanpurwala
Mohammad Bhanpurwala - avatar
5 Answers
+ 2
This simply means that you are trying to reference an object which hasn't been initialized, look at your stack trace it will tell you which line in your code your failing in, and as suggested but a try catch statement, if this object absolutely has to be initialized, then throw an exception or try handling the exception by making sure the object is initialized, also a simple null check on the object can be used before the object is used. If null, initialize the object, if the object is referencing an external resource such as a file or a url, it's best to throw an exception stating that because it would not make sense going on if your application needs to use that resource but can't find it. Short answer, do a null check, if(obj == null) but if the object your trying to initialize depends on the jvm to initialize it and you suspect that it might fail then use a try catch, handle the exception wen possible or throw an exception with an appropriate message for the user/or for debugging purposes.
25th Jul 2016, 12:42 AM
Eric Gitangu
Eric Gitangu - avatar
+ 1
can you send the codes?
24th Jul 2016, 6:03 PM
Dhiman Das
Dhiman Das - avatar
+ 1
use Try catch but it also depends upon ur code.
24th Jul 2016, 6:44 PM
Bhavesh Jangale
Bhavesh Jangale - avatar
0
i have been using try catch but yet the error doesn't go it seems to be much complicated !!!! actually my code is related to array ob object using constructor.... with bufferedreader...
25th Jul 2016, 3:16 AM
Mohammad Bhanpurwala
Mohammad Bhanpurwala - avatar
0
If it involves a bufferedreader then it means that you can't find the resource you are trying to read from thus your buffeted reader object remains null, try entering the whole uri/file path in your terminal or cmd(pc) if if fails to find/open it, it means that your resource can't be located, several things if your filepath has spaces or if your reader is reading your path as escape sequences rather than a '/' then you might need to use '//' to differentiate it from an escape sequence, try it on your prompt and see if it opens, for example in cmd prompt if you enter http://www.google.com, it'll open your browser and to Google, even adding a query like https://www.google.com/search?q=null%20exception, it should navigate to that resource, try and see if you can find the resource manually.
25th Jul 2016, 3:31 AM
Eric Gitangu
Eric Gitangu - avatar