SyntaxStudy
Sign Up
Kotlin Kotlin vs Java: Key Differences
Kotlin Beginner 1 min read

Kotlin vs Java: Key Differences

Kotlin dramatically reduces boilerplate compared to Java. A simple data-holding class that requires dozens of lines in Java can be expressed in a single line using Kotlin's data class feature. This makes code easier to read, maintain, and reason about. Kotlin's type system distinguishes between nullable and non-nullable types, eliminating entire categories of NullPointerExceptions at compile time. Every type is non-nullable by default; you must explicitly opt in to nullability by appending a question mark to the type name. Kotlin also introduces coroutines for asynchronous programming, extension functions for adding behaviour to existing classes without inheritance, and smart casts that automatically narrow types after an instanceof check — all features absent from standard Java.
Example
// Java-style verbose class (for comparison)
// public class Person {
//     private String name; private int age;
//     public Person(String name, int age) { ... }
//     public String getName() { ... }
//     // + equals, hashCode, toString ...
// }

// Kotlin equivalent — one line
data class Person(val name: String, val age: Int)

fun main() {
    val alice = Person("Alice", 30)
    val bob   = alice.copy(name = "Bob", age = 25)

    println(alice)          // Person(name=Alice, age=30)
    println(bob)            // Person(name=Bob, age=25)
    println(alice == bob)   // false — structural equality

    // Smart cast
    val obj: Any = "Hello"
    if (obj is String) {
        // obj is automatically cast to String here
        println(obj.uppercase())
    }

    // When expression (enhanced switch)
    val score = 85
    val grade = when {
        score >= 90 -> "A"
        score >= 80 -> "B"
        score >= 70 -> "C"
        else        -> "F"
    }
    println("Grade: $grade")
}