The String Type
Learn how to create and concatenate Strings in Java, and understand why String is not a primitive type.
Overview
Key Points
- •String is a class, not a primitive - it starts with a capital S
- •String values are immutable: "changing" a string creates a new String object
- •Use double quotes for Strings: "hello". Single quotes create a char: 'h'
- •Concatenation with + joins strings: "Hello" + " " + "World" = "Hello World"
- •Concatenating a String with any other type auto-converts it: "Score: " + 95 = "Score: 95"
- •String.length() returns the number of characters; an empty String "" has length 0
Examples
Creating and concatenating Strings
public class Main {
public static void main(String[] args) {
String firstName = "Alice";
String lastName = "Smith";
// Concatenation with +
String fullName = firstName + " " + lastName;
System.out.println(fullName); // Alice Smith
// Concatenate with other types
int age = 28;
System.out.println(fullName + " is " + age); // Alice Smith is 28
// length
System.out.println(firstName.length()); // 5
}
}The + operator is overloaded for Strings. When one operand is a String, the other is converted to text.
String is immutable - operations return new Strings
public class Main {
public static void main(String[] args) {
String original = "hello";
String upper = original.toUpperCase();
System.out.println(original); // hello (unchanged)
System.out.println(upper); // HELLO (new String)
// += looks like mutation but creates a new String
String s = "Java";
s += " is great";
System.out.println(s); // Java is great
}
}original is not changed by toUpperCase(). A new String "HELLO" is returned.
Useful String features
String msg = " Hello, World! ";
System.out.println(msg.length()); // 18
System.out.println(msg.trim()); // "Hello, World!"
System.out.println(msg.trim().length()); // 13
System.out.println("hello".toUpperCase()); // HELLO
System.out.println("HELLO".toLowerCase()); // hello
System.out.println("Java".charAt(0)); // J
// Text block (Java 15+) for multi-line strings
String json = """
{
"name": "Alice"
}
""";
System.out.println(json);Text blocks (triple-double-quotes) make multi-line strings much cleaner.
Common Mistakes
- Comparing Strings with == instead of .equals(): == compares object references, not content
- Confusing empty string "" (length 0) with null (no object at all) - null.length() throws NullPointerException
- Forgetting that Strings are objects: `String s;` (declared but null) will crash when you call s.length()
Note
Always use .equals() to compare String content: `name.equals("Alice")`. The == operator checks whether two variables point to the exact same object in memory, which is not what you usually want.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4