Question #136EasyGeneral

What is String Concatenation ?

Answer

Overview

String Concatenation is the process of joining two or more strings together to form a single string.


Ways to Concatenate Strings in Dart

1. String Interpolation (Recommended in Dart)

dart
String name = 'Alice';
int age = 28;

// Use $ for variable, ${} for expressions
String result = 'Hello, $name! You are $age years old.';
print(result); // Hello, Alice! You are 28 years old.

// Expression inside ${}
String info = 'Next year you will be ${age + 1}';

2. + Operator

dart
String first = 'Hello';
String second = ' World';
String result = first + second;
print(result); // Hello World

String greeting = 'Hi ' + 'there' + '!';
print(greeting); // Hi there!

3. Adjacent String Literals (Compile-time)

dart
// Dart automatically joins adjacent string literals at compile time
String message = 'Hello '
    'World '
    'from Dart!';
print(message); // Hello World from Dart!

4. StringBuffer (For Many Concatenations — Efficient)

dart
// ❌ Bad for large loops — creates many intermediate strings
String result = '';
for (int i = 0; i < 1000; i++) {
  result += 'item$i '; // O(n²) — slow!
}

// ✅ Good — StringBuffer internally uses a buffer
final buffer = StringBuffer();
for (int i = 0; i < 1000; i++) {
  buffer.write('item$i ');
}
String result2 = buffer.toString(); // Convert once at end

5. join() for Lists

dart
final words = ['Flutter', 'is', 'awesome'];
final sentence = words.join(' ');
print(sentence); // Flutter is awesome

final csv = ['Alice', 'Bob', 'Charlie'].join(', ');
print(csv); // Alice, Bob, Charlie

Performance Comparison

MethodUse CasePerformance
text
'$var'
interpolation
General use✅ Efficient
text
+
operator
Few stringsOK
Adjacent literalsCompile-time constants✅ Best (compile-time)
text
StringBuffer
Loops / many strings✅ Best for loops
text
join()
Lists of strings✅ Clean and efficient

Type Conversion Before Concatenation

dart
int number = 42;
double price = 9.99;

// Must convert to String first
String result1 = 'Number: ${number.toString()}';
String result2 = 'Price: ${price.toStringAsFixed(2)}';
String result3 = 'Total: $number items'; // Dart interpolation handles this

// ❌ This won't work with +
// String s = 'Value: ' + 42; // Error — int can't be added to String
String s = 'Value: ' + 42.toString(); // ✅ Explicit toString()

Dart Best Practice: Use string interpolation (

text
'$variable'
) for clarity and performance. Use StringBuffer in loops or when building large strings dynamically.