Strings
String handling in Java
Introduction
In this lesson, you'll learn about strings in Java. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with string handling in java.
Java has its own approach to string handling in java, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
String s1 = "Hello";
String s2;
int len = s1.length();
s2 = s1; // reference copy
String s3 = s1 + " World"; // concatenation
int cmp = s1.compareTo(s2);
boolean eq = s1.equals(s2);
// Immutable! Creates new string
String modified = s1.replace('H', 'J');Comparing to C
Here's how you might have written similar code in C:
#include <string.h>
char s1[50] = "Hello";
char s2[50];
int len = strlen(s1);
strcpy(s2, s1);
strcat(s1, " World");
int cmp = strcmp(s1, s2);
// Mutable
s1[0] = 'J'; // "Jello World"You may be used to different syntax or behavior.
String is a class with methods
You may be used to different syntax or behavior.
Strings are immutable - operations create new strings
You may be used to different syntax or behavior.
Use .equals() for comparison, not ==
You may be used to different syntax or behavior.
Concatenation with + creates new String
Step-by-Step Breakdown
1. String is a Class
In Java, String is a full-featured class with many useful methods.
String s = "Hello World";
s.length(); // 11
s.charAt(0); // 'H'
s.substring(0, 5); // "Hello"
s.toUpperCase(); // "HELLO WORLD"
s.toLowerCase(); // "hello world"
s.trim(); // remove whitespace
s.split(" "); // ["Hello", "World"]
s.contains("World"); // true
s.startsWith("Hello"); // true2. String Comparison
Use .equals() for content comparison. == compares references!
strcmp(s1, s2) == 0// WRONG - compares references
if (s1 == s2) { ... }
// CORRECT - compares content
if (s1.equals(s2)) { ... }
// Case-insensitive
if (s1.equalsIgnoreCase(s2)) { ... }3. StringBuilder
For building strings efficiently, use StringBuilder instead of concatenation.
char result[1000] = "";
for (int i = 0; i < 100; i++) {
strcat(result, "item");
}// Inefficient - creates many String objects
String result = "";
for (int i = 0; i < 100; i++) {
result += "item"; // bad!
}
// Efficient - single buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append("item");
}
String result = sb.toString();Common Mistakes
When coming from C, developers often make these mistakes:
- String is a class with methods
- Strings are immutable - operations create new strings
- Use .equals() for comparison, not ==
Key Takeaways
- String is a class with many methods
- Strings are immutable
- Use .equals() not == for comparison
- Use StringBuilder for efficient building