Skip to main content
Kotlin Basics
CHAPTER 04 Beginner

Variables and Data Types

Updated: May 18, 2026
5 min read

# CHAPTER 4

Variables and Data Types

1. Chapter Introduction

In this chapter, we will learn how to store and manipulate data in Kotlin. Variables act as containers for storing data values. Kotlin introduces a modern approach to variable declaration that emphasizes safety and readability. You will learn the difference between var and val, explore Kotlin's basic data types (Integers, Floats, Strings, Booleans), and see how the compiler is smart enough to guess your types automatically.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare mutable variables using the var keyword.
  • Declare read-only (immutable) variables using the val keyword.
  • Understand Immutability and why it is preferred.
  • Leverage Type Inference.
  • Identify Kotlin's fundamental data types.

3. Declaring Variables (val vs var)

Kotlin has two different keywords to declare variables. This is one of the most important concepts in the language.

#### var (Variable - Mutable) Use var if you expect the value of the variable to change later in the program.

kotlin
1234567
fun main() {
    var score = 10
    println("Initial score: $score")
    
    score = 20 // We can change this because it is a 'var'
    println("New score: $score")
}

#### val (Value - Immutable / Read-Only) Use val if the value should never change once it is assigned. It is the equivalent of a final variable in Java or const in JavaScript.

kotlin
123456
fun main() {
    val birthYear = 1995
    println("Birth Year: $birthYear")
    
    // birthYear = 1996 // ERROR: Val cannot be reassigned!
}

Best Practice: Always default to using val. Only change it to var if you absolutely need to modify the data later. Immutable variables make your code safer, easier to debug, and thread-safe.

4. Type Inference (The Smart Compiler)

In Java, you have to explicitly declare the type of every variable: String name = "Alice"; In Kotlin, the compiler is smart. If you assign a value immediately, it infers the data type automatically!
kotlin
123
val name = "Alice"   // The compiler knows this is a String
val age = 28         // The compiler knows this is an Int
val isStudent = true // The compiler knows this is a Boolean

5. Explicit Type Declaration

Sometimes you want to declare a variable without assigning a value immediately. In this case, you must specify the type. You do this by adding a colon : after the variable name.
kotlin
12345678
fun main() {
    val city: String // Explicit type declaration
    
    // ... some code happens ...
    
    city = "New York" // First assignment is valid for val
    println(city)
}

6. Basic Data Types

Even though Kotlin uses type inference, it is a statically-typed language (like Java), meaning every variable has a rigid type under the hood. Kotlin does NOT have primitive types like Java (int, double). Everything in Kotlin is an Object.

#### 1. Numbers (Integers)

  • Byte: 8-bit
  • Short: 16-bit
  • Int: 32-bit (Default for whole numbers)
  • Long: 64-bit (Add an 'L' to the end of the number: val billion = 1000000000L)

#### 2. Numbers (Floating Point)

  • Float: 32-bit (Add an 'f' or 'F': val weight = 70.5f)
  • Double: 64-bit (Default for decimal numbers: val pi = 3.14159)

#### 3. Booleans Can only be true or false.

kotlin
1
val isOnline: Boolean = true

#### 4. Characters Represents a single character enclosed in single quotes.

kotlin
1
val letter: Char = 'A'

#### 5. Strings Represents text, enclosed in double quotes.

kotlin
1
val greeting: String = "Hello, Kotlin!"

7. Type Conversion

In Java, a smaller number type can be automatically upgraded to a larger one (Implicit conversion). Kotlin does NOT allow this. You must explicitly convert types using helper functions.
kotlin
12345678910
fun main() {
    val smallNumber: Int = 100
    
    // val largeNumber: Long = smallNumber // ERROR! Type mismatch
    
    // CORRECT: Use explicit conversion
    val largeNumber: Long = smallNumber.toLong()
    
    val decimal: Double = smallNumber.toDouble()
}

Available functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble(), toString().

8. Common Mistakes

  • Trying to reassign a val: This is the most common beginner error. If the compiler says "val cannot be reassigned", change the keyword to var (or better yet, rethink your logic!).
  • Forgetting the 'f' for Floats: val weight: Float = 70.5 will cause an error because 70.5 is inferred as a Double. It must be 70.5f.

9. Best Practices

  • Favor Immutability: Write programs with as many val variables as possible. This is a core philosophy of modern JVM development.
  • Let the compiler do the work: Don't write val name: String = "Bob". Just write val name = "Bob". Rely on Type Inference to keep code clean.

10. Exercises

  1. 1. Declare a read-only variable company and set it to your dream company.
  1. 2. Declare a mutable variable yearsWorked and set it to 0.
  1. 3. Increment yearsWorked to 1.
  1. 4. Print both variables using println().

11. MCQs with Answers

Question 1

Which keyword is used to declare a variable whose value CANNOT be changed once assigned?

Question 2

Which keyword is used to declare a variable whose value CAN be reassigned?

Question 3

If you write val age = 30, what feature allows Kotlin to know it is an Integer without you explicitly declaring it?

Q4. Does Kotlin have primitive types (like Java's lowercase int or double)? a) Yes b) No, everything in Kotlin is an Object (e.g., Int, Double) Answer: b) No, everything is an Object.
Question 5

How do you explicitly declare a variable as a String?

Question 6

What happens if you try to assign score = 50 where score was declared using val score = 10?

Question 7

What is the default data type for a decimal number like 5.99 in Kotlin?

Question 8

How do you ensure a decimal is treated as a Float instead of a Double?

Q9. Does Kotlin allow implicit type conversion (e.g., automatically treating an Int as a Long)? a) Yes b) No, you must use explicit conversion methods like .toLong() Answer: b) No, you must use explicit methods.
Question 10

Why do Kotlin developers prefer val over var?

12. Interview Questions

  • Q: Explain the difference between var and val in Kotlin. Which one corresponds to Java's final keyword?
  • Q: What is Type Inference in Kotlin, and how does it differ from a dynamically typed language like JavaScript? (Answer: Kotlin determines the type at *compile time* and strictly locks it. JavaScript determines it at runtime and allows the type to change completely).

13. Summary

Kotlin simplifies variable declaration by combining the power of static typing with the cleanliness of Type Inference. By prioritizing val (Immutability), Kotlin encourages developers to write safe, predictable code that avoids accidental side effects. Furthermore, Kotlin's strict rejection of implicit type conversions eliminates sneaky mathematical bugs.

14. Next Chapter Recommendation

Now that we know how to store data, we need to manipulate it! In Chapter 5: Operators and Expressions, we will learn how to perform math, compare variables, and use Kotlin's special logical operators.

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: ·