Chapter 2 of 12 ~12 min read

Basic Syntax

How Kotlin's surface-level syntax differs from Java — and what you gain.


No Semicolons Required

In Kotlin, semicolons are optional. The compiler infers statement boundaries from line endings. You can use them, but the convention is to omit them entirely.

Java
int x = 10;
String name = "Alice";
System.out.println(name);
Kotlin
val x = 10
val name = "Alice"
println(name)

The main() Function

In Java, main() must be a public static method inside a class. In Kotlin, it's a top-level function — no class needed.

Java
public class App {
    public static void main(String[] args) {
        System.out.println("Starting...");
    }
}
Kotlin
fun main() {
    println("Starting...")
}
// Kotlin 2.x: args param is optional
Top-level declarations

Kotlin allows functions, properties, and even classes to be declared at the top level of a file — outside any class. This reduces forced object-orientation for simple utility functions.

Packages & Imports

Package and import syntax is nearly identical to Java — no learning curve here.

Java
package com.example.app;

import java.util.List;
import java.util.ArrayList;
import android.content.Context;
Kotlin
package com.example.app

import java.util.List
import java.util.ArrayList
import android.content.Context

String Templates

Kotlin's string templates are one of the first things Java developers love. No more String.format() gymnastics:

Java
String name = "Alice";
int age = 30;
String msg = "Hello " + name + ", age " + age;
// or with format:
String msg2 = String.format(
    "Hello %s, age %d", name, age);
Kotlin
val name = "Alice"
val age = 30
val msg = "Hello $name, age $age"

// Expressions with ${}:
val info = "Born in ${2026 - age}"
val len = "Name has ${name.length} chars"
Use ${} for expressions

Use $variable for simple names and ${expression} for method calls, math, or multi-field access inside strings.

Comments

Comments work identically to Java — single-line, multi-line, and KDoc (equivalent to Javadoc):

Kotlin
// Single-line comment (same as Java)

/*
 * Multi-line comment (same as Java)
 */

/**
 * KDoc — equivalent to Javadoc.
 * @param name The user's name.
 * @return A greeting message.
 */
fun greet(name: String): String = "Hello, $name!"

Syntax Quick Reference Table

ConceptJavaKotlin
Print to consoleSystem.out.println("x")println("x")
Variable declarationString s = "hi";val s = "hi"
String interpolation"Hi " + name"Hi $name"
Define functionpublic int add(int a, int b) { return a+b; }fun add(a: Int, b: Int): Int = a + b
if / elseif (x > 0) { ... }if (x > 0) { ... } (identical)
for loopfor (int i=0; i<10; i++)for (i in 0..9)
while loopwhile (condition) { ... }Same