Int Data type Usage and Type Conversion in Kotlin

Definition

  • Int is a 32-bit number in Kotlin. The type can be either declared explicitly or the compiler itself has the ability to infer the type of the assigned value.
  • Int value ranges from -2147483648 to 2147483647 ie., -(2^31) through 0 to (2^31)-1
  • In JVM, the characteristics of this "Int" variable is derived from the characteristics of primitive type int of Java which has a non-nullable default value.

Syntax and declaration

Thus an Int value can be declared by 3 ways as mentioned below.

1. Mentioning type explicitly

val variable_name : Int = value

for example,

val number : Int = 100

2. Number type is automatically inferred

val variable_name = value

for example,
//Number type is automatically inferred
val number = 100

3. Declaring and Initializing separately

var variable_name : Int 
variable_name = value

for example

//Declaring and Initializing separately
var number:Int 
number = 100

Int Datatype Example Program in Kotlin

// Int Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args: Array < String > ) {
    //Int type is inferred
    val num1 = 100 
    
    //Declaring an Int value immediately
    val num2: Int = 2147483647 
    
    //Print num1 and num2 values
    println("num1 Value : $num1")
    println("num2 Value : $num2")
}

Sample Output

num1 Value : 100
num2 Value : 2147483647

Type conversion syntax and declaration

//String to Int Conversion 
val variable_name = "string".toInt()

//Float and Double to Int Conversion 
val variable_name = float_variable.toInt()

Int type Conversion Example Program in Kotlin

// Int Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args: Array < String > ) {
    //Conversion from String and Int type is inferred
    val num1 = "500".toInt() 
    
    //Conversion from String and Declaring an Int value immediately
    val num2: Int = "100".toInt() 
    
    val num3: Float = 1000.1000f
    //Conversion from Float
    val num4: Int = num3.toInt()
    
    val num5: Double = 2000.1000
    //Conversion from Double
    val num6: Int = num5.toInt()
    
    //Print values after conversion
    println("String to Int : num1 Value : $num1")
    println("String to Int : num2 Value : $num2")
    println("Float Value : num3 Value : $num3")
    println("Float to Int : num4 Value : $num4")
    println("Double Value : num5 Value : $num5")
    println("Double to Int : num6 Value : $num6")
}

Sample Output

String to Int : num1 Value : 500
String to Int : num2 Value : 100
Float Value : num3 Value : 1000.1
Float to Int : num4 Value : 1000
Double Value : num5 Value : 2000.1
Double to Int : num6 Value : 2000