In this article you will learn what is data type and what are the different data types that exist in kotlin.

Data type

Data type tells the compiler what kind of data are we dealing with and how we intend to use them.

Following are the different data types that exist in Kotlin.

  1. Numbers : Bytes, Short, Int, Long, Float, Double
  2. Boolean
  3. Char
  4. Arrays
  5. String

Let’s briefly discuss all of those Data types.

Bytes

This Data type is used to denote a number anywhere from -128 to 127.

fun main(args: Array<String>) {
    val number: Byte = 10
    println(number * number)
}

If you try to assign a value higher than 127 then you will get an error.

fun main(args: Array<String>) {
    val number: Byte = 128
    println(number * number)
}

Short

This data type is used to represent a number anywhere from -32768 to 32767.

fun main(args: Array<String>) {
    val number: Short = 32767
    println(number * number)
}

If you try to assign a value greater than 32767 then you will get an error.

Int

This Data type is used to denote a number anywhere from -231 to 231-1. This data type is known as integer.

fun main(args: Array<String>) {
    val number: Int = 32767
    println(number * number)
}

If you do not specify any type then the compiler will by default assume it as an Int.

Long

This data type is used to denote a number anywhere from -263 to 263-1.

fun main(args: Array<String>) {
    val number: Long = 2_147_483_648
    println(number * number)
}

If you do not specify any type then the compiler will by default assume it as an Long because it is in the range of -263 to 263-1.

Note that we can insert ‘_’ in between numbers to improve the readability of the code.

Double

In kotlin, any floating point number i.e number with decimal is by default Double.

fun main(args: Array<String>) {
    val number: Double = 0.2
    println(number * number)
}

Float

Float can also be used to represent floating point numbers. The difference between Float and Double is that Float provides 6-7 decimal precision whereas Double provides 15-16 decimal point precision. To use the Float data type we need to suffix the number with ‘f’ or ‘F’ character.

fun main(args: Array<String>) {
    val number1: Float = 0.2f
    val number2: Float = 0.2f
    println(number1 * number2)
}

Boolean

If the data can be true or false then we use Boolean data type.

fun main(args: Array<String>) {
    val flag: Boolean = true
    println(flag)
}

Char

Char is used to represent 16 bit unicode characters. This data type is known as characters.

fun main(args: Array<String>) {
    val letter: Char = 'u'
    println(letter)
}

I have written separate articles for Kotlin Arrays and String as there are a lot of things to explore. Click on the next button to continue reading.

Category
Tags

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *