Nearby lessons

110 of 125

Java - String Methods

📌 What You Will Learn
  • Why String objects are immutable
  • String vs StringBuffer vs StringBuilder
  • The most important methods of String
  • == vs equals() — the classic interview question
  • How to split, join and manipulate text

String Methods is a core concept of the Java language. This lesson explains Most Important String Methods, == vs equals() — The Five-Object Version and uick Practice Questions with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Most Important String Methods

These are the methods you will use again and again. Learn them by heart:

MethodWhat it doesExample
length()Number of characters"Java".length() -> 4
charAt(i)Character at index i"Java".charAt(1) -> 'a'
toUpperCase() / toLowerCase()Change case"Java".toUpperCase() -> "JAVA"
trim()Remove leading/trailing spaces" hi ".trim() -> "hi"
substring(a, b)Part of string from index a to b-1"Program".substring(3) -> "gram"
replace(a, b)Replace all a with b"a-b".replace("-","") -> "ab"
equals(str)Compare content (case sensitive)"a".equals("a") -> true
equalsIgnoreCase(str)Compare ignoring case"JAVA".equalsIgnoreCase("java") -> true
contains(str)Does it contain the text?"Core Java".contains("Java") -> true
startsWith(s) / endsWith(s)Check beginning/ending"Demo.java".endsWith(".java") -> true
indexOf(ch)First position of the character"Java".indexOf('a') -> 1
split(regex)Break into parts"a,b,c".split(",") -> ["a","b","c"]
toCharArray()Convert to char array"Hi".toCharArray() -> ['H','i']
Example01
Loading editor…

== vs equals() — The Five-Object Version

The classic material proves the rule with five comparisons at once. Predict the output before reading:

The lesson: for primitives use ==; for objects use equals(). String overrides equals() to compare content; your own classes must override it too (with hashCode) — see Chapter 15.

Example02
Loading editor…

Quick Practice Questions

Example03
Loading editor…
📝 Key Takeaways
  • String is a class, not a primitive; it is immutable.
  • Immutability gives security, thread safety and pool caching.
  • Use StringBuilder (fastest, not thread-safe) or StringBuffer (thread-safe) when text changes often.
  • == compares references; .equals() compares content. Always use .equals() for Strings.
  • Override toString() to print objects meaningfully.
  • Text blocks (Java 15+) make multi-line strings clean.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.