IF3210 Mobile Application Development · Midterm Study Notes

Mobile Application Development

Comprehensive notes covering all 7 midterm topics · STEI ITB · Semester II 2025/2026
Mobile Platform Architecture SDLC & Agile React Native & Flutter Android SDK ConstraintLayout Material Design Kotlin Null Safety
01

Arsitektur Mobile Platform

Architecture

What is Mobile Computing?

Mobile Computing System = computing systems that can be easily moved physically and whose computing can be used while being moved.

ExamplesLaptops, PDAs, mobile phones, wearables
Key QuestionHow do we develop mobile apps that are extensible, flexible, and scalable?

Distinguishing Aspects of Mobile vs Stationary Computing

Wireless Connectivity

Prevalent wireless network use — mobility and wireless connectivity are orthogonal (independent) concepts.

Small Size

Constrained screen real estate, limited input methods, smaller physical form factor.

Power Sources

Battery-powered; performance must balance power consumption.

Mobile Nature

Used while moving — context-based, task-oriented, situational usage.

Functionality for mobile user

Designed to meet the unique needs and behaviors of mobile users in various contexts.

Four Pieces of the Mobile Problem

  • Mobile User — moving, context-switching, not focused on computing task
  • Mobile Device — hardware with limited capabilities
  • Mobile Application — software optimized for mobile settings
  • Mobile Network — wireless, variable, potentially unreliable

Wireless Communication Generations

0G (1946–1980s)
Early mobile phones in cars/trucks. Voice only, analog, expensive.
1G (1980s→)
Speed up to 2.4 kbps. Analog signal. Technologies: AMPS/DataTac.
2G (1990s→)
GSM (Finland, 1991). Speed up to 64 kbps. Digital voice + SMS + data. Tech: GSM, CDMA, TDMA.
2.5G
Marketing term. 2G + GPRS. Speed: 64–144 kbps. Tech: GPRS, EDGE.
3G (2000s→)
Speed: 114 kbps – 2 Mbps. Broadband, streaming, video. Tech: W-CDMA (UMTS).
4G (late 2000s→)
Speed: 100 Mbps – 1 Gbps. MAGIC: Mobile Multimedia, Anytime Anywhere, Global Mobility, Integrated Wireless, Customized Personal Services. Tech: LTE, WiMAX.
5G (2010s→)
Higher speed & capacity. Supports IoT/CPS, edge computing. Network slicing.

Mobile Application Types

TypeDescriptionExamplesPros / Cons
Text-based AppContent provider, SMS alerts, USSD codesSMS alertsSimple, low-tech
Mobile WebsiteFocus on content, simple interactionNews sites on browserNo install needed
Mobile Web AppWeb-based with application-like experience. HTML, CSS, JS.Gmail, Facebook web+ Single code base, no App Store dependency
− Limited device feature access
Native AppPlatform-specific: iOS (Swift/ObjC), Android (Kotlin/Java)Instagram native iOS+ Faster, full device API access
− Multiple code bases
GamesUsually native, graphics-heavy, often bypass Java API frameworkPUBG MobileHigh performance needed

Application Context Types

Utility Context

Short task-based. Minimal UI. e.g., Timer, Calculator, Weather.

Locale Context

Location-based. Maps, navigation, location-aware discounts.

Informative

Provides information. News, directory, marketing site.

Productivity

Task-based, priority-ordered. Address book, shopping.

Immersive Fullscreen

Focuses user on app. Games. Full-screen experience.

Mobile Platform Architecture Layers

A mobile platform consists of multiple layers from hardware up to developer tools:

HardwarePhysical components — CPU, sensors, screen, radios
OS / KernelCore OS. Linux kernel (Android), XNU (iOS)
Low-level LibrariesNetworking, file systems, multithreading, graphic rendering
RuntimeExecutes code. Android Runtime (ART) replaces Dalvik.
Native LibrariesC/C++ libraries (e.g., OpenGL ES, WebKit, SQLite)
Java/Kotlin API FrameworkHigh-level UI toolkit, Activity Manager, Content Providers, etc.
System / User AppsApps installed on device, including system defaults
Developer ToolsIDE (Android Studio), emulator, language (Kotlin), build tools (Gradle)

