String
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 8 of 93.
A Char is a single character (for example: 1, 6, %, b, p, ., T, etc.)
The String type is a special type that consists of multiple Chars.
To initialize a string value in a variable, enclose it within double quotation marks:
fun main() {
val s1 = "This is a string"
val s2 = "This is also a string"
}In the above example, two string values are initialized, named s1 and s2.
Note: In Kotlin, only double quotes " are used for Strings. Single quotes ' are used only for a single Char value:
fun main() {
val letter: Char = 'A' // single character
val word: String = "Hello" // string
}String Templates:
Kotlin has a powerful feature called string templates using $. This lets you insert values directly inside a string:
fun main() {
val name = "Alice"
val age = 25
println("My name is $name and I am $age years old.")
// My name is Alice and I am 25 years old.
}For expressions, use ${}:
fun main() {
val a = 10
val b = 5
println("The sum is ${a + b}") // The sum is 15
}Challenge
BeginnerStore the string I am learning to code with Coddy! in a value named coddy.
Be sure to store the exact string value with correct casing.
Try it yourself
fun main() {
// Type your code below
val coddy = ?
// Don't change the line below
println("coddy = \"$coddy\"")
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground