String
- Java course
- Beginner
- Lesson 9/116
- 4 min
Learn text variables with String.
What is String?
String is a reference type that holds text. It is written inside double quotes:
String name = "Alex";
String city = "London";String is a reference type: the variable holds the memory location, not the value itself. So we compare with equals rather than ==.
Strings are immutable: concatenation or trimming produces a new String, leaving the original untouched.
String is a reference type
Primitive types (int, boolean) hold the value itself. String is a reference type: the variable holds the memory location of the object.
That is why comparing two Strings with == may give wrong results. The right way is the equals method:
String a = "Hello";
String b = "Hello";
System.out.println(a.equals(b)); // trueThis topic is covered in more depth later.
Practice Define a String and print it
Write a Main class with a main method. Assign "Alex" to String name. Print it with println.
Sample solution
public class Main {
public static void main(String[] args) {
String name = "Alex";
System.out.println(name);
}
}Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Assign a value to a String variable
String name = ____;
String name = "Alex";
Explanation: A String value is written inside double quotes.
2 Match the String concepts
| Term | Meaning |
|---|---|
String |
Text type |
"Hello" |
String literal |
equals |
Comparison |
null |
Null reference |
3 Which is a valid String value?
- Hello
- 'Hello'
- "Hello" Correct answer
- `Hello`
Explanation: A String is written inside double quotes.