Android Platform Architecture

Android platform architecture stack diagram
Figure A. Android platform architecture stack.

Architectural Styles for Mobile Apps

  • Thin-client wireless client-server — logic on server, thin UI on device
  • Thick-client wireless client-server — significant logic on device too
  • Stand-alone applications — works fully offline, no server needed
Virtual Machine Abstraction

A VM (like ART on Android) abstracts hardware specificity, enabling code portability. However, performance considerations are more critical on mobile than desktop due to resource constraints.

02

Model Proses

Process Model

What is SDLC?

Software Development Life Cycle (SDLC) = a structured series of steps to design, develop, test, and maintain software. Goal: ensure software meets user needs and works correctly.

Benefits of SDLC

  • Ensures quality and consistency
  • Efficiency in time and cost
  • Easier maintenance and updates
  • Better team collaboration
  • Adaptability to changes

Core Software Development Activities

ActivityDescription
KomunikasiProject initiation, requirement gathering
PerencanaanEstimation, scheduling, tracking
PemodelanAnalysis and Design
KonstruksiProgramming and Testing
DeploymentDelivery, support, feedback

Process Flow Types

Linear Flow

Sequential — each phase completes before the next starts.

Iterative Flow

Phases repeat in cycles, refining the product each time.

Parallel Flow

Multiple activities run simultaneously in different streams.

Evolutionary Flow

Product evolves through releases (v1 → v2 → vN).

Waterfall Model

The classic linear process model. Each phase must fully complete before moving to the next. You cannot skip two phases back.

Phase 1Rekayasa Kebutuhan (Requirements Engineering)
Phase 2Analisa Kebutuhan (Requirements Analysis)
Phase 3Perancangan Umum/Rinci (General/Detailed Design)
Phase 4Pemrograman dan Pengujian (Programming & Testing)
Phase 5Deployment
Phase 6Perawatan (Maintenance)
Waterfall Problems

Requirements almost always change — Waterfall can't handle this well. Users wait until the end to see the product. Blocking states occur where team members idle waiting for others. Not suited for complex systems with many stakeholders.

Agile Methodology

Agile collects requirements iteratively and evolutionarily. A functionality is completed fully (requirements → code → unit tests) before starting the next.

The Agile Manifesto (4 Values)

Agile Values
  • Individuals and interactions
  • Working software
  • Customer collaboration
  • Responding to change
Over Traditional
  • …over processes and tools
  • …over comprehensive documentation
  • …over contract negotiation
  • …over following a plan

Agile Variants

  • Scrum (sprint-based, 2-week cycles)
  • Kanban (flow-based, continuous)
  • Extreme Programming (XP)
  • Feature Driven Development (FDD)
  • Dynamic Systems Development Method (DSDM)
  • Agile Unified Process (AUP)

SDLC for Mobile Apps — 6 Phases

1. Planning & Requirement Analysis
Identify user needs, business goals, technical feasibility. Define key features, UI/UX expectations, monetization models. Research target audience and competition.
2. UI/UX Design
Wireframing & prototyping (Figma, Adobe XD). User journey mapping. Focus on mobile constraints: screen sizes, touch interactions.
3. Development
Frontend (UI, animations) + backend (APIs, databases) in parallel. Frameworks: Flutter, React Native, or native (Swift/Kotlin). Implement modular code.
4. Testing & QA
Device and platform testing. Automated & manual tests. Beta testing via TestFlight (iOS) or Firebase App Distribution (Android).
5. Deployment & App Store Submission
Comply with Google Play Store & Apple App Store policies. ASO (App Store Optimization). Prepare for approval delays.
6. Maintenance & Update
Collect feedback via Firebase / Sentry. Regular updates for bugs and new features. Ensure OS version compatibility.

