$show=/label

Kotlin Variables and Basic Types With Examples - Kotlin Tutorial

SHARE:

A quick guide how to create the variables in kotlin for basic types and when to use var and val. What are the main differences between var vs val.

1. Overview

In this tutorial, We will learn how to create the variables in Koltin for basic types using var.

var is a keyword in kotlin which is used to declare the any type of variable.

Kotlin has another keyword "val" to declare the variables.

Any variable is declared using var that value can be changed at anytime whereas variable declared with val keyword value can not modified one it is initialized.

Mainly val is used to define the constants in kotlin.

Kotlin Variables and Basic Types



2. Variable var examples


var keyword is used in the variable declaration. When you are using var keyword, that indicates the value can be changed at any time and the variable type is optional. If we are not provided the type then it takes the type implicitly based on the value assigned.

Syntax:

var <variable-name> : <variable-type-optional> = value;

Examples:

Below are the few examples on with and without variable type.

First created a double variable with var keyword with 3.14 value. Next used only var and did not mention any type but assigned the value. So it takes it as double internally because value is double type.

Additionally, created a variable with string content and not mentioned its type. But, kotlin has the intelligence to inspect the value and assign the right type.

if you call the welcome.toUpperCase() method, it does not throw any error. because it knows that object is type of String. So, We can use all methods from String class.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {

    // double type
    var pi : Double = 3.14
    println("Double PI value $pi")

    // without type but it takes the double type internally based on the value
    var doubleValue = 3.14;
    println("Default type double $doubleValue")

    // Without type but it takes as String type from assigned value
    var welcome = "hello world"
    println("string welcome note $welcome")

    var str : String = "i am string"
    println("string type note $str")
}

Output:
Double PI value 3.14
Default type double : doubleValue
string welcome note hello world
string type note i am string

3. val Variable Examples


val is an another keyword in koltin and it is alos used to declare the variables.

Let us create a variable and try to change the value to new one using var and val variables.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {

    // int type varaible with var keyword
    var number: Int = 12345;
    println("old value of number : $number")
    number = 10000
    println("new value of number : $number")

    // int type variable with val keyword
    val highestMark: Int = 99;
    println("old value of highestMark : $number")
    highestMark = 98
    println("new value of highestMark : $number")
}


Output:
Kotlin: Val cannot be reassigned

It will produce the compile time error saying value can not be reassigned for val type variable.

So, val keyword is only to declare the constant values because it will not allow to change the value.

4. Difference between var and val


The main difference between the val and var keywords - is var type variables values can be modified and reassigned with the new values but val type variables can not be reassigned with the new values.

5. Assigning the large numbers to variables


When you are using the kotlin in the real time applications, there will be a need to hold the credit card or debit card numbers and phone numbers. 

var creditCardNumber : Long = 4320123456782468;

The above number is not readable but it holds the actual value. To make the numbers more readable, we can use the underscore(_) delimiter in between the numbers.

We can use the underscore for any numbers even it is good to use for currency values or time values.

but when you print or use for different operations, it does not print or get error because of underscore usage. It removes the underscore while performing any mathematical operations. This delimiter just makes the data readable form.

Look the below example for better understanding.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {
    // long numbers with underscore for readable

    var creditCardNumber: Long = 4320_3456_9808_4389
    var debitCardNumber = 1234_45678_1234_9876L
    var timeInMilliSeconds = 60_000

    // printing
    println("Credit card number : $creditCardNumber")
    println("Debit card number : $debitCardNumber")
    println("Time in milli seconds : $timeInMilliSeconds")
}

Output:

Credit card number : 4320345698084389
Debit card number : 12344567812349876
Time in milli seconds : 60000

6. Kotlin Variable With Null Values - Null Safe (?)


As of now, we have seen the variable declaration and its initialization in single line. But now you want to do only the declaration with null value.

Now, how can we create a variable with null value in kotlin?

Use the ? symbol at the end of the variable declaration to assign with null value. Look at the below syntax.

val/var <variable-name> : <variable-type-optional> ?;

Sample example program to show variable nullable.

 // declaring a variable with the null
 val noValue : String?

 // assigning value
 noValue = "assigned value"

 // printing the value
 println("novalue is now : $noValue")

Output:

novalue is now : assigned value


Note: We can not use the null variable without initializing to a value. It show the compile time error "Kotlin: Variable 'noValue' must be initialized"

7. Type Conversions


Next, let us focus on the type conversions in kotlin.

We will try to convert Int to Long value without any casting. Just assign the Int variable to Long variable.

var number1 : Int = 10;
var number2 : Long = 12345678;

// compile time error : Kotlin: Type mismatch: inferred type is Int but Long was expected
// number2 = number1;

// right conversion
number2 = number1.toLong();
println("number 2 : $number2")

Output:

number 2 : 10

In the above program first directly assigned the int value to the long value but it give compile time error.

Kotlin does not support the direct assignment conversions when the type is mentioned in the declaration. Use toLong() method to do the explicit conversion from Int to Long. This is the process to convert from any type to any type in kotlin.

If the type is not mentioned in the declaration then it is allowed for direct assignment conversion.

var number3 = 10;
var number4= 12345678;

// no compile time error
 number4 = number3;

println("number4 : $number4")

Output:

number4 : 10

Type conversion with nullable type:

When you are using the nullable value type (?) in the declaration then you must use always the variable usage.

Use the null safe(?) operator when calling methods on the variable otherwise will get the compile time error.

// variable with null type and value assignment
var number5 : Int? = 100
var number6 : Long? = 200

// compile time error - Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?
// number6 = number5.toLong()

// no error with null safe
number6 = number5?.toLong();

println("number 6 : $number6")

Output:

number 6 : 100

8. Kotlin Basic Types 


Kotlin has the basic type supports as similar to the Java.

  • Numbers
                Byte
                Short
                Int
                Long
                Float
                Double
  • Char
  • Boolean
  • Array

let us explore the different examples on how to create the numbers, characters, booleans and arrays type variables in kotlin.

// Numbers
// Byte : range -128 to 127
var byteVar: Byte = 100
println("Byte variable : $byteVar")

// Short : range -32768 to 32767
var shortVar: Short = -1000
println("Short variable : $shortVar")

// Int : range -2^31 to 2^31-1
var intVar: Int = 12345
println("Int variable : $intVar")

// Long : range -2^63 to 2^63-1
var longVar: Long = 12345678900
println("Long variable : $longVar")

// Float : single precision 32 bit float point
var floatVar: Float = 123.4F // F is mandatory at end else compile time error
println("Float variable : $floatVar")

// Double : precision 64 bit floating value
var doubleVar: Double = 1234.56
println("Double variable : $doubleVar")


// Characters
// Char
var charVar: Char = 'A'
println("Char variable : $charVar")

// Boolean - this takes only two values - true/false
var booleanVar: Boolean = true
println("Boolean variable : $booleanVar")

var booleanVarFalse: Boolean = false
println("Boolean variable false : $booleanVarFalse")

// Arrays
// implicit type declaration
var array1  = listOf(1,2,3,4,5)

// explcit type declaration
var array2  = listOf<Long>(1,2,3,4,5)

Output:
Byte variable : 100
Short variable : -1000
Int variable : 12345
Long variable : 12345678900
Float variable : 123.4
Double variable : 1234.56
Char variable : A
Boolean variable : true
Boolean variable false : false

9. Conclusion


In this tutorial, we have seen how declare the variables example programs and other interesting stuff for kotlin programmers.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Kotlin Variables and Basic Types With Examples - Kotlin Tutorial
Kotlin Variables and Basic Types With Examples - Kotlin Tutorial
A quick guide how to create the variables in kotlin for basic types and when to use var and val. What are the main differences between var vs val.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhD6ENPF84ESQf7-dh8E1wjzLP6CmuBYAiwcZa1vuUu7ShgT9NB6KIl4ENRtNJ13Pu0cZq1bRu3pPVTCivR3GG2krID0jaBQdh6vO4rHawVORneMx9klOAGorC_xr3SvaLpV8bI0ktragU/w320-h226/Kotlin+Variables+and+Basic+Types+With+Examples+-+Kotlin+Tutorial.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhD6ENPF84ESQf7-dh8E1wjzLP6CmuBYAiwcZa1vuUu7ShgT9NB6KIl4ENRtNJ13Pu0cZq1bRu3pPVTCivR3GG2krID0jaBQdh6vO4rHawVORneMx9klOAGorC_xr3SvaLpV8bI0ktragU/s72-w320-c-h226/Kotlin+Variables+and+Basic+Types+With+Examples+-+Kotlin+Tutorial.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/01/kotlin-variable-types.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/01/kotlin-variable-types.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content