Fatskills
Practice. Master. Repeat.
Study Guide: Java: Strings - Common String Methods, length, charAt, substring, indexOf, equals, compareTo
Source: https://www.fatskills.com/surgery/chapter/java-strings-common-string-methods-length-charat-substring-indexof-equals-compareto

Java: Strings - Common String Methods, length, charAt, substring, indexOf, equals, compareTo

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~5 min read

What This Is and Why It Matters

Mastering common string methods in Java is crucial for effective text manipulation and data processing. These methods—length(), charAt(), substring(), indexOf(), equals(), and compareTo()—are fundamental for tasks ranging from simple text parsing to complex data validation. Misunderstanding these methods can lead to errors in data handling, such as incorrect string comparisons or improper substring extraction, which can compromise application functionality. For instance, incorrectly using equals() instead of == for string comparison can result in logical errors that are hard to detect.

Core Knowledge (What You Must Internalize)

  • String Methods: Key operations for manipulating and analyzing strings.
  • length(): Returns the number of characters in a string. (Why this matters: Essential for looping through strings and validating input length.)
  • charAt(int index): Returns the character at the specified index. (Why this matters: Useful for accessing individual characters in a string.)
  • substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string. (Why this matters: Critical for extracting parts of a string.)
  • indexOf(String sub): Returns the index within this string of the first occurrence of the specified substring. (Why this matters: Helps in finding the position of a substring within a string.)
  • equals(Object anObject): Compares this string to the specified object. (Why this matters: Correct way to compare string contents.)
  • compareTo(String anotherString): Lexicographically compares two strings. (Why this matters: Useful for sorting strings.)

Step?by?Step Deep Dive

  1. Determine String Length
  2. Use length() to get the number of characters in a string.
  3. Underlying Principle: Strings are arrays of characters.
  4. Example: String str = "Hello"; int len = str.length(); // len is 5
  5. Common Pitfall: Confusing length() with array length property.

  6. Access Individual Characters

  7. Use charAt(int index) to get a character at a specific position.
  8. Underlying Principle: Strings are zero-indexed.
  9. Example: char ch = str.charAt(1); // ch is 'e'
  10. Common Pitfall: Accessing an index out of bounds.

  11. Extract Substrings

  12. Use substring(int beginIndex, int endIndex) to get a part of the string.
  13. Underlying Principle: The end index is exclusive.
  14. Example: String sub = str.substring(1, 4); // sub is "ell"
  15. Common Pitfall: Misunderstanding the exclusivity of the end index.

  16. Find Substring Position

  17. Use indexOf(String sub) to find the first occurrence of a substring.
  18. Underlying Principle: Returns -1 if the substring is not found.
  19. Example: int pos = str.indexOf("ell"); // pos is 1
  20. Common Pitfall: Not checking for -1 return value.

  21. Compare String Contents

  22. Use equals(Object anObject) to compare string contents.
  23. Underlying Principle: equals() checks for value equality.
  24. Example: boolean isEqual = str.equals("Hello"); // isEqual is true
  25. Common Pitfall: Using == for string comparison.

  26. Lexicographically Compare Strings

  27. Use compareTo(String anotherString) to compare strings lexicographically.
  28. Underlying Principle: Returns 0 if equal, negative if less, positive if greater.
  29. Example: int result = str.compareTo("World"); // result is negative
  30. Common Pitfall: Misinterpreting the return values.

How Experts Think About This Topic

Experts view string methods as tools for efficient text processing. They understand the nuances of each method and apply them contextually. Instead of memorizing method signatures, they think in terms of string manipulation patterns and how these methods fit into larger algorithms.

Common Mistakes (Even Smart People Make)

  1. The mistake: Using == for string comparison.
  2. Why it's wrong: == checks for reference equality, not value equality.
  3. How to avoid: Always use equals() for string comparison.
  4. Exam trap: Questions that trick you into using ==.

  5. The mistake: Accessing an out-of-bounds index with charAt().

  6. Why it's wrong: Causes StringIndexOutOfBoundsException.
  7. How to avoid: Always check the index is within bounds.
  8. Exam trap: Questions with edge cases near string boundaries.

  9. The mistake: Misunderstanding substring() end index.

  10. Why it's wrong: End index is exclusive, not inclusive.
  11. How to avoid: Remember the end index is not part of the substring.
  12. Exam trap: Questions that test your understanding of indexing.

  13. The mistake: Not checking indexOf() return value.

  14. Why it's wrong: Missing the case where the substring is not found.
  15. How to avoid: Always check if indexOf() returns -1.
  16. Exam trap: Questions that require handling missing substrings.

Practice with Real Scenarios

Scenario: You need to extract the domain name from an email address. Question: Given the email [email protected], extract the domain name. Solution:
1. Find the position of the @ symbol using indexOf().
2. Use substring() to extract the part after the @ symbol. Answer: example.com Why it works: indexOf() finds the @ symbol, and substring() extracts the domain.

Scenario: You need to compare two strings for equality. Question: Given String str1 = "Hello"; String str2 = "hello";, are they equal? Solution:
1. Use equals() to compare the strings. Answer: false Why it works: equals() is case-sensitive and compares the actual content.

Scenario: You need to sort an array of strings lexicographically. Question: Given String[] arr = {"apple", "banana", "cherry"};, sort the array. Solution:
1. Use compareTo() in a sorting algorithm. Answer: {"apple", "banana", "cherry"} Why it works: compareTo() provides the correct order for sorting.

Quick Reference Card

  • Core Rule: Use equals() for string comparison, not ==.
  • Key Formula: substring(beginIndex, endIndex) where endIndex is exclusive.
  • Critical Facts:
  • length() returns the number of characters.
  • charAt(index) accesses a character at the specified index.
  • indexOf(sub) returns the position of the substring or -1 if not found.
  • Dangerous Pitfall: Using == for string comparison.
  • Mnemonic: equals() for equality, == for reference.

If You're Stuck (Exam or Real Life)

  • What to check first: Verify string comparison methods and index bounds.
  • How to reason from first principles: Think about how strings are stored and accessed.
  • When to use estimation: Estimate string lengths and positions to avoid off-by-one errors.
  • Where to find the answer: Refer to the Java API documentation for method details.

Related Topics

  • StringBuilder: Efficient string manipulation.
  • Link: Understanding StringBuilder helps in optimizing string operations.
  • Regular Expressions: Pattern matching in strings.
  • Link: Regular expressions complement string methods for complex text processing.