Adapted Agile for Mobile — 5 Practices

Scrum / Kanban

Scrum: 2-week sprints. Kanban: continuous flow-based delivery.

Sprint Planning

User Stories & Epics. Prioritize by business value. Define MVP early.

CI/CD

Automate builds (GitHub Actions, Jenkins, Bitrise). Feature toggling for phased rollouts.

User Feedback

Analytics (Mixpanel, Firebase). A/B testing. Adapt backlog based on user needs.

Cross-functional Teams

PM, devs, designers, QA collaborate. Daily stand-ups, sprint reviews, retrospectives.

Key Terms

MVPMinimum Viable Product — the smallest feature set that delivers value to users
SprintA fixed time-box (typically 2 weeks) for delivering a working increment
BacklogA prioritized list of features/tasks to be completed
User Story"As a [user], I want [feature] so that [benefit]" — a requirement in user language
ASOApp Store Optimization — improving metadata for discoverability in app stores
03

Cross Platform

Technology

The Key Challenge: Fragmentation

Each mobile platform has different interfaces, standards, programming languages, APIs, capabilities, and SDKs. Even within the same platform, devices differ in memory, screen resolution, etc.

3 Mobile Development Approaches

Native

Use platform-specific languages and tools.

Android: Kotlin/Java + Android Studio
iOS: Swift/ObjC + Xcode

Mobile Web

Web technologies running in mobile browser. JS, HTML, CSS. Tools: React, Vue, Angular.

Cross-Platform

Single code base targeting multiple platforms. Top tools: React Native, Flutter.

Why Use Cross-Platform?

  • Reusable code across platforms
  • Rapid time to market
  • Robust performance
  • Close-to-native UX
  • Broad audience reach (Android + iOS simultaneously)
  • Greater cost efficiencies

React Native (by Meta/Facebook)

Open-source framework using JavaScript + React to build native apps for Android, iOS, and more. First developed in 2013 internally at Facebook, public release in 2015.

React Native Architecture Components

JSIJavaScript Interface — allows JS to hold a reference to C++ objects and vice-versa. Direct method invocation without serialization costs.
FabricNew rendering system (evolution of legacy renderer). Unifies render logic in C++, uses JSI to control UI directly on native side.
TurboModulesLet React Native interact with native platform APIs not provided by RN. Uses JSI to access native modules.
YogaEmbeddable layout system supporting a subset of CSS (mostly Flexbox). Used by Fabric to position UI elements. Enables code sharing between native and browser.

React Native Render Pipeline

// The 3-step pipeline:
RenderCommitMount

// View Flattening: optimization to avoid deep layout trees
// Views (2) and (3) merged into (1) via diffing algorithm

Core Components (Native Components wrapped for JS)

  • View — basic rectangular container
  • Text — displays text
  • Image — displays images
  • TextInput — text input field
  • ScrollView — scrollable container
  • FlatList — optimized list rendering

Flutter (by Google)

Open-source framework for building natively compiled, multi-platform apps from a single codebase. Uses Dart language. Released as open source in 2017.

Flutter Architecture (Layered)

Dart AppComposes Widgets into UI. Implements business logic. Owned by developer.
FrameworkHigher-level API: widgets, hit-testing, gestures, accessibility, text input.
EngineRasterizes composited scenes. Low-level: graphics (Skia/Impeller), text layout, Dart runtime. Exposes dart:ui API.
EmbedderCoordinates with OS (rendering surfaces, input, accessibility). Manages event loop.
RunnerComposes embedder pieces into an app package. Generated by flutter create.

Flutter Rendering Process (Widget → Pixels)

Widget TreeEverything is a Widget. Stored hierarchically. May be stateless or stateful.
ReconciliationLinear reconciliation (not tree-diff like React) to find which widgets need updating.
LayoutDetermines size and position of each widget.
PaintingAssigns colors, gradients, other visual attributes onto canvas.
CompositingCombines painted widgets into final image (transparency, overlapping, layering).
RenderingConverts composite image to platform-specific GPU instructions.

