Strings in Java
Learn how Java represents text using String, how strings are created and compared, and how to use common String methods efficiently.
What is a String?
A String represents a sequence of characters.
In Java, String is a class provided by the
java.lang package.
Strings are objects, even though Java provides special syntax for creating them using string literals.
String name = "CIIT";
System.out.println(name);
Creating Strings
Strings are commonly created using string literals.
String language = "Java";
String message = "Welcome CIIT world 🌍..!";
A String can also be explicitly created using the constructor, although literals are normally preferred.
String text = new String("Java");
String Immutability
Strings in Java are immutable. Once a String object is created, its character contents cannot be changed.
String text = "CIIT";
text = text + " Institute";
System.out.println(text);
The original String object is not modified. A new String object is created for the concatenated result, and the variable is updated to reference it.
String Pool
Java maintains a special pool for string literals. Identical literals can share the same pooled String object.
String first = "CIIT";
String second = "Institute";
System.out.println(first == second);
true
The == comparison here checks whether the two
variables refer to the same object.
Comparing Strings with equals()
Use equals() when you want to compare String
contents.
String first = "CIIT";
String second = new String("Institute");
System.out.println(first.equals(second));
true
Case-Insensitive Comparison
String first = "ciit";
String second = "INSTITUTE";
System.out.println(
first.equalsIgnoreCase(second)
);
true
String length()
The length() method returns the number of UTF-16
code units in the String.
String text = "CIIT";
System.out.println(text.length());
4
charAt()
The charAt() method returns the character at a
specified zero-based index.
String text = "Java";
System.out.println(text.charAt(0));
System.out.println(text.charAt(2));
J
v
substring()
The substring() method extracts part of a String.
The ending index is exclusive.
String text = "Programming";
System.out.println(
text.substring(0, 4)
);
System.out.println(
text.substring(4)
);
Prog
ramming
contains()
String text = "Java Programming";
System.out.println(
text.contains("Java")
);
System.out.println(
text.contains("Python")
);
true
false
startsWith() and endsWith()
String file = "report.pdf";
System.out.println(
file.startsWith("report")
);
System.out.println(
file.endsWith(".pdf")
);
true
true
indexOf() and lastIndexOf()
String text = "Java Programming";
System.out.println(
text.indexOf("a")
);
System.out.println(
text.lastIndexOf("a")
);
replace()
Since Strings are immutable, replace() returns a
new String instead of modifying the original.
String text = "Java is easy";
String updated =
text.replace("easy", "powerful");
System.out.println(updated);
Java is powerful
toLowerCase() and toUpperCase()
String text = "Java Programming";
System.out.println(
text.toLowerCase()
);
System.out.println(
text.toUpperCase()
);
java programming
JAVA PROGRAMMING
trim() and strip()
trim() removes certain leading and trailing
characters with code points at or below U+0020.
Modern Java also provides strip(), which uses
Unicode-aware whitespace rules.
String text = " Java ";
System.out.println(
text.trim()
);
System.out.println(
text.strip()
);
String Concatenation
Strings can be combined using the + operator.
String firstName = "Samadhan";
String lastName = "Patole";
String fullName =
firstName + " " + lastName;
System.out.println(fullName);
concat()
String first = "CIIT";
String second = " Institute";
String result = first.concat(second);
System.out.println(result);
split()
The split() method divides a String according to
a regular expression.
String languages =
"Java,Python,CSharp";
String[] values =
languages.split(",");
for (String value : values) {
System.out.println(value);
}
Java
Python
CSharp
String.join()
String.join() can combine multiple strings using
a delimiter.
String result = String.join(
", ",
"Java",
"Python",
"CSharp"
);
System.out.println(result);
Java, Python, CSharp
String Formatting
String.format() creates formatted text using
placeholders.
String name = "Amit";
int age = 25;
String result = String.format(
"Name: %s, Age: %d",
name,
age
);
System.out.println(result);
Name: Amit, Age: 25
Text Blocks
Modern Java supports text blocks for convenient representation of multiline text.
String message = """
Hello
Welcome to Java
Programming
""";
StringBuilder
When text needs to be modified repeatedly, use
StringBuilder instead of creating many temporary
String objects.
StringBuilder builder =
new StringBuilder();
builder.append("Java");
builder.append(" ");
builder.append("Programming");
System.out.println(
builder.toString()
);
Java Programming
StringBuffer
StringBuffer is another mutable character
sequence. Its methods are synchronized, making it different
from StringBuilder.
StringBuffer buffer =
new StringBuffer("Java");
buffer.append(" Programming");
System.out.println(buffer);
String vs StringBuilder vs StringBuffer
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Typical Use | Fixed text | Repeated text modification | Mutable text with synchronized methods |
| Synchronization | Immutable | No | Yes |
| Performance | Good for immutable values | Usually preferred for local mutable building | More overhead than StringBuilder |
Checking Empty and Blank Strings
String text = "";
System.out.println(text.isEmpty());
String value = " ";
System.out.println(value.isBlank());
true
true
isEmpty() checks whether the String has zero
characters. isBlank() also considers strings
containing only whitespace to be blank.
String and null
A String variable can contain null, meaning it
does not currently reference a String object.
String text = null;
if (text != null) {
System.out.println(text.length());
}
length() on a
null reference causes NullPointerException.
String and Unicode
Java Strings use UTF-16 internally. Characters outside the
Basic Multilingual Plane may require a surrogate pair, so
char is not always equivalent to one Unicode
code point.
String text = "Hello";
System.out.println(
text.codePointAt(0)
);
Example: Username Validation
String username = " Sam2210 ";
username = username.strip();
if (!username.isBlank()
&& username.length() >= 5) {
System.out.println(
"Valid username"
);
} else {
System.out.println(
"Invalid username"
);
}
String Best Practices
-
Use
equals()for content comparison. -
Avoid using
==when your intention is to compare String contents. - Remember that Strings are immutable.
-
Use
StringBuilderfor repeated local string modifications. -
Handle possible
nullreferences safely. -
Use
strip()when Unicode-aware whitespace handling is desired.
Interview Questions
== compares
references, while equals() is used
to compare logical content when the class
implements it appropriately.
isEmpty() checks for zero length,
while isBlank() also considers a
string containing only whitespace to be blank.
Summary
Java Strings are immutable objects used to represent text.
Important concepts include string literals, the String
pool, content comparison with equals(),
common String methods, Unicode handling, and mutable
alternatives such as StringBuilder and
StringBuffer.