Short Data type Usage and Type Conversion in Kotlin

Definition

  • Short is a 16-bit number in Kotlin The type is to be declared explicitly.
  • The short data type can have values from -32768 to 32767.
  • In JVM, the characteristics of this "Short" variable is derived from the characteristics of primitive type short of Java which has a non-nullable default value.

Syntax and declaration

Thus a Short value can be declared by 2 ways as mentioned below.

1. Mentioning type explicitly

val variable_name : Short = value

for example,

val number : Short = 100

2. Declaring and Initializing separately

var variable_name : Short 
variable_name = value

for example

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

Short Datatype Example Program in Kotlin

// Short Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs
	
fun main(args:Array<String>) {
    //Assigning value to Byte variable explicitly
    val a:Short = -32768
    val b:Short = 32767
    
    println("Short value in a is $a")
    println("Short value in b is $b")
}

Sample Output

Short value in a is -32768
Short value in b is 32767

Type conversion syntax and declaration

//String to Short Conversion 
val variable_name = "string".toShort()

//Int to Short Conversion 
val variable_name = int_variable.toShort()

Short type Conversion Example Program in Kotlin

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

fun main(args: Array < String > ) {
    //Converted from String and Short type is inferred
    val num1 = "50".toShort()

    //Conversion from String and Declaring an Short value immediately
    val num2: Short = "30".toShort()

    val num3: Int = 10
    //Conversion from Int
    val num4: Short = num3.toShort()

    val num5: Float = 20.31f
    //Conversion from Float
    val num6: Short = num5.toShort()

    //Print values after conversion
    println("String to Short : num1 Value : $num1")
    println("String to Short : num2 Value : $num2")
    println("Int Value : num3 Value : $num3")
    println("Int to Short : num4 Value : $num4")
    println("Float Value : num5 Value : $num5")
    println("Float to Short : num6 Value : $num6")
}

Sample Output

String to Short : num1 Value : 50
String to Short : num2 Value : 30
Int Value : num3 Value : 10
Int to Short : num4 Value : 10
Float Value : num5 Value : 20.31
Float to Short : num6 Value : 20