Kotlin Basics
Syntax, variables, data types, operators, type conversion, and console input/output
Table of Contents
1Kotlin Syntax
Kotlin syntax is concise and expressive. Semicolons are optional, blocks use curly braces { }, and the entry point for console apps is the top-level function fun main().
Basic program structure
Syntax rules at a glance
| Rule | Kotlin | Notes |
|---|---|---|
| Semicolons | Optional | One statement per line is standard |
| Blocks | { } | Functions, if, loops, classes |
| Entry point | fun main() | No public static void main required |
| Top-level code | Allowed | Functions and properties outside classes |
| String templates | "Hello, $name" | Use ${expression} for expressions |
| Case sensitivity | Yes | name and Name are different |
String templates
2Variables
Variables store values that can change during program execution. Kotlin provides two keywords: var (mutable) and val (read-only reference).
| Keyword | Mutable? | When to use |
|---|---|---|
val | No (reference cannot be reassigned) | Default choice — prefer immutability |
var | Yes | When value must change (counters, UI state) |
Type inference
Kotlin infers types from initial values. You can declare a type explicitly when needed for clarity or when no initializer is present:
Use val by default. Switch to var only when reassignment is required — this reduces bugs and makes code easier to reason about.
3Constants
Constants are fixed values known at compile time. In Kotlin, use const val for compile-time constants, typically at the top level or inside an object or companion object.
const val vs val
| Feature | const val | val |
|---|---|---|
| Compile-time constant | Yes — inlined at compile time | Runtime value allowed |
| Allowed types | String, Int, Long, Float, Double, Boolean | Any type |
| Location | Top level, object, companion object | Anywhere |
| Example | const val TIMEOUT = 5000 | val user = getUser() |
UPPER_SNAKE_CASE by convention (e.g. MAX_SIZE, DEFAULT_TIMEOUT).
4Data Types
Kotlin is statically typed — every variable has a type known at compile time. Types are divided into numeric, character, boolean, string, and array categories.
Numeric types
| Type | Size | Example |
|---|---|---|
Byte | 8 bit | 127 |
Short | 16 bit | 32000 |
Int | 32 bit | 42 (default for integers) |
Long | 64 bit | 1_000_000L |
Float | 32 bit | 3.14f |
Double | 64 bit | 3.14159 (default for decimals) |
Other common types
| Type | Description | Example |
|---|---|---|
Boolean | true or false | val active = true |
Char | Single Unicode character | 'A', '\u0041' |
String | Text sequence | "Hello", triple-quoted """...""" |
Array | Fixed-size collection | arrayOf(1, 2, 3) |
Use underscores for readability: 1_000_000, 0xFF_EC_DE_5E, 3.14_15_92.
5Operators
Kotlin supports arithmetic, comparison, logical, assignment, and range operators similar to Java, with some Kotlin-specific additions.
Arithmetic operators
Comparison and logical operators
| Category | Operators | Example |
|---|---|---|
| Comparison | == != > < >= <= | x > 5 |
| Logical | && || ! | a && b |
| Identity | === !== | Same object reference (rare) |
Assignment and increment
Range operator
6Type Conversion
Unlike Java, Kotlin does not allow implicit widening conversions between numeric types. You must convert explicitly using conversion functions or toString() for strings.
| From | Conversion functions |
|---|---|
Int | .toByte() .toShort() .toLong() .toFloat() .toDouble() .toChar() |
Double | .toInt() .toLong() .toFloat() (truncates toward zero) |
String | .toInt() .toDouble() .toLong() .toBoolean() |
| Any type | .toString() |
Safe conversion with toIntOrNull()
as for unsafe cast and as? for safe cast on reference types. Smart casts work after type checks — covered in Control Statements.
7Input/Output
Kotlin provides simple functions for console I/O in JVM programs. Android apps use different UI mechanisms, but console I/O is ideal for learning and CLI tools.
Output — println and print
| Function | Behavior |
|---|---|
print() | Prints without newline |
println() | Prints with newline (most common) |
printf() | Formatted output (Java-style, via JVM) |
Input — readln and readLine
readLine() — older style
Console input works when running main() from IntelliJ's Run window or from the terminal. It does not work in Kotlin Playground for interactive input — use hardcoded values there instead.
8Summary Cheatsheet
| Topic | Key Takeaway |
|---|---|
| Syntax | fun main(), optional semicolons, string templates $var |
| Variables | val (read-only) preferred; var when mutable |
| Constants | const val for compile-time constants; UPPER_SNAKE_CASE |
| Data Types | Int, Long, Float, Double, Boolean, Char, String, Array |
| Operators | Arithmetic, comparison, logical, compound assignment, ranges |
| Type Conversion | Explicit: .toInt(), .toDouble(), toIntOrNull() |
| I/O | println() out; readln() / readLine() in |
| Next lesson | Control Statements — if, when, loops |
Kotlin Basics MCQ Practice
10 Basic MCQs 10 Advanced MCQs10 Basic Kotlin Basics MCQs
Which keyword declares a read-only variable in Kotlin?
val declares a read-only reference — the variable cannot be reassigned after initialization.What is the standard entry point for a Kotlin console application?
fun main() function — no class wrapper or static keyword required.Which declaration creates a compile-time constant in Kotlin?
const val must be a compile-time constant of allowed primitive types, inlined at compile time.Kotlin does not allow implicit conversion between numeric types. To convert Int to Long you must?
intVal.toLong() — no implicit numeric widening.How do you embed a simple variable in a Kotlin string?
$variable for simple references and ${expression} for expressions.What type is inferred for val x = 3.14 without a suffix?
f suffix default to Double; use 3.14f for Float.Which function reads a line of console input in modern Kotlin (1.6+)?
readln() reads the full line as a non-null String; readlnOrNull() handles EOF.What is the safe way to parse a String to Int without throwing an exception?
toIntOrNull() returns null on invalid input instead of throwing NumberFormatException.What values does the range 1..5 include?
.. operator creates a closed range — both endpoints are included.Semicolons at the end of statements in Kotlin are?
10 Advanced Kotlin Basics MCQs
After if (x is String), Kotlin automatically treats x as String inside the block. This is called?
is checks when the compiler can prove the type is stable in that scope.Which integers are in 1 until 5?
until creates a half-open range — it includes the start but excludes the end value.What is the recommended default when declaring a local variable?
val for immutability — use var only when the reference must be reassigned.How do you write a Long integer literal in Kotlin?
L to mark a literal as Long; underscores improve readability: 1_000_000L.To convert an Int to Double in Kotlin you should?
intVal.toDouble() — Kotlin does not widen automatically.Which operator checks referential equality (same object instance)?
=== compares references; == calls structural equality via equals().What does readLine() return?
readLine() returns String? — use ?: "default" or readln() when you need non-null input.What naming convention is used for Kotlin constants?
const val MAX_SIZE = 100 follows UPPER_SNAKE_CASE, matching Java constant style.Which range operator produces 5, 4, 3, 2, 1?
downTo creates a descending progression; .. always counts upward.How do you declare a Float literal such as 3.14?
f suffix, decimal literals infer as Double; append f for Float.Kotlin Basics Interview Q&A
15 topic-focused questions for interviews and revision.
var and val in Kotlin?easyvar declares a mutable variable whose reference can be reassigned. val declares a read-only reference — once assigned, it cannot point to a different value. Prefer val by default for safer, clearer code.fun main() and why does Kotlin not need a class for the entry point?easyfun main() is the top-level entry function for console and JVM apps. Kotlin allows top-level functions and properties outside classes, so you do not need a public static void main(String[] args) wrapper like in Java.const val versus regular val.mediumconst val must be a compile-time constant of primitive or String type, declared at top level or in object/companion object, and is inlined at compile time. Regular val can hold runtime-computed values and any type.Int to Long) to prevent subtle bugs. Use explicit methods like .toLong(), .toDouble(), and .toInt() so conversions are always visible in code.$variableName to embed a variable and ${expression} for arbitrary expressions inside strings. Example: "Score: ${a + b}" evaluates the sum before interpolation.val x = 10 is Int, val y = 3.14 is Double. You can specify types explicitly when there is no initializer or for clarity.println(), print(), and readln().easyprint() writes without a newline; println() writes and appends a newline. readln() reads a full line from standard input as a non-null String — ideal for simple console programs in IntelliJ or terminal.toIntOrNull() and when should you use it?mediumtoIntOrNull() parses a string to Int?, returning null instead of throwing when input is invalid. Use it for user input, API data, or any untrusted string before doing arithmetic..., until, and downTo.medium1..5 is inclusive on both ends (1 through 5). 1 until 5 includes 1 but excludes 5 (1–4). 5 downTo 1 counts downward from 5 to 1 inclusive.== and === in Kotlin?medium== checks structural equality (calls equals(), with null-safe handling). === checks referential equality — whether two variables reference the exact same object instance.readLine() instead of readln()?easyreadLine() returns String? and is the older JVM-style API — handle null with ?:. readln() (Kotlin 1.6+) returns non-null String and throws on EOF; readlnOrNull() handles EOF safely.Byte, Short, Int, Long, Float, Double, plus unsigned variants. Integer literals default to Int; decimals without suffix default to Double. Use L for Long and f for Float.if (x is String), the compiler automatically casts x to String in that branch without an explicit as cast, as long as the variable cannot be mutated concurrently in that scope.print("Enter name: "), val name = readln(), print("Enter age: "), val age = readln().toIntOrNull() ?: 0, then println("Hello, $name! You are $age years old."). This combines I/O, safe parsing, and string templates.