Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 02 / Stage 1

Language fundamentals

Goal: Declare values with val and var, work with Kotlin's basic types and type inference, build output with string templates, tell expressions apart from statements, use Kotlin's operators correctly, convert between types on purpose, and read real input from the terminal — then put all of it into a restaurant bill splitter. Time: ~5 hours · Level: finished Part 1

What you will learn

  • val versus var: read-only by default, reassignable only when you say so, and what the compiler actually does when you break that rule
  • Kotlin's basic types — Int, Long, Double, Boolean, Char, String — and type inference
  • String templates: $name and ${expression}, and how they compare to + concatenation
  • Expressions versus statements: why a println(...) call is itself an expression of type Unit
  • Arithmetic, comparison and logical operators, including the integer-division and % gotchas
  • Converting between types on purpose: toInt(), toDouble(), toLong() — nothing converts for you
  • Reading standard input with readln(), and turning text into numbers safely
  • The running build for this part: a restaurant bill splitter with GST and tip

Topics in this part

Practice

Try each one yourself first. Then check the solution.

Every exercise is one file with a top-level fun main() — no if/when, no loops, no functions of your own beyond main, no classes. Those come in later parts.


Exercise 1: Chai stall tab

Scenario: Sharma Chai Corner in Jaipur keeps a running tab for a regular customer who orders a few items, one at a time. What to do: Declare the stall's name as a val. Declare a tab total as a var starting at 0.0, then add two cups of chai at ₹15 each and one samosa at ₹20 to it using +=, one line per item. Print the stall name and the final tab using string templates.

Sample output:

Stall: Sharma Chai Corner, Jaipur
Items so far: 2 chai, 1 samosa
Tab: ₹50.0

💡 Hint: The stall name never changes, so it's a val; the tab grows one item at a time, so it's a var. tab += 15.0 is shorthand for tab = tab + 15.0.


Exercise 2: Fix the broken program

Scenario: A friend sends you this file. It does not compile.

fun main() {
    val itemCount = 3
    itemCount = 5

    val smallTotal = 1200
    val bigTotal: Long = smallTotal

    val city = "Chennai"
    println(city)
    println("Item count: itemCount, big total: bigTotal")
}

What to do: Fix every error so it compiles and prints the city, then the item count and the big total using string templates.

Sample output:

City: Chennai
Item count: 5, big total: 1200

💡 Hint: There are three separate bugs: itemCount is reassigned but declared val, so it needs to be a var; smallTotal is an Int and bigTotal is declared Long, and Kotlin never widens that for you, so it needs .toLong(); and the last println has no $ before either name, so both print as literal text instead of their values.


Exercise 3: Product catalog types

Scenario: A small shop's inventory system needs one sample product printed with every field's inferred type next to it, to confirm the catalog's data will hold the right kind of value. What to do: Declare five vals for one product — a Char SKU letter, an Int price, a Double weight in kilograms, a Boolean stock flag and a String name — with no explicit type annotations. Print each one with its value and its inferred type name (${value::class.simpleName}).

Sample output:

SKU: B (Char)
Price: ₹499 (Int)
Weight: 0.75 kg (Double)
In stock: true (Boolean)
Name: Steel Water Bottle (String)

💡 Hint: None of the five declarations need a type annotation — kotlinc infers every one of them correctly from the literal alone.


Exercise 4: Kirana store discount

Scenario: A kirana store in Mumbai gives a flat percentage discount on a bill, and the owner wants both the integer-division and decimal-division behaviour shown side by side so the till software is built on the right assumption. What to do: Given a bill of ₹1850 and a 10% discount, compute the discount amount and the payable amount using * and /. Then print 9 / 2 as Int division, 9.0 / 2 as Double division, and 9 % 2 as a remainder, to show all three results together.

Sample output:

Bill: ₹1850
Discount (10%): ₹185
Payable: ₹1665
9 / 2 as Int: 4
9.0 / 2 as Double: 4.5
9 % 2 (remainder): 1

💡 Hint: billAmount * discountPercent / 100 keeps every intermediate value a whole number until the final division, same order the bill splitter in section 8 uses for GST and tip.


Exercise 5: Two-number calculator

Scenario: You want a tiny calculator that reads two numbers typed at the terminal and shows all four basic operations on them. What to do: Read two lines with readln(), .trim() and .toDouble() each one, then print their sum, difference, product and quotient.

Sample output: (for inputs 15 then 4)

Enter the first number:
Enter the second number:
Sum: 19.0
Difference: 11.0
Product: 60.0
Quotient: 3.75

💡 Hint: readln() already returns a plain, non-null String — no !! needed, just .trim().toDouble() on each line before you do arithmetic with it.


Exercise 6: Reproduce and fix a NumberFormatException

Scenario: Section 6 of the README showed this happening to someone else. Now make it happen to you, on purpose, and fix it. What to do:

  1. Write TrailingSpace.kt, inside solutions/ (or wherever you keep your practice files), with a val priceText = "250 " (note the trailing space) and val price = priceText.toInt(), then println(price).
  2. Compile it there without -include-runtime: kotlinc TrailingSpace.kt -d ..
  3. Run it with plain java -cp . TrailingSpaceKt. Copy the exact exception text into a comment at the top of your file.
  4. Fix it with .trim() on priceText before converting, recompile, and run the fixed version with the kotlin launcher (not plain java — .trim() is a real stdlib call, unlike .toInt(), so it needs kotlin-stdlib on the classpath, same lesson as Part 1 section 8). Copy that successful run into the same comment.

Sample output: (the broken command)

$ java -cp . TrailingSpaceKt
Exception in thread "main" java.lang.NumberFormatException: For input string: "250 "
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:662)
    at java.base/java.lang.Integer.parseInt(Integer.java:778)
    at TrailingSpaceKt.main(TrailingSpace.kt:27)
    at TrailingSpaceKt.main(TrailingSpace.kt)

Sample output: (the fix)

$ kotlin -cp . TrailingSpaceKt
250

💡 Hint: .toInt() alone compiles down to a direct call that plain java can already run, which is why the broken version above fails with NumberFormatException, not NoClassDefFoundError — the class itself isn't the problem, the trailing space is. .trim() is the one that actually needs kotlin-stdlib.jar on the classpath; the line number in your own exception will depend on how many comment lines sit above your fun main().


Exercise 7: Bill splitter with a service charge

Scenario: Some restaurants add a separate "service charge" on top of GST, before the diner's own tip. The group wants the bill splitter from section 8 extended to handle that third charge. What to do: Starting from the section 8 bill splitter, add a fixed serviceChargePercent (10%) alongside gstPercent (5%), compute all three amounts (GST, service charge, tip) from the same subtotal, and print a receipt with all three lines plus the final total and per-head share.

Sample output: (for inputs 2000, 5, 10)

Enter the food subtotal in rupees:
Enter the number of diners:
Enter the tip percent you want to leave:
-------------------------------------------
Subtotal                : ₹2000.0
GST (5.0%)             : ₹100.0
Service charge (10.0%) : ₹200.0
Tip (10.0%)              : ₹200.0
Total                    : ₹2500.0
-------------------------------------------
Each of 5 people pays: ₹500.0

💡 Hint: Each of the three charges is its own subtotal * percent / 100 line, exactly like the GST and tip lines in section 8 — there's no need for a running total variable here, since every charge is computed from the same, unchanging subtotal.


📁 About the solution filename: exercise 6 keeps its lesson-mandated name (TrailingSpace.kt) instead of ex06.kt, because for that one the filename, the generated class name and the exception's line number are all part of the subject, exactly as in Part 1.

👉 Solutions

Show the solutions for Part 2 (7 files)

solutions/ex01.kt

// Exercise 1: Chai stall tab
fun main() {
    val stallName = "Sharma Chai Corner, Jaipur"
    var tab = 0.0

    tab += 15.0   // Chai
    tab += 15.0   // Chai
    tab += 20.0   // Samosa

    println("Stall: $stallName")
    println("Items so far: 2 chai, 1 samosa")
    println("Tab: ₹$tab")
}

solutions/ex02.kt

// Exercise 2: Fix the broken program (the fixed version)
// Original bugs: reassigning a val, no explicit toLong() for an Int -> Long val,
// and a missing $ before a template name.
fun main() {
    var itemCount = 3
    itemCount = 5

    val smallTotal = 1200
    val bigTotal: Long = smallTotal.toLong()

    val city = "Chennai"
    println("City: $city")
    println("Item count: $itemCount, big total: $bigTotal")
}

solutions/ex03.kt

// Exercise 3: Product catalog types
fun main() {
    val sku = 'B'
    val price = 499
    val weightKg = 0.75
    val inStock = true
    val productName = "Steel Water Bottle"

    println("SKU: $sku (${sku::class.simpleName})")
    println("Price: ₹$price (${price::class.simpleName})")
    println("Weight: $weightKg kg (${weightKg::class.simpleName})")
    println("In stock: $inStock (${inStock::class.simpleName})")
    println("Name: $productName (${productName::class.simpleName})")
}

solutions/ex04.kt

// Exercise 4: Kirana store discount
fun main() {
    val billAmount = 1850
    val discountPercent = 10

    val discountAmount = billAmount * discountPercent / 100
    val payable = billAmount - discountAmount

    println("Bill: ₹$billAmount")
    println("Discount ($discountPercent%): ₹$discountAmount")
    println("Payable: ₹$payable")

    // Int division vs Double division, side by side
    println("9 / 2 as Int: ${9 / 2}")
    println("9.0 / 2 as Double: ${9.0 / 2}")
    println("9 % 2 (remainder): ${9 % 2}")
}

solutions/ex05.kt

// Exercise 5: Two-number calculator over readln()
fun main() {
    println("Enter the first number:")
    val a = readln().trim().toDouble()

    println("Enter the second number:")
    val b = readln().trim().toDouble()

    println("Sum: ${a + b}")
    println("Difference: ${a - b}")
    println("Product: ${a * b}")
    println("Quotient: ${a / b}")
}