React Native vs Flutter Comparison

AspectReact NativeFlutter
LanguageJavaScriptDart
ByMeta (Facebook)Google
UI ApproachUses native components via bridge/JSICustom renderer (Impeller/Skia) — draws own widgets
CommunityVery large (JS ecosystem)Rapidly growing
CI/CDEAS (Expo) or third partiesRich default CLI
Best ForTeams with strong JS/Web backgroundTeams with budget for Dart learning; pixel-perfect UI

Framework Choice Guidelines

Choose React Native if…

Your team has strong JavaScript or web background. Easier to reuse existing skills, reduces cost and development time.

Choose Flutter if…

You have enough budget and resources. Dart is not widely used, so learning curve is higher — but the result is consistent pixel-perfect UI across platforms.

04

Intro to Android

Android SDK

What is Android?

  • Mobile OS based on Linux kernel
  • UI designed for touch screens
  • Used on over 80% of all smartphones
  • Powers watches, TVs, cars, and more
  • Open-source. 3+ billion monthly active devices.
  • 2.5+ billion monthly active Google Play users. 2M+ apps.

Android Software Developer Kit (SDK)

  • Development tools: debugger, monitors, editors
  • Libraries: maps, wearables, ML
  • Virtual devices (emulators/AVDs)
  • Documentation at developer.android.com
  • Sample code

Kotlin — The Language for Android

Expressive & Concise

Less boilerplate than Java. Modern language features.

Safer Code

Null safety built-in. Eliminates NullPointerExceptions by default.

Interoperable

100% compatible with Java. Can call Java libraries from Kotlin.

Structured Concurrency

Coroutines for async code without callback hell.

API Levels — Three Key SDK Versions

SDK Version Hierarchy minSdkVersion ≤ targetSdkVersion ≤ compileSdkVersion
minSdkVersionDevice needs at least this API level to install the app.
targetSdkVersionThe API version the app was designed and tested for.
compileSdkVersionThe Android OS library version compiled with (usually latest).

4 Types of Application Components

Activity

A single screen with a user interface. Entry point for user interaction.

Hotel analogy: the registration desk

Service

Performs long-running tasks in the background (no UI).

Hotel analogy: laundry service

Broadcast Receiver

Responds to system-wide announcements (battery low, SMS received).

Hotel analogy: package arrival notification

Content Provider

Manages a shared set of app data (contacts, media).

Hotel analogy: city tour companies

App Building Blocks

Resources (res/)Static content: layout files, images, audio files, strings, colors as XML. Stored separately from code for easy localization and updates.
AndroidManifest.xmlMetadata about the app. Lists all activities, services, receivers, providers. Declares permissions and hardware requirements.
Gradle build filesBuild automation. build.gradle (Module): dependencies, SDK versions. build.gradle (Project): repositories, global config.

Views — Building Blocks of UI

"Everything you see is a View." Views are Android's basic UI building blocks — rectangular elements on screen.

Common View Classes

Display Views
  • TextView — displays text
  • ImageView — displays images
  • ScrollView — scrollable container
  • RecyclerView — efficient lists
Input Views
  • Button — clickable button
  • EditText — editable text field
  • CheckBox — on/off toggle
  • RadioButton — single selection
  • SeekBar — range slider
  • Switch — toggle switch

View Size Options

wrap_contentView is only as big as its content needs to be.
match_parentView expands to fill its parent container.
Fixed dp valueExact size, e.g., 48dp. Use dp not px.

ViewGroups — Layout Containers

FrameLayoutHolds generally a single child View. Stacked on top of each other.
LinearLayoutAligns children in a single row or column. Set android:orientation to horizontal or vertical.
ConstraintLayoutRecommended default. Positions views using constraints. Avoids deep nesting.

Event Handling

// SAM (Single Abstract Method) — concise click listener
button.setOnClickListener { view ->
    /* handle click */
}

// Modify a View dynamically
val resultTextView: TextView = findViewById(R.id.textView)
resultTextView.text = "Goodbye!"

