Variables and Data Types
# 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 betweenvar 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
varkeyword.
-
Declare read-only (immutable) variables using the
valkeyword.
- 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.
#### 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.
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!
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.
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.
#### 4. Characters Represents a single character enclosed in single quotes.
#### 5. Strings Represents text, enclosed in double quotes.
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.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 tovar(or better yet, rethink your logic!).
-
Forgetting the 'f' for Floats:
val weight: Float = 70.5will cause an error because70.5is inferred as aDouble. It must be70.5f.
9. Best Practices
-
Favor Immutability: Write programs with as many
valvariables 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 writeval name = "Bob". Rely on Type Inference to keep code clean.
10. Exercises
-
1.
Declare a read-only variable
companyand set it to your dream company.
-
2.
Declare a mutable variable
yearsWorkedand set it to0.
-
3.
Increment
yearsWorkedto1.
-
4.
Print both variables using
println().
11. MCQs with Answers
Which keyword is used to declare a variable whose value CANNOT be changed once assigned?
Which keyword is used to declare a variable whose value CAN be reassigned?
If you write val age = 30, what feature allows Kotlin to know it is an Integer without you explicitly declaring it?
int or double)?
a) Yes b) No, everything in Kotlin is an Object (e.g., Int, Double)
Answer: b) No, everything is an Object.
How do you explicitly declare a variable as a String?
What happens if you try to assign score = 50 where score was declared using val score = 10?
What is the default data type for a decimal number like 5.99 in Kotlin?
How do you ensure a decimal is treated as a Float instead of a Double?
Int as a Long)?
a) Yes b) No, you must use explicit conversion methods like .toLong()
Answer: b) No, you must use explicit methods.
Why do Kotlin developers prefer val over var?
12. Interview Questions
-
Q: Explain the difference between
varandvalin Kotlin. Which one corresponds to Java'sfinalkeyword?
- 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 prioritizingval (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.