Avoiding NullPointerExceptions
Patterns for safe code.
Avoiding NullPointerExceptions is a free Android Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Goal: No NPEs
A NullPointerException, or NPE, happens when code uses something that is actually null. Kotlin is designed to make these rare.
This lesson brings together the tools you have learned and warns about the few ways an NPE can still sneak in.
The !! Operator
The not-null assertion !! tells the compiler to trust you that a value is not null. If you are wrong, it throws an NPE.
It removes safety, so use it rarely and only when you are certain.
fun main() {
val name: String? = "Ada"
println(name!!.length) // works, name is not null
}!! Can Crash
If the value really is null, !! throws a NullPointerException at that exact line.
This is the main way to reintroduce the very problem Kotlin prevents. Avoid !! when a safe call or Elvis would do.
val name: String? = null
println(name!!.length)
// throws KotlinNullPointerExceptionPrefer Safe Alternatives
Almost any use of !! can be rewritten with ?. and ?:. The safe version cannot crash.
Compare the risky and safe forms below.
// Risky:
val len1 = name!!.length
// Safe:
val len2 = name?.length ?: 0Validate Early
Handle null at the boundary of your code, then work with non-null values inside. Use Elvis with return or throw to reject missing input up front.
After the guard, the value is smart-cast to non-null.
fun length(s: String?): Int {
val text = s ?: return 0
return text.length
}requireNotNull
When a null truly means a bug, requireNotNull throws a clear error and returns the non-null value.
It is more descriptive than !! because you can add a message.
fun start(config: String?) {
val c = requireNotNull(config) { "config missing" }
println(c.length)
}Platform Types from Java
Values coming from Java have unknown nullability, called platform types. Kotlin cannot guarantee they are non-null.
When you use Java libraries, declare the expected type explicitly and handle null defensively.
// From Java: String maybe = obj.getName();
val name: String? = obj.name // be safe
println(name?.length ?: 0)lateinit Pitfall
A lateinit var lets you delay initializing a non-null property. But using it before assignment throws an exception.
Only use lateinit when you are sure the value is set before any access.
lateinit var config: String
fun read() {
println(config.length)
// crashes if config was never set
}Defaults Instead of Null
Often you can avoid nullability entirely by choosing a sensible default value. An empty string or empty list is frequently better than null.
Fewer nullable types means fewer chances for an NPE.
fun main() {
val tags: List<String> = emptyList()
println(tags.size) // 0, never null
}A Safe Pipeline
This program reads an optional value, transforms it safely, and always produces a result. No !!, no crash.
This is the style to aim for in real Android code.
fun main() {
val input: String? = null
val result = input?.trim()?.uppercase() ?: "N/A"
println(result) // prints: N/A
}Best Practices
Prefer non-null types, handle null at boundaries with Elvis, and use ?.let for optional actions. Save !! for the rare cases where null is impossible.
Follow these habits and NullPointerExceptions become a thing of the past.
val safe = data?.value ?: default
data?.let { handle(it) }Quick Check
Test your understanding of avoiding NullPointerExceptions.
Recap
NPEs in Kotlin usually come from !!, platform types from Java, or uninitialized lateinit values. Avoid them by preferring non-null types and safe operators.
Use ?., ?:, ?.let, and validation like requireNotNull to keep code crash-free. You have now completed the essentials of Kotlin null safety.
Frequently asked questions
Is the “Avoiding NullPointerExceptions” lesson free?
Yes — the full text of “Avoiding NullPointerExceptions” is free to read here on the web, and the Android Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.
What will I learn in “Avoiding NullPointerExceptions”?
Patterns for safe code. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Android Academy?
No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Avoiding NullPointerExceptions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Android Academy lesson?
Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Nullable vs Non-Null Types
- Safe Calls and Elvis
- let, also, and Scope Functions
- Avoiding NullPointerExceptions