Contents
Kotlin Data Types
In Kotlin, data types are the foundation of variable storage. Each variable must be assigned a specific data type, which determines the kind of data it can hold and the operations that can be performed on it.
1. Int (Integer): Represents a 32-bit signed integer. Suitable for whole numbers.
These data types contain integer values.
Data Type | Bits | Min Value | Max Value |
---|---|---|---|
byte | 8 bits | -128 | 127 |
short | 16 bits | -32768 | 32767 |
int | 32 bits | -2147483648 | 2147483647 |
long | 64 bits | -9223372036854775808 | 9223372036854775807 |
Example:
fun main(args: Array) {
var myInt = 35
var myLong = 23L // suffix L for long integer
println("My integer: $myInt")
println("My long integer: $myLong")
println("Smallest byte value: ${Byte.MIN_VALUE}")
println("Largest byte value: ${Byte.MAX_VALUE}")
println("Smallest short value: ${Short.MIN_VALUE}")
println("Largest short value: ${Short.MAX_VALUE}")
println("Smallest integer value: ${Int.MIN_VALUE}")
println("Largest integer value: ${Int.MAX_VALUE}")
println("Smallest long integer value: ${Long.MIN_VALUE}")
println("Largest long integer value: ${Long.MAX_VALUE}")
}
Output:
My integer: 42
My long integer: 123456789
Smallest byte value: -128
Largest byte value: 127
Smallest short value: -32768
Largest short value: 32767
Smallest integer value: -2147483648
Largest integer value: 2147483647
Smallest long integer value: -9223372036854775808
Largest long integer value: 9223372036854775807
Smallest float value: 1.4E-45
Largest float value: 3.4028235E38
Smallest double value: 4.9E-324
Largest double value: 1.7976931348623157E308
2. Boolean Data Type : The Boolean data type represents one bit of information, with two possible values: true
or false
.
Data Type | Bits | Value Range |
---|---|---|
Boolean | 1 | true, false |
Example Program:
fun main(args: Array) {
if (true is Boolean) {
println("Yes, true is a boolean value")
}
}
Output:
Yes, true is a boolean value
3. Character Data Type : Represents characters such as letters, digits, and symbols.
Data Type | Bits | Min Value | Max Value |
---|---|---|---|
Char | 16 | ‘\u0000’ | ‘\uFFFF’ |
Example Program:
fun main(args: Array) {
var alphabet: Char = 'C'
println("C is a character: ${alphabet is Char}")
}
Output:
C is a character: true
Variables
Variables in Kotlin store data values, which can be accessed and modified throughout the program. In Kotlin, every variable should be declared before it’s used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value. Kotlin enforces the declaration of variables with explicit types, providing clarity and safety.
1. Immutable (val
): Once assigned, the value of the variable cannot be changed. It is similar to a constant.
var rollNumber = 55
var studentName = "Praveen"
println(rollNumber)
println(studentName)
In the example above, the variable rollNumber
holds the value 55
, and its type is inferred as an Int
based on the literal value. Similarly, studentName
is recognized as a String
. In Kotlin, variables are declared using two primary keywords:
val
for immutable variablesvar
for mutable variables
2. Immutable Variables (val): Variables declared with val
are read-only, meaning their value cannot be changed once assigned.
val personName = "Gaurav"
personName = "Praveen" // This will cause a compile-time error
Attempting to reassign an immutable variable will result in an error. Although they cannot be reassigned, val
variables are not considered constants because they can be initialized with other variables. The value of a val
variable doesn’t need to be known at compile-time and can change during each function call if declared inside a construct that’s called repeatedly.
var birthDate = "02/12/1993"
val newBirthDate = birthDate
println(newBirthDate)
3. Mutable Variables (var) : Variables declared with var
can have their values changed after initialization.
var age = 25
age = 26 // This compiles successfully
println("My updated age is $age")
Output:
My updated age is 26
Kotlin Operators
In Kotlin, operators are special symbols that carry out operations on operands. For instance, +
and –
are operators that perform addition and subtraction, respectively. Similar to Java, Kotlin provides various kinds of operators:
- Arithmetic operators
- Relational operators
- Assignment operators
- Unary operators
- Logical operators
- Bitwise operators
Arithmetic Operators : Arithmetic operators are used to perform basic mathematical operations. Here’s a breakdown:
Operator | Meaning | Expression | Translates to |
---|---|---|---|
+ | Addition | a + b | a.plus(b) |
- | Subtraction | a - b | a.minus(b) |
* | Multiplication | a * b | a.times(b) |
/ | Division | a / b | a.div(b) |
% | Modulus | a % b | a.rem(b) |
Example:
fun main(args: Array) {
var a = 20
var b = 4
println("a + b = " + (a + b))
println("a - b = " + (a - b))
println("a * b = " + (a.times(b)))
println("a / b = " + (a / b))
println("a % b = " + (a.rem(b)))
}
Output:
a + b = 24
a - b = 16
a * b = 80
a / b = 5
a % b = 0
Relational Operators : These operators compare two values:
Operator | Meaning | Expression | Translates to |
---|---|---|---|
> | Greater than | a > b | a.compareTo(b) > 0 |
< | Less than | a < b | a.compareTo(b) < 0 |
>= | Greater than or equal to | a >= b | a.compareTo(b) >= 0 |
<= | Less than or equal to | a <= b | a.compareTo(b) <= 0 |
== | Equal to | a == b | a?.equals(b) ?: (b === null) |
!= | Not equal to | a != b | !(a?.equals(b) ?: (b === null)) |
Example:
fun main(args: Array) {
var c = 30
var d = 40
println("c > d = " + (c > d))
println("c < d = " + (c.compareTo(d) < 0))
println("c >= d = " + (c >= d))
println("c <= d = " + (c.compareTo(d) <= 0))
println("c == d = " + (c == d))
println("c != d = " + (!(c?.equals(d) ?: (d === null))))
}
Output:
c > d = false
c < d = true
c >= d = false
c <= d = true
c == d = false
c != d = true
Assignment Operators : These operators are used to assign values to variables and also modify the current values.
Operator | Expression | Translates to |
---|---|---|
+= | a = a + b | a.plusAssign(b) |
-= | a = a - b | a.minusAssign(b) |
*= | a = a * b | a.timesAssign(b) |
/= | a = a / b | a.divAssign(b) |
%= | a = a % b | a.remAssign(b) |
Example:
fun main(args: Array) {
var a = 10
var b = 5
a += b
println(a)
a -= b
println(a)
a *= b
println(a)
a /= b
println(a)
a %= b
println(a)
}
Output:
15
10
50
10
0
Unary Operators : Unary operators are applied to a single operand to modify its value.
Operator | Expression | Translates to |
---|---|---|
++ | ++a or a++ | a.inc() |
-- | --a or a-- | a.dec() |
Example:
fun main(args: Array) {
var e = 10
println("Print then increment: " + e++)
println("Increment then print: " + ++e)
println("Print then decrement: " + e--)
println("Decrement then print: " + --e)
}
Output:
Print then increment: 10
Increment then print: 12
Print then decrement: 12
Decrement then print: 10
Logical Operators : Logical operators work with boolean values.
Operator | Meaning | Expression |
---|---|---|
&& | True if both are true | (a > b) && (a > c) |
` | ` | |
! | Negates the expression | a.not() |
Example:
fun main(args: Array) {
var x = 100
var y = 25
var z = 10
var result = false
if (x > y && x > z) println(x)
if (x < y || x > z) println(y)
if (result.not()) println("Logical operators")
}
Output:
100
25
Logical operators
Bitwise Operators: Bitwise operators work directly on the bits of binary numbers.
Operator | Meaning | Expression |
---|---|---|
shl | Signed shift left | a.shl(b) |
shr | Signed shift right | a.shr(b) |
ushr | Unsigned shift right | a.ushr(b) |
and | Bitwise AND | a.and(b) |
or | Bitwise OR | a.or(b) |
xor | Bitwise XOR | a.xor(b) |
inv | Bitwise Inverse | a.inv() |
Example:
fun main(args: Array) {
println("5 shifted left by 1: " + 5.shl(1))
println("10 shifted right by 2: " + 10.shr(2))
println("12 unsigned shifted right by 2: " + 12.ushr(2))
println("36 AND 22: " + 36.and(22))
println("36 OR 22: " + 36.or(22))
println("36 XOR 22: " + 36.xor(22))
println("Bitwise inverse of 14: " + 14.inv())
}
Output:
5 shifted left by 1: 10
10 shifted right by 2: 2
12 unsigned shifted right by 2: 3
36 AND 22: 4
36 OR 22: 54
36 XOR 22: 50
Bitwise inverse of 14: -15
Kotlin Standard Input/Output
In Kotlin, standard input and output operations are used to transfer byte streams from input devices (like the keyboard) to the system’s memory and from memory to output devices (such as the monitor). This guide covers how to take input and display output using Kotlin.
Kotlin Output
In Kotlin, output is displayed using the print()
and println()
functions. Unlike Java, where we use System.out.println()
, Kotlin directly provides print()
and println()
.
Here is an example of basic output:
fun main(args: Array) {
print("Hello, World! ")
println("Welcome to Kotlin.")
}
Output:
Hello, World! Welcome to Kotlin.
Difference Between print()
and println()
print()
displays the message inside the double quotes, but the cursor stays on the same line.println()
also displays the message but moves the cursor to the next line after printing.
Example:
fun main(args: Array) {
println("Kotlin Programming")
println("Language Overview")
print("Kotlin - ")
print("Language")
}
Output:
Kotlin Programming
Language Overview
Kotlin - Language
Printing Literals and Variables
You can print literals, variables, and even the result of function calls directly using string interpolation.
Example:
fun sum(a: Int, b: Int): Int {
return a + b
}
fun main(args: Array) {
var x = 10
var y = 20
var z = 50L
var score = 88.5
println("Sum of $x and $y is: ${sum(x, y)}")
println("Long value is: $z")
println("Score: $score")
}
Output:
Sum of 10 and 20 is: 30
Long value is: 50
Score: 88.5
Kotlin Input
Kotlin provides several ways to take input from the user.
1. Using readLine():
The readLine()
function reads input from the user as a string. It’s commonly used for string input but can be converted to other types like integers or doubles using conversion functions.
Example:
fun main(args: Array) {
print("Enter some text: ")
var input = readLine()
print("You entered: $input")
}
Output:
Enter some text: Kotlin Input
You entered: Kotlin Input
2. Using the Scanner
Class : For more advanced input handling, such as accepting numbers, we can use the Scanner
class from Java. You need to import java.util.Scanner
before using it.
Example:
import java.util.Scanner
fun main(args: Array) {
val scanner = Scanner(System.`in`)
print("Enter an integer: ")
val intValue = scanner.nextInt()
println("You entered: $intValue")
print("Enter a float value: ")
val floatValue = scanner.nextFloat()
println("You entered: $floatValue")
print("Enter a boolean: ")
val boolValue = scanner.nextBoolean()
println("You entered: $boolValue")
}
Output:
Enter an integer: 10
You entered: 10
Enter a float value: 25.5
You entered: 25.5
Enter a boolean: true
You entered: true
3. Taking Input Without Using the Scanner
Class : You can also take input without importing the Scanner
class by using readLine()
and converting the string to other data types.
Example:
fun main(args: Array) {
print("Enter an integer: ")
val inputString = readLine()!!
val intValue: Int = inputString.toInt()
println("You entered: $intValue")
print("Enter a double value: ")
val doubleString = readLine()!!
val doubleValue: Double = doubleString.toDouble()
println("You entered: $doubleValue")
}
Output:
Enter an integer: 42
You entered: 42
Enter a double value: 99.99
You entered: 99.99
Kotlin Type Conversion
Type conversion, also known as type casting, refers to changing the data type of a variable into another type. In Java, implicit type conversion is allowed, meaning smaller data types can be automatically converted into larger ones. For instance, an integer value can be assigned to a long data type without any issues.
Java Example of Implicit Type Conversion:
public class TypeCastingExample {
public static void main(String args[]) {
byte p = 12;
System.out.println("byte value: " + p);
// Implicit type conversion
long q = p; // Integer value can be assigned to long
}
}
Kotlin Example of Explicit Type Conversion:
However, in Kotlin, implicit type conversion is not allowed. You cannot directly assign an integer value to a long variable.
var myNumber = 100
var myLongNumber: Long = myNumber // This will cause a compiler error
// Type mismatch: inferred type is Int but Long was expected
In Kotlin, explicit type conversion can be achieved using helper functions.
var myNumber = 100
var myLongNumber: Long = myNumber.toLong() // This will compile successfully
Kotlin Type Conversion Helper Functions:
Kotlin provides several helper functions to convert one data type to another:
toByte()
toShort()
toInt()
toLong()
toFloat()
toDouble()
toChar()
Note: There is no helper function to convert directly to a Boolean type.
Conversion from Larger to Smaller Data Types:
var myLongNumber = 10L
var myNumber2: Int = myLongNumber.toInt()
Example:
fun main(args: Array) {
println("259 to byte: " + (259.toByte()))
println("50000 to short: " + (50000.toShort()))
println("21474847499 to Int: " + (21474847499.toInt()))
println("10L to Int: " + (10L.toInt()))
println("22.54 to Int: " + (22.54.toInt()))
println("22 to float: " + (22.toFloat()))
println("65 to char: " + (65.toChar()))
// Char to Number is deprecated in Kotlin
println("A to Int: " + ('A'.toInt()))
}
Output:
259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65
Kotlin Expression, Statement and Block
An expression in Kotlin consists of variables, operators, method calls, and other elements that produce a value. Expressions are building blocks of a program, often created to compute new values or assign them to variables. It’s worth noting that expressions can also contain other expressions.
A few things to note:
- A variable declaration is not an expression (e.g.,
var a = 100
). - Assigning a value is not an expression (e.g.,
b = 15
). - A class declaration is not an expression (e.g.,
class XYZ { ... }
).
In Kotlin, every function returns at least a Unit
type, meaning every function is treated as an expression.
Here is an example of Kotlin expressions:
fun sumOf(a: Int, b: Int): Int {
return a + b
}
fun main(args: Array) {
val a = 10
val b = 5
val sum = sumOf(a, b)
val mul = a * b
println(sum)
println(mul)
}
Output:
15
50
Kotlin if
Expression
Unlike Java, where if
is a statement, in Kotlin, if
is an expression. It evaluates a condition and returns a value based on the result. This is why Kotlin doesn’t have a ternary operator like (a > b) ? a : b
, as the if
expression serves this purpose.
if (condition) conditionMet else conditionNotMet
Example: Here’s an example to find the maximum of two values:
if (condition) conditionMet else conditionNotMet
Output:
if (condition) conditionMet else conditionNotMet
Kotlin Statements
A statement is a syntactic unit in programming that expresses an action to be carried out. Programs are made up of one or more statements. While Java requires a semicolon at the end of every statement, Kotlin makes this optional.
Examples of statements:
- Declaring a variable:
val marks = 90
- Assigning a value:
var sum = 10 + 20
In the example var sum = 10 + 20
, the part 10 + 20
is an expression, while var sum = 10 + 20
is a statement.
Multiple Statements: Multiple statements can be written on a single line.
fun main(args: Array) {
val sum: Int
sum = 100
println(sum) // single statement
println("Hello"); println("World") // multiple statements
}
Output:
100
Hello
World
Kotlin Block
A block in Kotlin is a section of code enclosed in curly braces { ... }
. A block can consist of one or more statements, often with variable declarations. Blocks can also be nested. Each function in Kotlin has its own block, and the main function also contains a block.
Here’s an example of a block with a nested block:
fun main(args: Array) { // start of outer block
val array = intArrayOf(2, 4, 6, 8)
for (element in array) { // start of inner block
println(element)
} // end of inner block
} // end of outer block
Output:
2
4
6
8