Skip to main content
Android Development with Kotlin
CHAPTER 04 Beginner

Variables, Data Types, and Operators in Kotlin

Updated: May 16, 2026
20 min read

# CHAPTER 4

Variables, Data Types, and Operators in Kotlin

1. Introduction

In the previous chapter, we learned how to store data in named boxes called variables. However, we barely scratched the surface of how Kotlin manages computer memory. Building robust Android applications requires extreme precision regarding what data can be mutated (changed) and what specific format that data takes (text, decimals, true/false). In this chapter, we will master Variables, Data Types, and Operators in Kotlin. We will explore the critical architectural difference between var and val, explicitly define primitive Data Types, and perform mathematical operations.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand and utilize the difference between Mutable (var) and Immutable (val) variables.
  • Explicitly declare data types (Int, Double, Boolean, String).
  • Perform mathematical operations using Arithmetic Operators.
  • Execute Type Conversions safely.

3. The Golden Rule: val vs var

Kotlin has two entirely different keywords for creating variables. Understanding the difference is the most important concept in Kotlin memory management.

var (Variable / Mutable): The data inside this box CAN be changed later.

kotlin
12345678
fun main() {
    var playerHealth = 100
    println(playerHealth) // Prints 100
    
    // The player takes damage! We change the variable.
    playerHealth = 80 
    println(playerHealth) // Prints 80
}

val (Value / Immutable): The data inside this box is LOCKED. It can NEVER be changed once assigned. It is a "constant".

kotlin
1234
fun main() {
    val maxPlayers = 4
    // maxPlayers = 5 // FATAL ERROR: "Val cannot be reassigned!"
}

*Best Practice Rule:* ALWAYS use val unless you are absolutely certain the variable needs to change in the future. This prevents massive bugs where data is accidentally overwritten!

4. Explicit Data Types

While Type Inference (letting Kotlin guess) is great, sometimes you want to explicitly tell the computer exactly what type of data the box must hold. You do this using a colon :.
  • Int: Whole numbers (e.g., 10, -500)
  • Double: Decimal numbers (e.g., 3.14, 99.99)
  • Boolean: True or False flags.
  • String: Text wrapped in double quotes.
kotlin
1234567
fun main() {
    // Explicit Type Declaration
    val age: Int = 25
    val price: Double = 19.99
    val isGameOver: Boolean = false
    val username: String = "AdminUser"
}

5. Type Conversion

If you try to add an Int to a String, the app will crash. You must convert types explicitly! Kotlin provides built-in helper functions like .toInt(), .toDouble(), and .toString().
kotlin
123456789101112
fun main() {
    val stringNumber = "50"
    
    // val total = stringNumber + 10 // ERROR! Cannot add String and Int!
    
    // 1. Convert the String into a real Integer!
    val realNumber = stringNumber.toInt() 
    
    // 2. Now the math works!
    val total = realNumber + 10 
    println(total) // Prints 60
}

6. Arithmetic Operators

Kotlin uses standard mathematical symbols:
  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus (Remainder): %
kotlin
123456789101112
fun main() {
    var gold = 100
    
    // Standard Math
    gold = gold + 50 
    
    // Shorthand Math (Does the exact same thing, but faster to type!)
    gold += 50  
    
    // Increment by exactly 1
    gold++      
}

7. Logical Operators

When dealing with Boolean variables (True/False), we use logical operators to combine conditions.
  • && (AND): Both sides must be true.
  • || (OR): Only one side needs to be true.
  • ! (NOT): Reverses the boolean (True becomes False).
kotlin
12345678
fun main() {
    val hasKey = true
    val doorIsUnlocked = false
    
    // OR Operator: Can we open the door?
    val canEnter = hasKey || doorIsUnlocked 
    println("Can enter? $canEnter") // Prints true (because hasKey is true!)
}

8. Mini Project: Character Stats

Let's combine explicit data types, val vs var, and arithmetic operators.
kotlin
1234567891011121314151617181920212223
fun main() {
    // Immutable stats (These never change!)
    val characterName: String = "Eldoria"
    val characterClass: String = "Mage"
    
    // Mutable stats (These change during gameplay!)
    var level: Int = 1
    var experiencePoints: Double = 0.0
    var isAlive: Boolean = true
    
    // Simulating combat
    println("--- BATTLE START ---")
    println("$characterName the $characterClass attacks!")
    
    // Gaining XP
    experiencePoints += 45.5
    
    // Leveling up
    level++
    
    println("Battle Won! Current XP: $experiencePoints")
    println("Level Up! You are now level $level.")
}

9. Common Mistakes

  • Integer Division: If you divide two Int variables in Kotlin (e.g., val result = 5 / 2), the answer will be 2, NOT 2.5. Because both numbers are Integers, Kotlin chops off the decimal! To get a decimal answer, at least one number must be a Double (e.g., val result = 5.0 / 2).
  • Reassigning val: Beginners often use val everywhere because it's shorter to type, and then get frustrated when the compiler throws errors when they try to update a score counter. Remember: val = Locked. var = Changeable.

10. Best Practices

  • Prefer val Over var: In enterprise Android engineering, mutability (data changing) is the number one cause of unpredictable bugs. If you create a variable that just holds a downloaded URL, and it never needs to change, it MUST be a val. Only elevate it to var if the application logic strictly demands mutation.

11. Exercises

  1. 1. Declare a mutable variable named temperature and explicitly assign it a Double data type with a value of 98.6.
  1. 2. Change the value of temperature to 100.2.

12. Coding Challenges

Challenge: Write a script that converts Celsius to Fahrenheit. Create an immutable val named celsius set to 25.0. The formula for Fahrenheit is (celsius * 9/5) + 32. Execute the math, store it in a val named fahrenheit, and print the result using string interpolation.

13. MCQ Quiz with Answers

Question 1

In Kotlin, what is the fundamental architectural difference between the val and var keywords?

Question 2

A developer writes: val input = "50". They want to multiply this value by 2. Which of the following code snippets correctly prevents a Type Mismatch crash?

14. Interview Questions

  • Q: Explain the paradigm of "Immutability" in software engineering. Why does Kotlin heavily encourage developers to default to val instead of var?
  • Q: Describe the behavior of Integer Division in Kotlin. If you execute val ratio = 10 / 3, what is the exact data type and value assigned to ratio, and why?
  • Q: Contrast the Explicit Data Type declaration (val age: Int = 10) with Type Inference (val age = 10). In what specific architectural scenario might Explicit Declaration be absolutely mandatory?

15. FAQs

Q: I see some code using const val. What is the difference between val and const val? A: A standard val is determined at "Runtime" (when the app is actually running). A const val is determined at "Compile Time" (before the app even launches). const val is strictly used for global constants at the very top of a file, like const val BASEAPIURL = "https://google.com".

16. Summary

In Chapter 4, we solidified our understanding of Kotlin memory allocation. We mastered the critical architectural rule of Immutability, learning to default to val to prevent unpredictable data mutation, elevating to var only when strictly necessary. We took direct control over memory structures by explicitly defining primitive Data Types (Int, Double, String, Boolean), successfully executed Type Conversions to bridge disparate data formats, and manipulated logic utilizing fundamental Arithmetic and Logical Operators.

17. Next Chapter Recommendation

Our scripts currently run from top to bottom, executing every single line perfectly. But what if we only want code to run *if* a user is a VIP? What if we want code to repeat 100 times automatically? Proceed to Chapter 5: Conditions, Loops, and Control Flow.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·