Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 134 ยท Practice

Kotlin for Java Developers

A side-by-side guide for Java developers learning Kotlin: classes, null safety, equality, collections, lambdas, static members, exceptions, interop and a practical migration plan.

If you know Java, you already know most of what Kotlin runs on. Both compile to JVM bytecode, both use the same libraries, garbage collector and tools, and a Kotlin class can extend a Java class or be called from Java. The difference is the language on top: Kotlin removes ceremony (getters, setters, constructors, equals), moves a whole class of errors from run time to compile time (null), and treats functions and expressions as first-class.

This lesson is a translation guide. Each section shows the Java idiom you know, then the Kotlin equivalent, then the pitfalls that catch Java programmers. Java snippets are read-only; all Kotlin runs. The last section gives a migration plan for real projects.

Classes, properties and data

A typical Java value class needs fields, a constructor, getters, equals, hashCode and toString. Java 16 added records to cut this down. In Kotlin you write a data class, and plain properties replace getter/setter pairs.

Java
// read-only example: Java
public final class User {
    private final String name;
    private int age;
    public User(String name, int age) { this.name = name; this.age = age; }
    public String getName() { return name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    // equals, hashCode, toString omitted...
}
Kotlin Properties and data classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Differences to remember:

  • val name: String declares a field, a getter and a constructor parameter in one line. Access is u.name, never u.getName() in Kotlin code (Java code still calls the generated getName()).
  • Classes and methods are final by default. You write open to allow inheritance, the reverse of Java. See Inheritance.
  • There is no new: User("Ada", 36).
  • There are no package-private defaults: the default visibility is public. See Visibility Modifiers.
  • Records and data classes are close cousins, but data classes can have var properties, copy and destructuring. See Data Classes.

Null safety instead of NullPointerException

Java's type String means "a string or null". Kotlin splits it in two: String can never be null, String? can. The compiler tracks the difference, replacing Optional, defensive checks and @Nullable annotations with the language itself.

Java
// read-only example: Java
String city = user.getAddress() != null ? user.getAddress().getCity() : "unknown";
Kotlin Null safety in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

?. replaces chains of null checks, ?: supplies a default, and after if (text != null) the compiler smart-casts text to String. Learn these three tools and you will rarely write !!, which throws like a Java NPE. Values coming from Java have platform types: Kotlin trusts you to know whether they can be null. Declare nullable types for Java results that might be null. See Null Safety and Common Kotlin Mistakes.

Equality, strings and numbers

This is the translation that bites hardest. In Java, == on objects compares references and you call .equals(). In Kotlin, == calls equals (null-safely) and === is reference identity.

Java Kotlin
a.equals(b) a == b
a == b (references) a === b
int, Integer Int (the compiler picks primitive or box)
long x = i; (implicit widening) val x: Long = i.toLong() (explicit)
String.format("%d", n) "$n" or "%d".format(n)
switch statement when expression
ternary a ? b : c if (a) b else c
StringBuilder loops buildString { }
Kotlin Equality, conversions, when and templates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Collections, lambdas and streams

Java collections are the same classes under the hood: Kotlin's MutableList is java.util.List. But Kotlin adds a read-only interface hierarchy and many functions directly on the collections, so the stream().collect(...) ceremony disappears.

Java
// read-only example: Java
List<String> names = people.stream()
    .filter(p -> p.getAge() >= 18)
    .map(Person::getName)
    .sorted()
    .collect(Collectors.toList());
Kotlin From streams to collection functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Differences: no new ArrayList<>() needed (mutableListOf), lambdas use { x -> ... } and it, and a Java interface with one method (Runnable, Comparator) accepts a lambda directly. Functions on collections are eager (each step builds a list); for long pipelines add .asSequence() to get stream-like laziness. See Collection Transformations and Sequences.

Static members, singletons, utilities and extensions

Kotlin has no static keyword. Its replacements are cleaner:

Java Kotlin
static utility class (Strings.isBlank) top-level functions, or extension functions
static method on a class companion object { fun ... }
Singleton with getInstance() object Name { }
Builder / telescoping constructors default and named arguments
Anonymous inner class object : Interface { } or lambda
Overloaded methods for defaults one function with defaults
Kotlin Companions, objects, extensions and defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Exceptions and resources

Kotlin has no checked exceptions: you are never forced to catch or declare anything, and try is an expression. For resources, use replaces try-with-resources, and require/check replace hand-written argument checks. When Java callers need the throws clause, add @Throws. See Exceptions and Using Closeable Resources.

Java
// read-only example: Java
try (BufferedReader r = new BufferedReader(new StringReader(text))) {
    return r.readLine();
} catch (IOException e) {
    return null;
}
Kotlin
// read-only example: Kotlin
fun firstLine(text: String): String? =
    runCatching { text.reader().buffered().use { it.readLine() } }.getOrNull()

Interop and migrating a Java project

Kotlin and Java can live in one module: Kotlin calls Java directly, and Java calls Kotlin through the generated bytecode. A few annotations make Kotlin friendlier to Java callers: @JvmStatic (a real static method), @JvmOverloads (overloads for defaults), @JvmField (a plain field) and @Throws. Top-level functions in Util.kt appear to Java as static methods of UtilKt. See Java Interoperability.

A sensible migration plan:

  1. Add the Kotlin plugin to your build and write new code in Kotlin first; nothing else has to change.
  2. Convert tests next. Low risk, and tests show you the idioms.
  3. Convert data holders and utilities (data classes, extension functions), then services, one file at a time with your IDE's converter. Clean the output by hand: converter code is often Java in Kotlin clothing.
  4. Replace nullable platform types at the boundary with explicit ? types, and use val wherever the converter wrote var.
  5. Introduce Kotlin-only features (sealed types, coroutines) when they bring value, not all at once.

A converted file that compiles is not yet idiomatic. After conversion look for getter calls, !!, for (i in 0 until list.size) loops, StringBuilder code and if (x == null) ... else ... blocks; each has a shorter Kotlin form. See Kotlin Idioms.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does == do on two objects in Kotlin?

    == is structural equality and is translated to equals. Use === for reference identity.
  2. 2. Which is true about classes in Kotlin compared to Java?

    Kotlin classes and members are final unless you mark them open (or abstract), which is the opposite of Java's default.
  3. 3. What replaces Java's static utility methods and static members?

    Kotlin has no static. Top-level functions and extensions replace utility classes, companion object replaces static members, and object declares a singleton.
  4. 4. Which Kotlin type is the equivalent of an Integer that may be null?

    Int? is a nullable Int, boxed as java.lang.Integer when needed. Plain Int can never be null and is a primitive int wherever possible.

Summary

  • Kotlin and Java share the JVM, libraries and tools; you can mix them file by file.
  • Properties, data classes and default arguments replace getters, setters, equals/hashCode boilerplate and overloads.
  • Types are non-null by default; use ?., ?: and smart casts, and type Java results explicitly.
  • == is equals, === is identity; numbers are never widened implicitly.
  • Collection functions and lambdas replace most streams; use sequences for lazy pipelines.
  • No static, no checked exceptions; use top-level functions, companions, object, use and require.
  • Migrate gradually: new code, tests, data classes, then services, and clean up converted code.

Next: Kotlin Interview Questions