Monday, 20 March 2023

Kotlin Variables & Datatypes


            Variables are used to store data values. In kotlin we are using var and val keywords for variable declaration. Kotlin is smart enough to understand the datatype based on the value you assigned, so its not necessary to specify the datatype (Int, Float, Double, Char, Boolean, String,.. etc) at the time of variable declaration.

var keyword 

Variables declared with the var keyword can be changed/modified at any place.

Here is some way of var variable declarations,

var myText = "myText"      
var myNum = 1956            
var myDoubleNum = 5.99   
var myLetter  = 'D'     
var myBoolean = true  
          

        Here we are declaring var variables of different datatypes by assigning the value at the time of declaration.


var myNum: Int = 5                // Int
var myDoubleNum: Double = 5.99    // Double
var myLetter: Char = 'D'          // Char
var myBoolean: Boolean = true     // Boolean
var myText: String = "Hello"      // String

        Here we are declaring the variables by specifying the datatype, also we are assigning the value at the time of declaration. 


//Variable Declaration
var myNum: Int // Int
var myDoubleNum: Double // Double
var myLetter: Char           // Char
var myBoolean: Boolean     // Boolean
var myText: String       // String

//Assigning the values to declared variables
myNum = 5            
myDoubleNum = 5.99   
myLetter = 'D'      
myBoolean = true     
myText = "Hello"      

        Here we are declaring the variable by specifying the datatype. After declaring variable we are assigning the value to the variable.



val keyword 

    When you create a variable with the val keyword, the value cannot be changed/reassigned later.

Here is the example of val variable declarations.


val myText = "myText"      
val myNum = 1956            
val myDoubleNum = 5.99   
val myLetter  = 'D'     
val myBoolean = true  

        Here we are declaring val variables of different datatype by assigning the value at the time of declaration


val myNum: Int = 5                // Int
val myDoubleNum: Double = 5.99    // Double
val myLetter: Char = 'D'          // Char
val myBoolean: Boolean = true     // Boolean
val myText: String = "Hello"      // String

        Here we are declaring the variables by specifying the datatype, also we are assigning the value at the time of declaration. 



Kotlin Variables & Datatypes

               Variables are used to store data values. In kotlin we are using var and val keywords for variable declaration. Kotlin is sma...