Instruction 4
Learning About Basic Data Types: Boolean and Strings
In this lesson, you’ll cover the remaining data types - Booleans and Strings.
Boolean
The Boolean data type can be only one of two types: true or false. This makes it suitable for representing data that can only be in two states. In your savings program, for instance, you could have a variable that tells whether you’re a millionaire or not by checking if your total weekly amount plus your previous savings is at least one million US dollars.
Add a currentBalance variable that represents all your past savings from the previous weeks. This amount is to be added to the total amount every week to update your total savings. Following the ’totalWeeklyAmount` calculation, make the following changes after the daily calculation:
...
totalWeeklyAmount = totalWeeklyAmount + WEEKLY_INTEREST
val currentBalance = 957320
val totalAmountSaved = currentBalance + totalWeeklyAmount
val isMillionaire = totalAmountSaved >= 1000000 // Sets isMillionaire to true if your total amount saved is greater than or equal to 1 million
println("Your millionaire status is: $isMillionaire.")
...
Run the program to know whether you’ve reached millionaire status or not. :]
Character
Characters represent single-character symbols and numbers. They’re represented in Kotlin by the Char class. They’re instantiated using single quotes '. See the following examples:
val grade = 'A'
Note: There are also special characters. These are preceded by a
\and have distinct meanings depending on the character(s) that follow the\.
String
Strings represent text. Strings are, in effect, a sequence of characters put together. In Kotlin, they’re defined by the String class. They’re initialized with double quotes ". Strings are widely used in software programming. Every object in Kotlin has a string representation.
There are two types of string literals in Kotlin:
-
Escaped strings: These are strings that contain the escape character
\. This is the same as the special characters you saw earlier. -
Multiline strings: Multiline strings begin with three double quotes instead of two. They contain newlines and don’t use special characters or escaped strings.
For escaped strings, add the following closing message to your program at the bottom of the main function:
val message = "End of the program!\nSee you next week." // "\n" is a special character which represents a new line.
println(message)
Run the program. The text that follows \n appears on a new line in the console:
End of the program
See you next week.
Here’s how the same message can be written as a multiline string:
val message = """
End of the program!
See you next week.
"""
println(message)
Run the program. The text appears exactly as written:
End of the program
See you next week.
Remember that good variable names alone may not always be enough to describe your code. This leads us to the next lesson: Comments.