Byte Data type Usage and Type Conversion in Kotlin
On this page (9sections)
Definition
- A byte is an 8-bit number in Kotlin. This type is mentioned explicitly.
- A byte value ranges from -128 to 127
- In JVM, the characteristics of this “Byte” variable is derived from the characteristics of primitive type byte of Java which has a non-nullable default value.
Syntax and declaration
Thus a Byte value can be declared in 2 ways as mentioned below.
1. Mentioning type explicitly
val variable_name : Byte = value
for example,
val number : Byte = 20
2. Declaring and Initializing separately
var variable_name : Byte
variable_name = value
for example
//Declaring and Initializing separately
var number:Byte
number = -50
Byte Datatype Example Program in Kotlin
// Byte Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs
fun main(args:Array<String>) {
//Assigning value to Byte variable explicitly
val a:Byte = 100
val b:Byte = -50
println("The byte is: $a")
println("The byte is: $b")
}
Sample Output
The byte is: 100
The byte is: -50
Type conversion syntax and declaration
//String to Byte Conversion
val variable_name = "string".toByte()
//Int to Byte Conversion
val variable_name = int_variable.toByte()
Byte type Conversion Example Program in Kotlin
// Byte Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs
fun main(args: Array < String > ) {
//Converted from String and Byte type is inferred
val num1 = "50".toByte()
//Conversion from String and Declaring an Byte value immediately
val num2: Byte = "30".toByte()
val num3: Int = 10
//Conversion from Int
val num4: Byte = num3.toByte()
val num5: Float = 20.31f
//Conversion from Float
val num6: Byte = num5.toByte()
//Print values after conversion
println("String to Byte : num1 Value : $num1")
println("String to Byte : num2 Value : $num2")
println("Int Value : num3 Value : $num3")
println("Int to Byte : num4 Value : $num4")
println("Float Value : num5 Value : $num5")
println("Float to Byte : num6 Value : $num6")
}
Sample Output
String to Byte : num1 Value : 50
String to Byte : num2 Value : 30
Int Value : num3 Value : 10
Int to Byte : num4 Value : 10
Float Value : num5 Value : 20.31
Float to Byte : num6 Value : 20