MegalaTechBuzz
This blog will help to improve your technical Knowledge. This blog Contains C,C++,Java Interview based questions, Problems Solving questions. This blog will give an idea about Basic Android studio kotlin. It will help you to design your own app.
Wednesday, June 28, 2023
Kotlin Data Types
Kotlin Data Types:
In Kotlin, the type of a variable is decided by its value:
Ex:
val myNum = 5 // Int
val myDoubleNum = 5.99 // Double
val myLetter = 'D' // Char
val myBoolean = true // Boolean
val myText = "Hello" // String
However, you learned from the previous chapter that it is possible to specify the type if you want:
Ex:
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
Sometimes you have to specify the type, and often you don't. Anyhow, it is good to know what the different types represent.
You will learn more about when you need to specify the type later.
Data types are divided into different groups:
Numbers
Characters
Booleans
Strings
Arrays
Numbers
Number types are divided into two groups:
Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are
Byte,Short,IntandLong.Floating point types represent numbers with a fractional part, containing one or more decimals. There are two types:
FloatandDouble.If you don't specify the type for a numeric variable, it is most often returned as Int for whole numbers and Double for floating point numbers.
Integer Types
Byte
The
Bytedata type can store whole numbers from -128 to 127. This can be used instead ofIntor other integer types to save memory when you are certain that the value will be within -128 and 127:Ex:
val myNum: Byte = 100
println(myNum)
Short
The
Shortdata type can store whole numbers from -32768 to 32767:Ex:
val myNum: Short = 5000
println(myNum)
Int
The
Intdata type can store whole numbers from -2147483648 to 2147483647:println(myNum)
Long
The
Longdata type can store whole numbers from -9223372036854775807 to 9223372036854775807. This is used whenIntis not large enough to store the value. Optionally, you can end the value with an "L":Ex:
val myNum: Long = 15000000000L
println(myNum)
Difference Between Int and Long
A whole number is an
Intas long as it is up to 2147483647. If it goes beyond that, it is defined asLong:val myNum1 = 2147483647 // Int
val myNum2 = 2147483648 // Long
Floating Point Types
Floating point types represent numbers with a decimal, such as 9.99 or 3.14515.
The Float and Double data types can store fractional numbers:
Ex:
val myNum: Float = 5.75F
println(myNum)
Ex:
val myNum: Float = 5.75F
println(myNum)
Use Float or Double?
The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of Float is only six or seven decimal digits, while Double variables have a precision of about 15 digits. Therefore it is safer to use Double for most calculations.
Also note that you should end the value of a Float type with an "F"
Booleans
The Boolean data type and can only take the values true or false:
Ex:
val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun) // Outputs true
println(isFishTasty) // Outputs false
Characters
The Char data type is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c':
Ex:
val myGrade: Char = 'B'
println(myGrade)
Unlike Java, you cannot use ASCII values to display certain characters. The value 66 would output a "B" in Java, but will generate an error in Kotlin:
Example
val myLetter: Char = 66
println(myLetter) // Error\
Strings
The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:
Ex:
val myText: String = "Hello World"
println(myText)
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Type Conversion
Type conversion is when you convert the value of one data type to another type.
In Kotlin, numeric type conversion is different from Java. For example, it is not possible to convert an Int type to a Long type with the following code:
Ex:
val x: Int = 5
val y: Long = x
println(y) // Error: Type mismatch
To convert a numeric data type to another type, you must use one of the following functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble() or toChar():
Ex:
val x: Int = 5
val y: Long = x.toLong()
println(y)
Kotlin Variables
Kotlin Variables
Variables are containers for storing data values.
To create a variable, use
varorval, and assign a value to it with the equal sign (=):Syntax
var variableName = value
val variableName = value
Ex:
var name = "John"
val birthyear = 1975
println(name) // Print the value of name
println(birthyear) // Print the value of birthyear
The difference between
varandvalis that variables declared with thevarkeyword can be changed/modified, whilevalvariables cannot.Variable Type
Unlike many other programming languages, variables in Kotlin do not need to be declared with a specified type (like "String" for text or "Int" for numbers, if you are familiar with those).
To create a variable in Kotlin that should store text and another that should store a number, look at the following example:
Ex:
var name = "John" // String (text)
val birthyear = 1975 // Int (number)
println(name) // Print the value of name
println(birthyear) // Print the value of birthyear
Kotlin is smart enough to understand that "John" is a
String(text), and that 1975 is anInt(number) variable.However, it is possible to specify the type if you insist:
Ex:
var name: String = "John" // String
val birthyear: Int = 1975 // Int
println(name)
println(birthyear)
You can also declare a variable without assigning the value, and assign the value later. However, this is only possible when you specify the type:
Ex: Ex:
This works fine: This will generate an error:
var name: String var name
name = "John" name = "John"
println(name) println(name)
Kotlin Comment
Kotlin Comments
Comments can be used to explain Kotlin code, and to make it more readable. It can also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments starts with two forward slashes (
//).Any text between
//and the end of the line is ignored by Kotlin (will not be executed).This example uses a single-line comment before a line of code:
Ex:
println("Hello World") // This is a comment
This example uses a single-line comment at the end of a line of code:
Multi-line Comments
Multi-line comments start with
/*and ends with*/.Any text between
/*and*/will be ignored by Kotlin.This example uses a multi-line comment (a comment block) to explain the code:
Ex:
println("Hello World") /* The code below will print the words Hello World
to the screen, and it is amazing */
Kotlin Syntax
Kotlin Syntax
In the previous chapter, we created a Kotlin file called
Main.kt, and we used the following code to print "Hello World" to the screen:Example:
fun main()
{
println("Hello World")
}
Ex Explained:
The
funkeyword is used to declare a function. A function is a block of code designed to perform a particular task. In the example above, it declares themain()function.The
main()function is something you will see in every Kotlin program. This function is used to execute code. Any code inside themain()function's curly brackets{}will be executed.For example, the
println()function is inside themain()function, meaning that this will be executed. Theprintln()function is used to output/print text, and in our example it will output "Hello World".Note: In Kotlin, code statements do not have to end with a semicolon (
;) (which is often required for other programming languages, such as Java, C++, C#, etc.).
Kotlin Get Started
Kotlin IDE
The easiest way to get started with Kotlin, is to use an IDE.
An IDE (Integrated Development Environment) is used to edit and compile code.
In this chapter, we will use IntelliJ (developed by the same people that created Kotlin) which is free to download from https://www.jetbrains.com/idea/download/.
Kotlin Install
Once IntelliJ is downloaded and installed, click on the New Project button to get started with IntelliJ:

Then click on "Kotlin" in the left side menu, and enter a name for your project:

Next, we need to install something called JDK (Java Development Kit) to get our Kotlin project up and going. Click on the "Project JDK" menu, select "Download JDK" and select a version and vendor (e.g. AdoptOpenJDK 11) and click on the "Download" button:

When the JDK is downloaded and installed, choose it from the select menu and then click on the "Next" button and at last "Finish":

Now we can start working with our Kotlin project. Do not worry about all of the different buttons and functions in IntelliJ. For now, just open the src (source) folder, and follow the same steps as in the image below, to create a kotlin file:

Select the "File" option and add a name to your Kotlin file, for example "Main":

You have now created your first Kotlin file (Main.kt). Let's add some Kotlin code to it, and run the program to see how it works. Inside the Main.kt file, add the following code:
main.kt
fun main()
{
println("Hello World")
}

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, lets focus on how to run the code. Click on the Run button at the top navigation bar, then click "Run", and select "mainkt".
Next, IntelliJ will build your project, and run the Kotlin file. The output will look something like this:

As you can see, the output of the code was "Hello World", meaning that you have now written and executed your first Kotlin program!