// Event flow: User interacts → Event fired → Check callback → Execute or ignore

Gradle — Build System

  • Build automation system
  • Manages the build cycle via a series of tasks (compile Kotlin, run tests, install APK)
  • Determines proper task order and manages dependencies

Accessibility Best Practices

Contrast Ratio Requirements Small text: ≥ 4.5:1 contrast | Large text: ≥ 3.0:1 contrast
  • Touch target size: at least 48dp × 48dp
  • Set contentDescription on images and controls for screen readers
  • Use TalkBack — Google's screen reader for Android
  • Use Switch Access for users who cannot use touch
05

Layouts

Android UI

Size Units in Android

sp (scale-independent px)Use for text size. Scaled by the user's font size preference.
dp (density-independent px)Use for everything else (width, height, margin, padding). Consistent across screen densities.
px (pixels)Actual screen pixels. Not recommended — results in different sizes on different devices.

DP Formula

Density-Independent Pixel Calculation dp = (width in pixels × 160) ÷ screen density (dpi)

Screen Density Buckets

QualifierDescriptionDPI EstimateScale Factor
ldpiLow density (mostly unused)~120 dpi0.75×
mdpiMedium density (baseline)~160 dpi
hdpiHigh density~240 dpi1.5×
xhdpiExtra-high density~320 dpi
xxhdpiExtra-extra-high density~480 dpi
xxxhdpiExtra-extra-extra-high density~640 dpi

View Rendering Cycle

1. Measure

Determine the size of each view based on constraints and content.

2. Layout

Position each view within its parent container.

3. Draw

Render the views onto the screen.

View Spacing

Margin

Space outside the view's border — pushes the view away from other elements.

android:layout_margin="16dp"
android:layout_marginTop="8dp"
Padding

Space inside the view's border — pushes content away from the edge.

android:padding="16dp"
android:paddingStart="8dp"

ConstraintLayout

Recommended default layout for Android. Solves the costly issue of too many nested layouts while allowing complex behavior. Positions and sizes views using constraints.

Why avoid deep nesting?

Deeply nested ViewGroups require more computation. Views may be measured multiple times. This causes UI slowdown and lack of responsiveness. ConstraintLayout solves this with a flat hierarchy.

Constraint Format

Constraint Attribute Format app:layout_constraint<Source>_to<Target>Of="parent | @id/view"

Example Constraints

<TextView
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />  ← centers the view

Constraint Widget Sizes

FixedExplicit size value in dp.
Wrap contentSize is just large enough to fit content.
Match constraints (0dp)Expands to fill available space between constraints. Use instead of match_parent in ConstraintLayout children.

Chains in ConstraintLayout

Chains let you position views in relation to each other (horizontally or vertically). Provide much of LinearLayout functionality.

Chain StyleDescription
Spread ChainViews spread evenly across available space (default).
Spread InsideFirst and last views at edges; space distributed between remaining views.
Weighted ChainViews take up space proportional to their weights.
Packed ChainViews packed together at center of available space.

Guidelines

Invisible layout helpers that let you position multiple views relative to a single guide. Can be vertical or horizontal. Not drawn on device.

<Guideline
    android:orientation="vertical"
    app:layout_constraintGuide_begin="16dp" />

<!-- Specify one of these: -->
layout_constraintGuide_begin   ← from start
layout_constraintGuide_end     ← from end
layout_constraintGuide_percent ← percentage of parent (0.0–1.0)

Groups

Control the visibility of a set of widgets as a group.

// Toggle group visibility
if (group.visibility == View.GONE) {
    group.visibility = View.VISIBLE
} else {
    group.visibility = View.GONE
}
// Visibility constants:
// VISIBLE   → shown
// INVISIBLE → not shown but TAKES space
// GONE      → not shown and does NOT take space

Data Binding

Bind UI components in layouts directly to data sources — replaces repetitive findViewById() calls.

Setup

// 1. Enable in build.gradle
android {
    buildFeatures { dataBinding = true }
}