solutions/ex07.kt

// Exercise 7: Bill splitter with a service charge added
fun main() {
    val gstPercent = 5.0
    val serviceChargePercent = 10.0

    println("Enter the food subtotal in rupees:")
    val subtotal = readln().trim().toDouble()

    println("Enter the number of diners:")
    val diners = readln().trim().toInt()

    println("Enter the tip percent you want to leave:")
    val tipPercent = readln().trim().toDouble()

    val gstAmount = subtotal * gstPercent / 100
    val serviceChargeAmount = subtotal * serviceChargePercent / 100
    val tipAmount = subtotal * tipPercent / 100
    val total = subtotal + gstAmount + serviceChargeAmount + tipAmount
    val perHead = total / diners

    println("-------------------------------------------")
    println("Subtotal                : ₹$subtotal")
    println("GST ($gstPercent%)             : ₹$gstAmount")
    println("Service charge ($serviceChargePercent%) : ₹$serviceChargeAmount")
    println("Tip ($tipPercent%)              : ₹$tipAmount")
    println("Total                    : ₹$total")
    println("-------------------------------------------")
    println("Each of $diners people pays: ₹$perHead")
}

solutions/TrailingSpace.kt

// Exercise 6: Reproduce and fix a NumberFormatException
//
// Real transcript (compiled WITHOUT -include-runtime, run with plain java):
//
//   $ kotlinc TrailingSpace.kt -d .
//   $ java -cp . TrailingSpaceKt
//   Exception in thread "main" java.lang.NumberFormatException: For input string: "250 "
//       at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
//       at java.base/java.lang.Integer.parseInt(Integer.java:662)
//       at java.base/java.lang.Integer.parseInt(Integer.java:778)
//       at TrailingSpaceKt.main(TrailingSpace.kt:27)
//       at TrailingSpaceKt.main(TrailingSpace.kt)
//
// .toInt() needs the string to be ONLY the number; a trailing space (as if someone had
// copy-pasted "250 " from a spreadsheet cell) makes parseInt() reject it outright.
//
// Fix -- trim() before converting. Swap which of the two priceText lines below is commented
// out, recompile, then run it with the `kotlin` launcher instead of plain `java` -- unlike
// .toInt(), .trim() is a real Kotlin stdlib function (kotlin.text.StringsKt), so plain
// `java -cp .` fails with the same NoClassDefFoundError Part 1 section 8 covered:
//
//   $ kotlin -cp . TrailingSpaceKt
//   250
fun main() {
    val priceText = "250 "   // comment out this line and uncomment the next one to see the fix
    // val priceText = "250 ".trim()
    val price = priceText.toInt()
    println(price)
}

Common mistakes

Mistake Why it is wrong Fix
Reassigning a val A val is a compile-time guarantee, not a hint — kotlinc refuses to build it Use var if the value genuinely needs to change
val total: Long = someInt Kotlin never widens numeric types implicitly, even Int → Long someInt.toLong()
7 / 2 expecting 3.5 Both operands are Int, so the division truncates to Int Make one side a Double: 7.0 / 2, or .toDouble() on a variable
7 % 2 read as "7 percent of 2" % is the remainder operator, unrelated to percentages Build a percentage with * and /, as section 8 does for GST and tip
"42 ".toInt() (trailing space from copy-pasted input) .toInt()/.toDouble() need the string to be only the number .trim() before converting
readLine()!! readLine() returns String? and needs !!; kotlinc itself warns it's deprecated readln() — same job, no nullable type, no !!
Assuming == on two Strings compares identity, Java-style Kotlin's == already calls .equals() — it compares value, not reference Use == for value comparison; reach for === only when identity itself is the question

Quick recap

  • val is read-only and enforced by the compiler; var is reassignable — default to val.
  • Kotlin infers Int, Long, Double, Boolean, Char and String from a literal, but never converts between numeric types for you, not even widening.
  • "$name" and "${expression}" are string templates; $ needs \$ to appear literally.
  • A val/var declaration is a statement; almost everything to its right, including a println(...) call, is an expression — println itself returns Unit.
  • / between two Ints truncates, % is the remainder, == compares value, === compares identity, and &&/|| short-circuit.
  • Every type conversion is an explicit call — .toInt(), .toDouble(), .toLong() — and .toInt()/.toDouble() on text throws NumberFormatException if the text isn't a clean number.
  • readln() reads one line of input as a plain String, replacing the older, nullable readLine().

Checklist

  • I can say, without looking it up, what happens if you try to reassign a val.
  • I declared values of each basic type and printed their inferred class with ::class.simpleName.
  • I wrote a string template using both the $name and ${expression} forms.
  • I can explain why println(...) is an expression, not just a statement.
  • I caused and explained the 7 / 2 integer-division result and the 7 % 2 remainder.
  • I converted a trailing-space string into a number, watched it fail, then fixed it with .trim().
  • I read two lines of real input with readln() and used them in a calculation.
  • I built and ran the restaurant bill splitter myself, with my own numbers.

Search the guide