A String is an object holding a sequence of characters. It is the most used class in Java.
String course = "Java"; // literal (stored in the string pool)
String other = new String("Java"); // new object on the heap
Common String methods#
[Vindhyaedu Java Course]
length: 22
charAt(0): V
indexOf("Java"): 11
substring(11): Java Course
substring(0, 10): Vindhyaedu
toUpperCase: VINDHYAEDU JAVA COURSE
replace: Vindhyaedu Python Course
contains Course? true
startsWith V? true, endsWith e? true
isEmpty: true, isBlank: true| Method | Returns |
|---|---|
length() |
number of characters |
charAt(i) |
the character at index i |
substring(a, b) |
characters a to b-1 |
indexOf(x) / lastIndexOf(x) |
position or -1 |
toUpperCase() / toLowerCase() |
changed copy |
trim() / strip() |
without leading/trailing spaces |
replace(a, b) |
copy with replacements |
split(regex) |
array of parts |
equals, equalsIgnoreCase, compareTo |
comparison |
String.join(sep, parts) |
joined text |
Comparing strings: equals vs ==#
true false true true -1 0
Never compare strings with ==. It may seem to work for literals (because of the string pool) and then fail for strings read from input or built at run time. Always use equals().
== यह देखता है कि दोनों variables एक ही object की ओर इशारा करते हैं या नहीं। equals() यह देखता है कि दोनों strings के अक्षर एक जैसे हैं या नहीं। User input या database से आई strings की तुलना हमेशा equals() से करें।
Immutability#
A String never changes after it is created. Methods like toUpperCase() and replace() return a new String:
asha ASHA
Immutability makes Strings safe to share between parts of a program (and between threads), and allows the JVM to reuse identical literals from the string pool.
Splitting and joining#
Roll 101 | Aarav Gupta | Bhopal | CGPA 7.06 5 words Learn-Java-step-by-step user=sneha.gupta, domain=vindhya.edu
StringBuilder - for building text efficiently#
Because Strings are immutable, s = s + x in a loop creates a new object every time. StringBuilder keeps one modifiable buffer:
1, 2, 3, 4, 5 Numbers: 1, 2, 3, 4, 5 racecar Java 21 (length 7)
Character-level processing#
letters=20 digits=4 spaces=4 others=2 Madam palindrome? true
Formatting text#
[Notebook 3 135.00] Name : Kavya Marks: 96
Summary#
- Strings are immutable objects; methods return new Strings.
- Compare with
equals/equalsIgnoreCase/compareTo- never==. split,substring,indexOf,replace,trim,String.joincover most text tasks.- Use
StringBuilderwhen building text in loops;String.format/formattedfor layout.