In this tutorial, we will learn about kotlin basic data types. We will see different data types in kotlin like – Number, Character, Strings, Arrays etc.
This post will cover basic data types in Kotlin programming language. You can check Basics About Kotlin, how to create kotlin project in Android Studio, IntelliJ IDEA or Eclipse.
Data type of a variable decides how much space it occupies in memory location and how the bit pattern stored is interpreted. It also decides what are the operation that can be performed on the variable.
Kotlin is a statically typed programming language i.e. type of the variable defined in the program is known during the compile time. For example,
var marks = 30; val name: String
Here, the compiler knows that marks is of type Integer and name is of type String before the compile time.
The built-in types in Kotlin can be categorised as:-
1. Numbers
2. Characters
3. Booleans
4. Arrays
5. Strings
We will talk about each type one by one.
1. Kotlin Numbers Data Type
Numbers in Kotlin are similar to Java, but not exactly the same. For example, There are not implicit widening conversion for numbers.
There are 6 built-in types representing numbers.
A. Byte
– Bit width is 8. So, This data type can have values from -128 to 127 (8 bit signed 2’s complement integer).
– This data type is used when we are sure that value of variable will be between 128 to -127. this way we save the memory.
– Example,
fun main (args : Array) { val marks: Byte = 100 println("$marks"); }
When you run the program, you will get 100 as output.
Now, Guess what will be the output in below scenarios
2.
fun main (args : Array) { val marks: Byte = -100 println("$marks"); }
3.
fun main (args : Array) { val marks: Byte = 200 println("$marks"); }
4.
fun main (args : Array) { val marks: Byte = -120 println("$marks"); }
5.
fun main (args : Array) { val marks: Byte = -220 println("$marks"); }
B. Short
– It’s bit width is 16. So, it can have value from -32768 to 32767 (16 bit signed 2’s complement integer).
– It is used when we are sure that values will be between -32768 to 32767. This way we can save memory.
– Example,
Can you guess the output of below programs?
1.
fun main (args : Array) { val fbLikes: Short = 3200 println("$fbLikes"); }
2.
fun main (args : Array) { val fbLikes: Short = -3200 println("$fbLikes"); }
3.
fun main (args : Array) { val fbLikes: Short = -32000 println("$fbLikes"); }
4.
fun main (args : Array) { val fbLikes: Short = 32000 println($fbLikes"); }
5.
fun main (args : Array) { val fbLikes: Short = 0 println("$fbLikes"); }
6.
fun main (args : Array) { val fbLikes: Short = -320000 println("$fbLikes"); }
C. Int
– It’s bit width is 32. So, it can have value from -2^31 to 2^31 – 1 (32 bit signed 2’s complement integer).
Note: If you do not specify data type of a variable while declaring it and assign an integer value between -2^32 to 2^31 – 1. Then, compiler will infer it’s data type as Int.
– Example,
Can you guess the output of below program?
1.
fun main (args : Array) { val population = -20000 println("$population"); }
2.
fun main (args : Array) { val population: Int = -20000; println("$population"); }
Note: If you are using IntelliJ IDEA or Android Studio, you can check the data type by placing the cursor inside the variable and pressing ctrl + shift + p.
D. Long
– It’s bit width is 64. So, it can have value from -2^63 to 2^63 – 1 (64 bit signed 2’s complement integer).
– If you assign a value (without specifying it’s data type explicitly) that is either less than – 2^31 or greater than 2^31 – 1, then, it’s data type will be Long.
– If you want to specify the Long data type explicitly, you can do so by adding L symbol next to the value being assigned to the variable while declaring it.
– Example,
1. What is the data type of below variable?
val distance = 10000000000
2. What is the data type of below variable?
var capacity = 1000L;
3. What is the data type of below variable?
var capacity = 1000;
E. Double
– It’s bit width is 64.
– It is double-precision 64 bit floating point.
– If you assign a floating point value to a variable and do not declare the data type explicitly, it is inferred as Double data type variable by the compiler.
– Example,
1. Can you guess data type of “average”?
fun main(args : Array) { val average = 3.8 println("$average") }
F. Float
– It’s bit-width is 32.
– It is a single-precision 32 bit floating point.
– You can declare Float variable as below –
var average: Float = 3.8F
or
var average = 3.8F
Notice that we have added F with the value being assigned to the variable average. This is just to tell the compiler that data type of average is Float. What would happen if we do not add F?
– Example,
1. Can you guess the data type of average in below program?
val average = 4.2F
2. Guess the data type of average.
val average = 4.2
3. What is data type of average?
val average: Float = 4.2F
If you want to declare a variable that can take any value it is assigned, you should declare it’s type as Number. By this way, you can assign any value (Integer, float or double) to it.
For example,
fun main(args : Array) { var numb: Number = 12.2 println("$numb") numb = 12.4F // Float smart cast from Number println("$numb") numb = 12 // Int smart cast from Number println("$numb") numb = 120L // Long smart cast from Number println("$numb") }
Important points about Numbers
– Numbers are boxed when a nullable reference is needed. Identity is not preserved by the boxing operation.
– Due to different representation of Number types, smaller types are not sub-types of bigger type.
– Every number type supports the following conversions:
* toByte(): Byte * toShort(): Short * toInt(): Int * toLong(): Long * toFloat(): Float * toDouble(): Double * toChar(): Char
– Kotlin supports the standard sets of arithmetical operations over numbers.
– Complete list of bitwise operations (available for Int and Long only) that you can perform in Numbers:
* shl(bits) – signed shift left (Java's <<) * shr(bits) – signed shift right (Java's >>) * ushr(bits) – unsigned shift right (Java's >>>) * and(bits) – bitwise and * or(bits) – bitwise or * xor(bits) – bitwise xor * inv() – bitwise inversion
2. Kotlin Character Data Type
– Characters are represented by the type Char.
– You need to use single quotes ‘ ‘ to denote a character. For example,
'1', '2', 'c', 'g' etc.
– You can declare Char variable as below.
var letter = 'm'
or
var letter: Char = 'm'
– Special characters can be escaped using a backslash. For example,
\t, \b, \n, \r etc.
– To encode any other character, you need to use the Unicode escape sequence syntax. For example, ‘\uFF00’.
– They can not be treated directly with Numbers.
– Like Numbers, characters are boxed when a nullable reference is needed. Identity is not preserved by the boxing operation.
– Example,
1. Can you guess the output?
fun main(args : Array) { var letter: Char letter = 'm' println("$letter") }
2. Can you guess the output?
fun main(args : Array) { var letter = 'm' println("$letter") }
3. Can you guess the output?
fun main(args : Array) { var letter: Char letter = 78 }
4. What is output of the below program?
fun main(args : Array) { var letter: Char = 78 }
3. Kotlin Boolean Data Type
– Boolean are represented by the type Boolean.
– It has two values – True or False.
– Booleans are boxed if nullable reference is needed.
– Built-in operations on boolean includes –
|| - lazy disjunction && - lazy conjunction ! - negation
– It is used in decision making.
– Example,
1. What is output of below program?
fun main(args : Array) { var isReady = true; if(isReady) println("True") else println("False"); }
2. What is output of below program?
fun main(args : Array) { var isReady = false; if(isReady) println("True") else println("False"); }
4. Kotlin Arrays Data Type
As you know very well, An array is a container that holds value of single type. For example, an array of Int that holds 100 integer values, an array of Float that holds 58 floating point values etc.
In Kotlin, arrays are represented by Array class. It has get and set functions, and size property, along with other useful member functions.
How to create array in kotlin?
In Kotlin, you can create array in 2 ways.
a. Using Library Function.
b. Using Factory Function.
a. Create Array Using Library Function
You can create an array in kotlin using library function arrayOf() and pass the values to it. For example,
2. arrayOfNulls() library function can be used to create an array of given size that are initialised with null values.
3. What is output of below program?
fun main(args : Array) { var numbList = arrayOf(1,2,3,4,5,6); for(numb in numbList) { println(numb) } }
b. Create Array Using Factory Function
You can create an array in Kotlin using factory function that takes size of array and the function that can return initial value of each element, present in the array, given it’s index. For example,
val asc = Array(5, { i -> (i * i).toString() })
1. What is output of below program?
fun main(args : Array) { var numbList = Array(5, { i -> (i * i).toString() }) for(numb in numbList) { println(numb) } }
Important points about Array
– Arrays in kotlin are invariant i.e. You can not assign Array to an Array. This way kotlin reduces the possible runtime error.
– You can represent arrays of primitive types without boxing overhead. We have special class for these purposes. For example, ByteArray (to represent array of Byte), IntArray (to represent array of Int) or ShortArray (to represent array of Short) etc. These classes are not inherited from Array class but they have same set of methods and properties. Each of them also have corresponding factory function. For example,
fun main(args : Array) { val x: IntArray = intArrayOf(2, 3, 4) x[0] = x[1] + x[2] println(x[0]) }
5. Kotlin String Data Type
– Strings are represented by the type String.
– Strings are immutable.
– Elements of Strings are characters that can be accessed by indexing operation. For example, s[i].
– Like other programming language, You can iterate string using for loop in kotlin. For example,
for (c in str) { println(c) }
String Literals
Kotlin has two types of string literals.
– a. Escaped Strings.
– b. Raw Strings.
a. Escaped Strings
– It can have escaped characters in them. For example,
val s = "Hello, world!\n"
– It is same as String in Java. Escaping is done in conventional way i.e. using backslash.
b. Raw Strings
– It can have newlines and arbitrary text in them. It is delimited by using triple quotes (“””). It contains no escaping. For example,
val text = """ This is Rajeev Kumar """
Some example of Strings –
fun main(args : Array) { val text: "Hi Tutorialwing!\n" println(text) }
2. What is output of below program?
fun main(args : Array) { val text = """ Hello Tutorialwing! \n """ println(text) }
Conclusion
In this tutorial, we discussed about different data types of Kotlin programming language. we also went through different examples of kotlin basic data types. We saw how to use kotlin number, character, string, array or boolean data type. You can check about Kotlin programming language to know more.
You must be logged in to post a comment.