Why does my java code throw a null pointer exception - how to fix?

preview_player
Показать описание
A common reason for Null Pointer Exceptions in Java is a variable redeclaration instead of instantiation. Learn what that means, how to avoid it, and how to spot it, in this presentation.

# FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration

- Any 'variables' we instantiate need to be 'fields' rather than variables
- We want to instantiate them in the setup method rather than redeclare them

- To make the code readable
- I could do that
- but I don't think I would have declared a new variable after the refactorings because I have a working code example that I'm moving.

# In General

- Try to write one test at a time so that if you have a problem it is easier to identify where the problem is
- Try to write working isolated tests and then refactor to a more general solution when you need it - that way, you know it was working, so you just have to work backwards to find out what went wrong
- Try to use automated IDE refactoring rather than move code around manually
- Use the IDE syntax highlighting to help spot any issues

For more details see Blog Post:

SlideShare:

Рекомендации по теме
Комментарии
Автор

Thank you, I am a novice java programmer and this really helped me a lot.

vladey
Автор

It didn't fix my problem but it made me check what was being sent by the method, and that led me to fix my problem, thank you so much.

Blue-sixw
Автор

how are you instantiating the interface?

aishwaryjain
Автор

Thank u so much ....helped me a lot ..

vasubhagya
Автор

Thank you very much, that was a huge help! :)

unicodeofdeath
Автор

I have done all the above steps that you mentioned to avoid null pointer exception but even then I am getting null pointer exception for
in my Base class. Can you please help with regard to what could be other possible reason for null pointer exception. Please help

Thanks in advance.

deea
Автор

Hi when i am trting to delete the records, records get duplicated how to resolvd it

priti
Автор

Attempt to invoke virtual method 'int on a null object reference

Chetan-xhsm
Автор

My textfield is literally not fucking null, and it throws anyways

SolidPayne