// 2. Wrap layout in <layout> tag
<layout>
    <data>
        <variable name="name" type="String"/>
    </data>
    <ConstraintLayout>
        <TextView android:text="@{name}" />
    </ConstraintLayout>
</layout>

// 3. Use binding in Activity
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.name = "John"
ViewBinding vs Data Binding

ViewBinding: Ties View to a Binding Class, providing static access to views — but does NOT tie variables/data to views. Data Binding: Does both. For reactive two-way binding, use Data Binding with LiveData or Observable objects. With Jetpack Compose, binding is not needed as it provides its own reactive framework.

RecyclerView

Widget for displaying lists of data. "Recycles" (reuses) item views when they scroll off-screen to make scrolling more performant.

RecyclerView Key Parts

RecyclerView.AdapterSupplies data and layouts. Must override getItemCount, onCreateViewHolder, onBindViewHolder.
ViewHolderHolds references to the views for one item. Reused as items scroll in/out.
LayoutManagerControls how items are arranged. LinearLayoutManager (list), GridLayoutManager (grid).
class MyAdapter(val data: List<Int>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    class MyViewHolder(val row: View) : RecyclerView.ViewHolder(row) {
        val textView = row.findViewById<TextView>(R.id.number)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val layout = LayoutInflater.from(parent.context).inflate(R.layout.item_view, parent, false)
        return MyViewHolder(layout)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.textView.text = data.get(position).toString()
    }

    override fun getItemCount(): Int = data.size
}
06

MD vs HIG

UI/UX Design

Overview

Material Design (MD)

Google's design standard for Android. Based on the "material metaphor" concept — digital surfaces with real-world physics, shadows, and movement.

Human Interface Guidelines (HIG)

Apple's design standard for iOS. Focuses on simplicity, clarity, and deference to user content. Transparency and layering for depth.

Core Design Principles

AspectMaterial DesignHuman Interface Guidelines
Philosophy Material metaphor — digital surfaces with real-world properties (shadows, depth) Simplicity, clarity, and deference to user content
Core Principle 1 Material as Metaphor: realistic shadows and movement Clarity: legible and visually distinct interface
Core Principle 2 Bold Graphics & Intentional Colors: vibrant palettes, strong contrast Deference: UI elements support content, don't overshadow it
Core Principle 3 Meaningful Motion: animation provides visual cues for understanding Depth through Transparency: blur and layering for hierarchy
Core Principle 4 Adaptive Design: optimized for different screen sizes and orientations Intuitive Navigation: familiar interactions, smooth transitions

Navigation Patterns

Material Design Navigation
  • Navigation Drawer — side menu for quick access to app sections
  • Top Tabs — tabs at top of screen
  • Back Button — physical or on-screen button for backward navigation
HIG Navigation
  • Bottom Navigation Bar — quick access to primary sections
  • Hierarchical Navigation — back button in top-left corner
  • Swipe Gestures — swipe left/right for navigation

Visual Elements: Icons, Colors, Animations

ElementMaterial DesignHIG (iOS)
IconsColorful, bright, detailed, expressiveFlat & monochromatic, minimalistic, simple
DepthShadows & elevation create hierarchyTransparency & blur (no heavy shadows)
AnimationExplicit, smooth, meaningful movementNatural, seamless, fluid transitions

Layout Approach

Material Design
  • Grid-Based Layout: responsive grid system with columns, gutters, margins
  • Responsive Design: adapts to various screen sizes and orientations
HIG
  • Alignment and Spacing: precise alignment enhances readability
  • Consistency: elements with similar functions have uniform appearance

UI Components Comparison

Component TypeMaterial DesignHIG (iOS)
ButtonsText, Elevated, Filled, Outlined (varying emphasis)System, Detail Disclosure, Info buttons
List/CardCards — encapsulate related info (image, text, actions)Collection Views — similar function, different pattern
Text InputText Fields — labels, helper text, floating hintsText Fields — built-in auto-correction, search capabilities
NavigationNavigation Drawer — hidden side menuTab Bar — persistent bottom navigation

