Definition
📌 Strings
Java's String class represents text and comes with a rich set of built-in methods.
Syntax
syntax
String name = "text";
name.length();
name.toUpperCase();
name.equals(other);Example
java
public class Main {
public static void main(String[] args) {
String name = "CodeyHub";
System.out.println("Name: " + name);
System.out.println("Length: " + name.length());
System.out.println("Upper: " + name.toUpperCase());
}
}Output
outputName: CodeyHub
Length: 8
Upper: CODEYHUB
Important Points
- Java
Stringobjects are immutable — methods return new strings rather than modifying in place. - Use
.equals(), not==, to compare string content. StringBuilderis the efficient choice for building strings in a loop, since it's mutable.- Common methods:
.length(),.substring(),.indexOf(),.split().
Common Mistakes
- Comparing strings with
==instead of.equals(). - Concatenating strings with
+repeatedly inside a large loop instead of usingStringBuilder. - Forgetting that string methods don't change the original string — you must capture the returned value.
Interview Tip
🎯 Before your interview
"Why are Java strings immutable?" is a classic question — it enables safe string sharing/caching and makes strings safe to use as hash keys.
