⚡0 XP🔥0

Strings and StringBuilder

Lesson 8 of 15 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Java

String methods (length, charAt, substring, indexOf, split, replace, toUpperCase...), comparing strings with equals, immutability, the string pool, StringBuilder and text formatting.

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#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
[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 ==#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
true
false
true
true
-1
0
Common Mistake

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:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
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#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
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:

▶ Try it YourselfJava
Ctrl + Enter to run
Output
1, 2, 3, 4, 5
Numbers: 1, 2, 3, 4, 5
racecar
Java 21 (length 7)

Character-level processing#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
letters=20 digits=4 spaces=4 others=2
Madam palindrome? true

Formatting text#

▶ Try it YourselfJava
Ctrl + Enter to run
Output
[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.join cover most text tasks.
  • Use StringBuilder when building text in loops; String.format / formatted for layout.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Count words and capitalise

Read a line, then print the number of words and the line with every word capitalised (first letter upper case, rest lower case):

Words: 5
Java Is Fun At Vindhyaedu
Test input:
jAVA is fun   at VINDHYAEDU
Expected output:
Words: 5
Java Is Fun At Vindhyaedu
2

Anagram check

Read two words and print listen and silent are anagrams or ... are not anagrams (ignore case). Sort the characters of both and compare.

Test input:
Listen Silent
Expected output:
listen and silent are anagrams

Quick Quiz

Q1.

How should you compare the contents of two Strings?

Q2.

What is "Vindhyaedu".substring(3, 6)?

Q3.

Strings in Java are immutable. That means...

Q4.

Why use StringBuilder in a loop that adds characters?

Q5.

"a,b,,c".split(",") has how many elements?