Strings
Published Jan 11, 2023
Contribute to Docs
Strings are immutable objects that represent a sequence of characters contained within double quotes (""
).
Syntax
val stringName: String = "string value"
In Kotlin, string values are always defined as instances of the String
class.
String Templates
Templates can also be used to dynamically produce string values. Dynamic values don’t have to start as strings, and can either be directly referenced with a dollar sign ($
) or evaluated as a string with additional curly braces ({}
).
Example
The following example showcases the various ways strings are used in Kotlin:
fun main(args: Array<String>) {// String literalsval greeting: String = "Hello, World!"println(greeting)// String templatesval dynamicValue = 4val stringOne: String = "The value of dynamicValue is $dynamicValue"System.out.println(stringOne)val a = dynamicValueval b = 5val stringTwo: String = "The sum of a and b is ${a + b}"System.out.println(stringTwo)}
The output for the above code will be:
Hello, World!The value of dynamicValue is 4The sum of a and b is 9
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.