Java
How to avoid NullPointerException in Java
Most of the developer’s idea is null checks makes the code less understandable and less reliable. Tony Hoare, who invented null references, calls them “a billion-dollar mistake”.
In object-oriented computer programming, a null object is an object with no referenced value. There are several places where null checking comes up,
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if they were an array.
- Throwing null as if it were a Throwable value.
The first thing you need to consider to avoid NullPointerException, is try to avoid use null values. So try to have fields and local variables with non-null default values.
When you are writing your code you have control over the code. If null is a valid response, you have to check for it.
public void method(Object object) {
if (object == null) {
// do something
}
}
Otherwise, avoid using nulls as a response. When methods that return collections or arrays, return empty collections or arrays instead of nulls.
Since java 7 you can use Objects methods,
Objects.isNull(object)
Objects.nonNull(object)
Objects.requireNonNull(object)
Objects.equals(object1, object2)
Since java 8 you can use Optional class ,
object.ifPresent(obj -> ...)
Advantages of Java 8 Optional is null checks are not required, no more NullPointerException at run-time and you can develop clean and neat APIs.
In special cases like Strings and Collections you can use apache commons utility methods,
public static boolean isEmpty(CharSequence cs) //apache CollectionUtils
public static boolean isEmpty(Collection coll) //apache StringUtils
public static boolean isEmpty(Map map) //apache MapUtils
An alternative solution is to never return null and instead use the Null Object pattern. The null reference to convey the absence of an object, you can use an object which implements the expected interface, but whose method body is empty, it does nothing. The advantage of this approach over a working default implementation is that a null object is very predictable and has no side effects.
public interface Animal {
void makeSound() ;
}
public class Dog implements Animal {
public void makeSound() {
System.out.println("woof!");
}
}
public class NullAnimal implements Animal {
public void makeSound() {
// body is empty, it does nothing
}
}









49 COMMENTS
Most manufacturers offer tablets of Cialis, meant to be swallowed whole with water, but chewable options have begun to hit the market, too buy cialis online us
American Urological Association Erectile Dysfunction Clinical Guidelines Panel cialis without a doctor’s prescription
Thanks for your blog, nice to read. Do not stop.
ECT was developed as a treatment option for TNBC patients, given the absence of viable therapeutic targets in this BC subtype cialis with dapoxetine
As part of our holistic approach to health care, we assess your health and identify underlying causes of your symptoms viagra pills for women
canada drugs
I like the efforts you have put in this, regards for all the great content.
Your blog is a treasure trove of wisdom and positivity I appreciate how you always seem to know just what your readers need to hear
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
The point of view of your article has taught me a lot, and I already know how to improve the paper on gate.oi, thank you.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.com/sl/register?ref=PORL8W0Z
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
UID_53166217###
Yuk, lihat info terkini seputar stok elpiji 3 kg di Batu, cek di sini, teman-teman! 📢🔥 Info Stok Elpiji 📰👈 Jangan sampai kehabisan ya! 😊🙏
Dapatkan info terbaru dari Berita Dana terbaru setiap harinya.
UID_63849688###
x twitter viral Video Bocor Bulan Sutena
x twitter viral Video Bocor Bulan Sutena
x twitter viral Video Bocor Bulan Sutena
UID_72942561###
Berita Hot! 🔥🔥 Isa Rachmatarwata Tersangka Kasus Jiwasraya Buntut kerugian negara hingga 16,8 Triliun! 😲😲
UID_53550706###
Berita terbaru! 🔥 Isa Rachmatarwata Ditahan Kejagung dalam kasus Jiwasraya. 🚔👮♂️
UID_57092237###
Berita gembira! 🎉 Pasokan Gas 3 Kg di Kramat Jati Kembali Normal 🎊 Siap-siap belanja gas, ya! 💪🔥
UID_72339950###
Heboh! 📣🔥 Unjuk Rasa di Polda Jatim 📢 Menuduh Jokowi Terlibat Korupsi! 😱🔍
UID_27764099###
Ini yang di ganti >>> “Bingung Kenapa 😕❓” Federasi Sepak Bola Pakistan Disanksi FIFA “Baca Penyebabnya Disini! 🧐🔍”
UID_74743238###
Ini dia! 🎉🎉 ASN BKN Ubah Pola Kerja yang baru dan efisien! 🎉🎉.
UID_83344528###
Inilah 🎉🎉 Pupuk Inovatif Kebun Riset Kujang yang bikin Wamen BUMN bangga! 💪🏻🇮🇩
UID_21891068###
Takjub 😮 dengan fenomena serbu gas? Yuk, baca Warung Tatang Diserbu Warga dan temukan faktanya! 🕵️♀️👀
UID_25978847###
situs terbaik hanya di slot gacor agentotoplay
UID_95859078###
Baru-baru ini, para pemain Mahjong Wins 3 dikejutkan dengan bocoran RTP yang diklaim bisa meningkatkan peluang kemenangan secara signifikan. Banyak yang percaya bahwa informasi ini membantu mereka mendapatkan hasil yang lebih konsisten dalam permainan. Jika Anda ingin tahu lebih lanjut, cek bocoran RTP Mahjong Wins 3 hari ini dan lihat apakah strategi ini benar-benar efektif.
UID_57331425###
Skandal terbaru mengguncang komunitas pecinta game slot setelah seorang admin terkenal, Rachel, dikabarkan tertangkap membocorkan pola kemenangan Gate of Olympus. Banyak yang bertanya-tanya apakah informasi ini benar-benar akurat atau hanya sekadar rumor yang beredar di kalangan pemain. Simak lebih lanjut detailnya dalam artikel admin Rachel tertangkap bocorkan pola Gate of Olympus.
UID_17136916###
Kisah inspiratif datang dari seorang tukang ojek online asal Tangerang yang berhasil membawa pulang hadiah fantastis setelah bermain Mahjong Ways 2. Dengan modal kecil, ia sukses mengubah nasibnya dan meraih kemenangan besar senilai 200 juta rupiah. Penasaran bagaimana caranya? Simak kisah lengkapnya di artikel tukang ojek online menang 200 juta dari Mahjong Ways 2.
UID_87427935###
Cek yuk! 🚍👮♂️Operasi Keselamatan 2025 Polres Ciamis Siapa tahu bus favoritmu jadi sasaran! 😱👍
UID_83003169###
Kenalan yuk! 🤝 Dengan guru inspiratif ini, Guru Dede Sulaeman yang mengajarkan cara merapikan pakaian di kelasnya. 👕👚🎓
UID_97211224###
Yuk, sehat bersama! 👨⚕️👩⚕️ Cek kondisi tubuh kamu di Program Cek Kesehatan Gratis sekarang juga! 💉🌡️ Selalu jaga kesehatan, ya! 🏥💖
UID_12835053###
test aje nieeeeee
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Hello, you used to write fantastic, but the last several posts have been kinda boring… I miss your super writings. Past few posts are just a little bit out of track! come on!
Merely wanna input on few general things, The website design and style is perfect, the content is very excellent. “Art for art’s sake makes no more sense than gin for gin’s sake.” by W. Somerset Maugham.
Wow! This could be one particular of the most helpful blogs We’ve ever arrive across on this subject. Basically Wonderful. I am also an expert in this topic so I can understand your effort.
Yo, been playing on juwa6game lately and gotta say, it’s pretty legit. Good selection of games and haven’t had any major issues. Give juwa6game a try, you might dig it.
Time to get back into the game! 80 jili login here I come! Click here 80 jili login to log in and play.
Just signed up for hcm66bet.net. Their signup bonus looks pretty sweet. Hope it translates into some actual winnings! Visit: hcm66bet
Thanks for the ideas you share through this site. In addition, quite a few young women exactly who become pregnant usually do not even try and get medical insurance because they worry they would not qualify. Although some states today require that insurers give coverage irrespective of the pre-existing conditions. Fees on these guaranteed programs are usually bigger, but when taking into consideration the high cost of health care it may be the safer way to go to protect your own financial future.
In accordance with my research, after a foreclosures home is sold at a sale, it is common to the borrower in order to still have the remaining unpaid debt on the mortgage loan. There are many financial institutions who try and have all expenses and liens paid back by the following buyer. On the other hand, depending on a number of programs, legislation, and state legislation there may be quite a few loans that aren’t easily settled through the switch of lending products. Therefore, the responsibility still rests on the debtor that has got his or her property in foreclosure process. Thanks for sharing your notions on this weblog.
Great site. A lot of useful info here. I am sending it to several friends ans also sharing in delicious. And naturally, thanks for your effort!