What is Int in Kotlin: Explanation and Examples
Int in Kotlin is a data type that represents a 32-bit signed integer number. It is used to store whole numbers without decimals, such as 1, 100, or -50.How It Works
Think of Int as a box that can hold whole numbers, both positive and negative, but not fractions or letters. This box has a fixed size that can store numbers from -2,147,483,648 to 2,147,483,647. When you use Int in Kotlin, you are telling the computer to reserve this box size for your number.
Just like you choose the right size of a container to store your items, you choose Int when you need to work with whole numbers that fit in this range. Kotlin manages these numbers efficiently, so operations like addition, subtraction, and comparison are fast and safe.
Example
This example shows how to declare and use Int variables in Kotlin.
fun main() {
val age: Int = 25
val year: Int = 2024
val temperature: Int = -5
println("Age: $age")
println("Year: $year")
println("Temperature: $temperature")
}When to Use
Use Int when you need to store whole numbers without decimals, such as counting items, storing ages, or representing years. It is perfect for everyday numbers that fit within its range.
For example, if you are making an app that tracks the number of steps a user takes, Int is a good choice. However, if you need to store very large numbers or decimals, you would use other types like Long or Double.
Key Points
- Int stores 32-bit signed whole numbers.
- Range is from -2,147,483,648 to 2,147,483,647.
- Used for counting, indexing, and simple math without decimals.
- More efficient than floating-point types for whole numbers.
Key Takeaways
Int is a Kotlin type for whole numbers within a fixed range.Int for counting and simple math without decimals.Int variables hold values from -2,147,483,648 to 2,147,483,647.Int for efficient storage of typical integer values.