Kotlin Basics

Syntax, variables, data types, operators, type conversion, and console input/output

Syntax var / val Operators I/O

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

Main.kt// Single-line comment /* Multi-line comment */ fun main() { println("Hello, Kotlin!") }

Syntax rules at a glance

RuleKotlinNotes
SemicolonsOptionalOne statement per line is standard
Blocks{ }Functions, if, loops, classes
Entry pointfun main()No public static void main required
Top-level codeAllowedFunctions and properties outside classes
String templates"Hello, $name"Use ${expression} for expressions
Case sensitivityYesname and Name are different

String templates

String interpolationfun main() { val language = "Kotlin" val version = 2.0 println("Learning $language version $version") println("Next year: ${version + 1}") }

2Variables

Variables store values that can change during program execution. Kotlin provides two keywords: var (mutable) and val (read-only reference).

KeywordMutable?When to use
valNo (reference cannot be reassigned)Default choice — prefer immutability
varYesWhen value must change (counters, UI state)
var vs valfun main() { var score = 10 // mutable — type inferred as Int score = 20 // OK val userName = "Nikhil" // read-only reference // userName = "Alex" // Error: Val cannot be reassigned var count: Int = 0 // explicit type val pi: Double = 3.14 }

Type inference

Kotlin infers types from initial values. You can declare a type explicitly when needed for clarity or when no initializer is present:

Type inferenceval message = "Hello" // String inferred val total = 100 // Int inferred val price = 19.99 // Double inferred lateinit var title: String // for non-null var initialized later (not for primitives) // title = "Kotlin Basics"
Best practice

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 — top levelconst val APP_NAME = "LearnHub" const val MAX_RETRY = 3 const val PI = 3.14159 fun main() { println("$APP_NAME allows $MAX_RETRY retries") }

const val vs val

Featureconst valval
Compile-time constantYes — inlined at compile timeRuntime value allowed
Allowed typesString, Int, Long, Float, Double, BooleanAny type
LocationTop level, object, companion objectAnywhere
Exampleconst val TIMEOUT = 5000val user = getUser()
Constants in companion objectclass Config { companion object { const val API_BASE_URL = "https://api.example.com" const val VERSION_CODE = 1 } } fun main() { println(Config.API_BASE_URL) }
Naming: Constants use 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

TypeSizeExample
Byte8 bit127
Short16 bit32000
Int32 bit42 (default for integers)
Long64 bit1_000_000L
Float32 bit3.14f
Double64 bit3.14159 (default for decimals)

Other common types

TypeDescriptionExample
Booleantrue or falseval active = true
CharSingle Unicode character'A', '\u0041'
StringText sequence"Hello", triple-quoted """..."""
ArrayFixed-size collectionarrayOf(1, 2, 3)
Data type examplesfun main() { val age: Int = 25 val salary: Long = 50_000L val rating: Float = 4.5f val temperature: Double = 36.6 val isStudent: Boolean = true val grade: Char = 'A' val name: String = "Kotlin" val numbers: Array<Int> = arrayOf(10, 20, 30) println("${name}: age=$age, grade=$grade, avg=$rating") }
Underscores in numbers

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

Arithmeticfun main() { val a = 10 val b = 3 println(a + b) // 13 addition println(a - b) // 7 subtraction println(a * b) // 30 multiplication println(a / b) // 3 integer division println(a % b) // 1 remainder (modulo) println(10.0 / 3) // 3.333... floating division }

Comparison and logical operators

CategoryOperatorsExample
Comparison== != > < >= <=x > 5
Logical&& || !a && b
Identity=== !==Same object reference (rare)

Assignment and increment

Assignment & compound operatorsfun main() { var x = 5 x += 3 // x = 8 x *= 2 // x = 16 x++ // x = 17 (post-increment) ++x // x = 18 (pre-increment) println(x) }

Range operator

Rangesfun main() { val range = 1..5 // 1, 2, 3, 4, 5 val until = 1 until 5 // 1, 2, 3, 4 val down = 5 downTo 1 // 5, 4, 3, 2, 1 println(3 in range) // true println(3 !in until) // true }

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.

FromConversion functions
Int.toByte() .toShort() .toLong() .toFloat() .toDouble() .toChar()
Double.toInt() .toLong() .toFloat() (truncates toward zero)
String.toInt() .toDouble() .toLong() .toBoolean()
Any type.toString()
Explicit conversionfun main() { val intVal = 100 val longVal: Long = intVal.toLong() val doubleVal: Double = intVal.toDouble() val str = "42" val parsed = str.toInt() // 42 val decimal = "3.14".toDouble() val num = 99 val text = num.toString() // "99" println("$longVal, $doubleVal, $parsed, $text") }

Safe conversion with toIntOrNull()

Safe parsingfun main() { val input = "abc" val number = input.toIntOrNull() // null — avoids crash val result = number ?: 0 println("Parsed: $result") }
Casting objects: Use 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

FunctionBehavior
print()Prints without newline
println()Prints with newline (most common)
printf()Formatted output (Java-style, via JVM)
Output examplesfun main() { print("Hello ") print("World") // Hello World (same line) println() // newline println("Line 1") println("Line 2") val name = "Nikhil" val score = 95 printf("Student: %s, Score: %d%n", name, score) }

Input — readln and readLine

Reading user inputfun main() { print("Enter your name: ") val name = readln() // reads full line (Kotlin 1.6+) print("Enter your age: ") val ageStr = readlnOrNull() // nullable if EOF val age = ageStr?.toIntOrNull() ?: 0 println("Hello, $name! You are $age years old.") }
Interactive calculatorfun main() { print("Enter first number: ") val a = readln().toDouble() print("Enter second number: ") val b = readln().toDouble() println("Sum: ${a + b}") println("Product: ${a * b}") }

readLine() — older style

readLine()fun main() { print("City: ") val city = readLine() ?: "Unknown" println("You live in $city") }
Run in IntelliJ or terminal

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

TopicKey Takeaway
Syntaxfun main(), optional semicolons, string templates $var
Variablesval (read-only) preferred; var when mutable
Constantsconst val for compile-time constants; UPPER_SNAKE_CASE
Data TypesInt, Long, Float, Double, Boolean, Char, String, Array
OperatorsArithmetic, comparison, logical, compound assignment, ranges
Type ConversionExplicit: .toInt(), .toDouble(), toIntOrNull()
I/Oprintln() out; readln() / readLine() in
Next lessonControl Statements — if, when, loops

Kotlin Basics MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Kotlin Basics MCQs

1

Which keyword declares a read-only variable in Kotlin?

Avar
Bval
Cconst var
Dlet
Explanation: val declares a read-only reference — the variable cannot be reassigned after initialization.
2

What is the standard entry point for a Kotlin console application?

Afun main()
Bpublic static void main()
Cfun start()
Dvoid main()
Explanation: Kotlin uses a top-level fun main() function — no class wrapper or static keyword required.
3

Which declaration creates a compile-time constant in Kotlin?

Aval only
Bconst val
Cvar const
Dfinal val
Explanation: const val must be a compile-time constant of allowed primitive types, inlined at compile time.
4

Kotlin does not allow implicit conversion between numeric types. To convert Int to Long you must?

ARely on automatic widening
BUse (Long) cast syntax only
CCall explicit functions like .toLong()
DUse parseLong()
Explanation: Unlike Java, Kotlin requires explicit conversion — e.g. intVal.toLong() — no implicit numeric widening.
5

How do you embed a simple variable in a Kotlin string?

A"Hello, $name"
B"Hello, %name"
C"Hello, #name"
Dconcat(name) only
Explanation: String templates use $variable for simple references and ${expression} for expressions.
6

What type is inferred for val x = 3.14 without a suffix?

AFloat
BDouble
CBigDecimal
DNumber
Explanation: Decimal literals without f suffix default to Double; use 3.14f for Float.
7

Which function reads a line of console input in modern Kotlin (1.6+)?

Areadln()
Bscanf()
Cinput()
DgetLine()
Explanation: readln() reads the full line as a non-null String; readlnOrNull() handles EOF.
8

What is the safe way to parse a String to Int without throwing an exception?

AtoInt()
BtoIntOrNull()
CparseInt()
DInt.parse()
Explanation: toIntOrNull() returns null on invalid input instead of throwing NumberFormatException.
9

What values does the range 1..5 include?

A1, 2, 3, 4, 5 (inclusive)
B1, 2, 3, 4 only
C2, 3, 4, 5 only
D5, 4, 3, 2, 1
Explanation: The .. operator creates a closed range — both endpoints are included.
10

Semicolons at the end of statements in Kotlin are?

ARequired on every line
BForbidden
COptional
DRequired only in classes
Explanation: Kotlin syntax allows omitting semicolons — one statement per line is the standard style.

10 Advanced Kotlin Basics MCQs

11

After if (x is String), Kotlin automatically treats x as String inside the block. This is called?

ASmart cast
BUnsafe cast
CDynamic cast
DReflection
Explanation: Smart casts apply after is checks when the compiler can prove the type is stable in that scope.
12

Which integers are in 1 until 5?

A1, 2, 3, 4, 5
B1, 2, 3, 4
C2, 3, 4, 5
D5, 4, 3, 2, 1
Explanation: until creates a half-open range — it includes the start but excludes the end value.
13

What is the recommended default when declaring a local variable?

AUse val unless reassignment is needed
BAlways use var
CAlways use const val
DNo preference
Explanation: Prefer val for immutability — use var only when the reference must be reassigned.
14

How do you write a Long integer literal in Kotlin?

A1000 (always Long)
B1000L or 1_000L
C1000.0
Dlong(1000)
Explanation: Append L to mark a literal as Long; underscores improve readability: 1_000_000L.
15

To convert an Int to Double in Kotlin you should?

ACall .toDouble() explicitly
BRely on implicit widening
CUse (double) cast
DAssign without conversion
Explanation: Numeric conversions are explicit: intVal.toDouble() — Kotlin does not widen automatically.
16

Which operator checks referential equality (same object instance)?

A==
B===
Cequals() only
D=
Explanation: === compares references; == calls structural equality via equals().
17

What does readLine() return?

AString? (nullable)
BNon-null String
CInt?
DCharArray
Explanation: readLine() returns String? — use ?: "default" or readln() when you need non-null input.
18

What naming convention is used for Kotlin constants?

AUPPER_SNAKE_CASE
BcamelCase
CPascalCase
Dkebab-case
Explanation: const val MAX_SIZE = 100 follows UPPER_SNAKE_CASE, matching Java constant style.
19

Which range operator produces 5, 4, 3, 2, 1?

A5..1
B5 until 1
C5 downTo 1
D1..5 reversed only
Explanation: downTo creates a descending progression; .. always counts upward.
20

How do you declare a Float literal such as 3.14?

A3.14 alone
B3.14f or 3.14F
CFloat(3.14) only
D3.14L
Explanation: Without the f suffix, decimal literals infer as Double; append f for Float.
Click an option to select, then check answers.

Kotlin Basics Interview Q&A

15 topic-focused questions for interviews and revision.

1What is the difference between var and val in Kotlin?easy
Answer: var 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.
2What is fun main() and why does Kotlin not need a class for the entry point?easy
Answer: fun 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.
3Explain const val versus regular val.medium
Answer: const 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.
4Why does Kotlin require explicit numeric type conversion?medium
Answer: Kotlin avoids implicit widening (e.g. Int to Long) to prevent subtle bugs. Use explicit methods like .toLong(), .toDouble(), and .toInt() so conversions are always visible in code.
5How do string templates work in Kotlin?easy
Answer: Use $variableName to embed a variable and ${expression} for arbitrary expressions inside strings. Example: "Score: ${a + b}" evaluates the sum before interpolation.
6What is type inference in Kotlin?easy
Answer: The compiler deduces variable types from initializers — e.g. val x = 10 is Int, val y = 3.14 is Double. You can specify types explicitly when there is no initializer or for clarity.
7Compare println(), print(), and readln().easy
Answer: print() 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.
8What is toIntOrNull() and when should you use it?medium
Answer: toIntOrNull() 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.
9Explain the difference between .., until, and downTo.medium
Answer: 1..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.
10What is the difference between == and === in Kotlin?medium
Answer: == checks structural equality (calls equals(), with null-safe handling). === checks referential equality — whether two variables reference the exact same object instance.
11When would you use readLine() instead of readln()?easy
Answer: readLine() 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.
12What numeric types does Kotlin provide and what are their defaults?medium
Answer: Kotlin has 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.
13What is a smart cast in Kotlin?hard
Answer: After a type check like 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.
14Are semicolons required in Kotlin? What other syntax rules stand out?easy
Answer: Semicolons are optional. Kotlin uses curly braces for blocks, supports top-level code, uses string templates, and is case-sensitive. It has no primitive types at the language level — everything is an object on the JVM.
15Write a short program flow: read name and age, then print a greeting.medium
Answer: Use 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.