Apple Liquid Glass (2025 — new in HIG)

Glass-like Translucency

Semi-transparent surfaces that reveal layers beneath.

Fluidity

Smooth, liquid-like animations and transitions.

Light Bending

Material that appears to refract and bend light realistically.

Impact on UX

Android (MD)

More flexibility and customization. Android offers diverse UX possibilities but at the cost of potential inconsistency across apps.

iOS (HIG)

More consistent and structured experience. Uniform patterns across all iOS apps create predictable UX.

Best Practice for Developers

Follow official guidelines for each platform. Cross-platform apps must consider both UI/UX paradigms. Don't just port an Android design to iOS or vice versa — adapt to each platform's conventions.

07

Non-Nullability (Kotlin Null Safety)

Kotlin

The Problem: The Billion-Dollar Mistake

Tony Hoare's "Billion-Dollar Mistake" (1965)

Tony Hoare invented the null reference in 1965 for ALGOL W. He later called it his "billion-dollar mistake" — it has led to innumerable errors, vulnerabilities, and system crashes. In Java: NullPointerException (NPE).

Kotlin's Solution: Non-Nullable by Default

In Kotlin, all reference variables are non-nullable by default. If you want a nullable reference, you must explicitly declare it with the ? suffix (nullability marker).

// Non-nullable (default) — cannot be null
var name: String = "Alice"
    name = null  // COMPILE ERROR

// Nullable — must use ? suffix
var name: String? = "Alice"
    name = null  // OK

Null Safety Operators

Safe Call Operator
A?.B
Returns A.B if A is not null. Returns null if A is null — never throws NPE. Great for chaining: if any part is null, entire chain returns null.
val len = name?.length  // Int? (nullable)
// Chaining:
user?.address?.city?.name
Elvis Operator
A ?: B
If A is not null, return A. If A is null, return B (default value). "Converts" nullable to non-nullable. The return value is typically non-nullable.
val name = nullableName ?: ""
// Equivalent to:
val l: Int = if (b != null) b.length else 0
// Elvis version:
val l: Int = b?.length ?: 0
Not-Null Assertion Operator
A!!
Forces a nullable value to non-nullable. If the value IS null, throws NPE at runtime. Use only when you are 100% certain the value is not null and the compiler cannot infer this.
val b = a!!  // Throws NPE if a is null
// Use sparingly — defeats null safety purpose
lateinit vars
lateinit var x: Type
Marks a non-nullable property that will be initialized later (e.g., in dependency injection or Activity.onCreate). Still null at construction, but guaranteed non-null eventually. Throws UninitializedPropertyAccessException if accessed before init.
lateinit var result: TextView

override fun onCreate(...) {
    result = findViewById(R.id.result)
}

Summary: Null Handling Decision Tree

Quick Reference Non-nullable default → A? to allow null → A?. for safe access → ?: for default → !! when certain (dangerous)

Language Null Safety Comparison

LanguageNull ConceptDefault Non-null?Compile-time?"Trust Me" Escape
Kotlinnull / T?YesYes!! — throws NPE if null
RustNone / Option<T>YesYes.unwrap() — panics if None
Dartnull / T?Yes (since 2.12)Yes! suffix — throws if null
TypeScriptnull / T | nullOpt-inYes (with strictNullChecks)Type assertions as T
Java@Nullable / @NonNullNoTools onlyAny reference is nullable by default
PythonNone / Optional[T]NoTools onlyType hints ignored at runtime
JavaScriptnull + undefinedNoNoEverything nullable, no enforcement
C++nullptrNoNoRaw nullptr dereference = undefined behavior (silent crash)
Key Insight: Why Kotlin's Approach is Better

By making non-null the default, the compiler warns you at the point of assignment (not at runtime crash). If you need null, you explicitly opt-in with ?, which forces you to handle the null case. This moves NPE bugs from runtime crashes to compile-time errors.