Skip to main content

How to declare a string variable in Kotlin

How to declare a string variable in Kotlin.

Here's a step-by-step tutorial on how to declare a string variable in Kotlin:

Step 1: Open your preferred Integrated Development Environment (IDE) and create a new Kotlin project.

Step 2: In Kotlin, you can declare a string variable using the var or val keyword followed by the variable name. The var keyword is used to declare a mutable string variable, which means its value can be changed. The val keyword is used to declare an immutable string variable, which means its value cannot be changed once it is assigned.

Let's start with declaring a mutable string variable:

var message: String

In the above example, we declared a mutable string variable named message without assigning any initial value.

Step 3: To assign a value to the string variable, you can use the assignment operator (=) followed by the value you want to assign. The value should be enclosed within double quotes (").

message = "Hello, Kotlin!"

In the above example, we assigned the string "Hello, Kotlin!" to the message variable.

Step 4: You can also declare and assign a value to a string variable in a single line:

var message: String = "Hello, Kotlin!"

This declaration assigns the string value "Hello, Kotlin!" to the message variable at the same time.

Step 5: Now, let's move on to declaring an immutable string variable using the val keyword:

val greeting: String = "Welcome to Kotlin!"

In the above example, we declared an immutable string variable named greeting and assigned the string value "Welcome to Kotlin!" to it. Since greeting is immutable, its value cannot be changed once assigned.

Step 6: You can also omit the variable type if it can be inferred from the assigned value:

val name = "John"

In the above example, we declared an immutable string variable named name and assigned the string value "John" to it. The Kotlin compiler infers that the variable type is String based on the assigned value.

Step 7: You can concatenate or combine multiple strings using the + operator:

val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName

In the above example, we declared three immutable string variables: firstName, lastName, and fullName. We concatenated the firstName, a space, and the lastName using the + operator to create the fullName.

That's it! You have successfully learned how to declare a string variable in Kotlin. Remember that mutable variables are declared using the var keyword, while immutable variables are declared using the val keyword. You can assign values to these variables using the assignment operator (=) and manipulate strings using various operators and functions available in Kotlin.