Popular Searches
Popular Course Categories
Popular Courses

Working with String Methods and Comparisons

Working with String Methods and Comparisons

Strings and String Manipulation

Working with String Methods and Comparisons in Java

Course: Core Java Training

Topic: Working with String Methods and Comparisons

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to String Methods in Java

Strings are one of the most frequently used data types in Java programming. They represent text such as names, addresses, messages, passwords, product descriptions, file paths, and user input. Java provides the built-in String class in the java.lang package to perform operations on textual data.

The String class includes methods for checking string length, accessing characters, searching for text, extracting substrings, replacing characters, changing letter case, removing surrounding whitespace, and comparing strings.

String objects are immutable, which means their contents cannot be changed after creation. Methods that transform a string generally return a new string instead of modifying the original object.

Example

public class StringIntroduction {
    public static void main(String[] args) {
        String message = "Hello Java";

        System.out.println(message.length());
        System.out.println(message.toUpperCase());
        System.out.println(message);

    }
}

Output:

10
HELLO JAVA
Hello Java

The length() method returns the number of UTF-16 code units in the string, and toUpperCase() returns an uppercase version. The original string remains unchanged.

2. Learning Objectives

After studying this topic, you should be able to:

  • Understand the purpose of commonly used String methods.
  • Find the length of a string and access individual characters.
  • Convert strings to uppercase and lowercase.
  • Remove surrounding whitespace and check for empty strings.
  • Search for characters and substrings.
  • Extract parts of a string using substring methods.
  • Replace text and combine strings.
  • Compare string contents using equals() and equalsIgnoreCase().
  • Compare strings lexicographically using compareTo().
  • Recognize the difference between reference comparison and content comparison.
  • Apply string methods to practical programming problems.

3. Understanding String Immutability

Immutability is an important property of the Java String class. Once a String object is created, its character sequence cannot be modified. A method that appears to change the text produces a result that can be stored in another variable or assigned back to the original reference.

Example

public class StringImmutability {
    public static void main(String[] args) {
        String language = "java";

        language.toUpperCase();
        System.out.println(language);

        language = language.toUpperCase();
        System.out.println(language);
    }
}

Output:

java
JAVA

In the first operation, the returned uppercase string is not saved. In the second operation, the result is assigned to language, so the variable refers to the uppercase string.

4. The length() Method

The length() method returns the length of a string as an integer. It is useful for validating input, determining text size, and controlling loops that process characters.

Syntax

stringName.length();

Example

public class StringLengthExample {
    public static void main(String[] args) {
        String name = "Programming";
        String city = "Mumbai";

        System.out.println(name.length());
        System.out.println(city.length());
    }
}

Output:

11
6

Important: The length() method counts UTF-16 code units, not necessarily user-perceived characters. Some Unicode characters, such as many emoji, use two code units.

5. The charAt() Method

The charAt() method returns the UTF-16 char value at a specified index. String indexing begins at zero.

Syntax

stringName.charAt(index);

Example

public class CharAtExample {
    public static void main(String[] args) {
        String language = "Java";

        System.out.println(language.charAt(0));
        System.out.println(language.charAt(1));
        System.out.println(language.charAt(3));
    }
}

Output:

J
a
a

Valid indexes range from 0 to length() - 1. An invalid index causes a StringIndexOutOfBoundsException.

6. Converting Strings to Uppercase and Lowercase

The String class provides toUpperCase() and toLowerCase() methods to convert text to uppercase or lowercase. These methods return new strings and do not modify the original object.

Example

public class CaseConversionExample {
    public static void main(String[] args) {
        String course = "Core Java Training";

        System.out.println(course.toUpperCase());
        System.out.println(course.toLowerCase());
    }
}

Output:

CORE JAVA TRAINING
core java training

Common Uses

  • Normalizing user input for comparisons.
  • Displaying text in a consistent format.
  • Processing case-insensitive identifiers where appropriate.
  • Preparing text for searches that should ignore letter case.

For language-sensitive text conversion, consider using methods that accept a specific Locale. The default-locale versions may behave differently for certain languages.

7. The trim() and strip() Methods

Java provides methods for removing whitespace from the beginning and end of a string.

  • trim() removes leading and trailing characters whose values are at or below the traditional ASCII space range.
  • strip(), available from Java 11, removes leading and trailing Unicode whitespace as defined by Java's whitespace rules.
  • stripLeading() removes whitespace only from the beginning.
  • stripTrailing() removes whitespace only from the end.

Example

public class WhitespaceExample {
    public static void main(String[] args) {
        String text = "   Hello Java   ";

        System.out.println("Original: [" + text + "]");
        System.out.println("Trimmed: [" + text.trim() + "]");
        System.out.println("Stripped: [" + text.strip() + "]");
        System.out.println("Leading removed: [" + text.stripLeading() + "]");
        System.out.println("Trailing removed: [" + text.stripTrailing() + "]");
    }
}

Output:

Original: [   Hello Java   ]
Trimmed: [Hello Java]
Stripped: [Hello Java]
Leading removed: [Hello Java   ]
Trailing removed: [   Hello Java]

These methods are useful when processing form inputs, user names, search terms, and text copied from external sources.

8. The isEmpty() and isBlank() Methods

These methods help determine whether a string contains meaningful text.

  • isEmpty() returns true when the string length is zero.
  • isBlank(), available from Java 11, returns true when the string is empty or contains only whitespace characters recognized by Java's whitespace rules.

Example

public class EmptyBlankExample {
    public static void main(String[] args) {
        String first = "";
        String second = "   ";
        String third = "Java";

        System.out.println(first.isEmpty());
        System.out.println(second.isEmpty());
        System.out.println(second.isBlank());
        System.out.println(third.isBlank());
    }
}

Output:

true
false
true
false

Important: Neither method can be called on a null reference. Check for null first if the value might be missing.

9. The equals() Method

The equals() method compares the contents of two strings. It returns true when both strings contain the same sequence of characters and false otherwise. The comparison is case-sensitive.

Syntax

firstString.equals(secondString);

Example

public class EqualsExample {
    public static void main(String[] args) {
        String first = "Java";
        String second = "Java";
        String third = "java";

        System.out.println(first.equals(second));
        System.out.println(first.equals(third));
    }
}

Output:

true
false

The first comparison is true because the strings have identical content. The second is false because uppercase J and lowercase j are different characters.

10. The equalsIgnoreCase() Method

The equalsIgnoreCase() method compares two strings without treating ordinary uppercase and lowercase differences as unequal. It is useful for case-insensitive checks, although it is not a substitute for locale-aware linguistic comparison.

Example

public class EqualsIgnoreCaseExample {
    public static void main(String[] args) {
        String first = "JAVA";
        String second = "java";
        String third = "Python";

        System.out.println(first.equalsIgnoreCase(second));
        System.out.println(first.equalsIgnoreCase(third));
    }
}

Output:

true
false

This method is useful for checking commands, category labels, and other text where case differences should not matter.

11. Difference Between == and equals()

The == operator and equals() serve different purposes when working with String objects.

Feature == equals()
Purpose Checks whether references identify the same object Checks whether string contents are equal
Comparison type Reference identity Content equality
Case-sensitive Not a content comparison Yes
Typical use Checking object identity Checking whether two strings contain the same text

Example

public class StringReferenceComparison {
    public static void main(String[] args) {
        String first = "Java";
        String second = "Java";
        String third = new String("Java");

        System.out.println(first == second);
        System.out.println(first == third);
        System.out.println(first.equals(third));
    }
}

Output:

true
false
true

Identical string literals normally reuse the pooled literal object. The constructor call creates a distinct String object, even though its content is the same.

Best practice: Use equals() when you want to compare the contents of strings.

12. The compareTo() Method

The compareTo() method compares two strings lexicographically. It compares character values in sequence and returns an integer indicating their relative ordering.

Return Values

  • A negative integer means the calling string comes before the argument string.
  • Zero means the strings are equal according to the comparison.
  • A positive integer means the calling string comes after the argument string.

Example

public class CompareToExample {
    public static void main(String[] args) {
        String first = "Apple";
        String second = "Banana";
        String third = "Apple";

        System.out.println(first.compareTo(second));
        System.out.println(first.compareTo(third));
        System.out.println(second.compareTo(first));
    }
}

Output:

-1
0
1

For these examples, the results are respectively negative, zero, and positive. In general, do not assume that compareTo() always returns exactly -1 or 1. The important property is the sign of the returned value.

13. The compareToIgnoreCase() Method

The compareToIgnoreCase() method performs a lexicographical comparison while ignoring ordinary differences in letter case.

Example

public class CompareIgnoreCaseExample {
    public static void main(String[] args) {
        String first = "java";
        String second = "JAVA";
        String third = "Python";

        System.out.println(first.compareToIgnoreCase(second));
        System.out.println(first.compareToIgnoreCase(third));
    }
}

Output:

0
positive or negative integer

The first result is 0 because the strings compare equally when case is ignored. The exact numeric value of the second result depends on the first differing character; its sign indicates the ordering.

Note: For programs that require language-specific alphabetical sorting, use locale-aware comparison facilities such as Collator rather than assuming that Unicode character ordering matches dictionary order in every language.

14. The startsWith() and endsWith() Methods

The startsWith() method checks whether a string begins with a specified prefix. The endsWith() method checks whether it ends with a specified suffix.

Example

public class PrefixSuffixExample {
    public static void main(String[] args) {
        String filename = "report.pdf";
        String website = "https://www.justacademy.co/";

        System.out.println(filename.startsWith("report"));
        System.out.println(filename.endsWith(".pdf"));
        System.out.println(website.startsWith("https://"));
    }
}

Output:

true
true
true

Common Uses

  • Checking file extensions.
  • Identifying prefixes in product codes.
  • Checking URL schemes before further validation.
  • Testing whether a string follows a naming convention.

These methods perform simple text checks. For security-sensitive validation, such as validating URLs, additional parsing and validation may be necessary.

15. The contains() Method

The contains() method checks whether a string contains a specified character sequence. It returns a boolean value.

Example

public class ContainsExample {
    public static void main(String[] args) {
        String message = "Learn Core Java Programming";

        System.out.println(message.contains("Java"));
        System.out.println(message.contains("Python"));
        System.out.println(message.contains("Core"));
    }
}

Output:

true
false
true

The method is case-sensitive. For example, searching for "java" in "Java Programming" returns false.

16. The indexOf() and lastIndexOf() Methods

The indexOf() method returns the index of the first occurrence of a character or substring. The lastIndexOf() method returns the index of the last occurrence. Both return -1 if the requested value is not found.

Example

public class IndexSearchExample {
    public static void main(String[] args) {
        String text = "Java is easy and Java is popular";

        System.out.println(text.indexOf("Java"));
        System.out.println(text.lastIndexOf("Java"));
        System.out.println(text.indexOf("Python"));
    }
}

Output:

0
18
-1

Use Cases

  • Finding the position of a word in a message.
  • Checking whether a delimiter appears in a string.
  • Finding the last dot in a filename.
  • Locating repeated words or characters.

17. The substring() Method

The substring() method extracts part of a string and returns it as a new String value. It supports two commonly used forms.

string.substring(beginIndex);
string.substring(beginIndex, endIndex);
  • substring(beginIndex) extracts from the specified index to the end.
  • substring(beginIndex, endIndex) extracts from the beginning index up to, but not including, the ending index.

Example

public class SubstringExample {
    public static void main(String[] args) {
        String language = "Programming";

        System.out.println(language.substring(3));
        System.out.println(language.substring(0, 7));
    }
}

Output:

gramming
Program

For a two-argument call, the starting index must be non-negative and no greater than the ending index, and the ending index must not exceed the string length. Invalid ranges cause an index-related exception.

18. The replace() Method

The replace() method creates a string in which matching characters or literal character sequences are replaced with new values. It does not modify the original string.

Example: Replacing Characters

public class ReplaceCharacterExample {
    public static void main(String[] args) {
        String text = "banana";

        String result = text.replace('a', 'o');

        System.out.println(result);
        System.out.println(text);
    }
}

Output:

bonono
banana

Example: Replacing Text

public class ReplaceTextExample {
    public static void main(String[] args) {
        String message = "I like Python";

        String result = message.replace("Python", "Java");

        System.out.println(result);
    }
}

Output:

I like Java

19. The replaceFirst() and replaceAll() Methods

Java also provides replaceFirst() and replaceAll(), which use regular expressions to identify matching text.

  • replaceFirst(regex, replacement) replaces the first match of the regular expression.
  • replaceAll(regex, replacement) replaces every match of the regular expression.

Example

public class RegexReplacementExample {
    public static void main(String[] args) {
        String text = "cat dog cat dog";

        System.out.println(text.replaceFirst("cat", "fox"));
        System.out.println(text.replaceAll("cat", "fox"));
    }
}

Output:

fox dog cat dog
fox dog fox dog

Remember that the first argument is a regular expression, not necessarily a literal string. Characters such as a dot have special meanings in regular expressions. Use replace() when you want straightforward literal replacement.

20. The concat() Method

The concat() method appends one string to the end of another and returns the combined result.

Example

public class ConcatExample {
    public static void main(String[] args) {
        String first = "Core";
        String second = " Java";

        String result = first.concat(second);

        System.out.println(result);
    }
}

Output:

Core Java

The concatenation operator + is another common way to combine strings. For simple expressions, both approaches are readable. For repeated modifications in a loop, consider StringBuilder.

21. The split() Method

The split() method divides a string into an array of strings using a regular expression as the delimiter. It is commonly used to process comma-separated values, words, and structured text.

Example

import java.util.Arrays;

public class SplitExample {
    public static void main(String[] args) {
        String languages = "Java,Python,JavaScript";

        String[] items = languages.split(",");

        System.out.println(Arrays.toString(items));
    }
}

Output:

[Java, Python, JavaScript]

The delimiter is a regular expression. If the delimiter contains special regex characters, such as a dot, escape it appropriately. The two-argument form also allows control over the number of splits and how trailing empty results are handled.

22. The join() Method

The static String.join() method combines multiple character sequences using a specified delimiter. It is useful for formatting lists into a single string.

Example

public class JoinExample {
    public static void main(String[] args) {
        String result = String.join(" | ", "Java", "Python", "SQL");

        System.out.println(result);
    }
}

Output:

Java | Python | SQL

The delimiter is placed between the supplied elements, not automatically at the beginning or end.

23. The valueOf() Method

The static String.valueOf() method converts supported values into their string representation. It is useful when working with numbers, booleans, characters, and other data types.

Example

public class ValueOfExample {
    public static void main(String[] args) {
        int age = 25;
        double salary = 45000.50;
        boolean active = true;

        String ageText = String.valueOf(age);
        String salaryText = String.valueOf(salary);
        String activeText = String.valueOf(active);

        System.out.println(ageText);
        System.out.println(salaryText);
        System.out.println(activeText);
    }
}

Output:

25
45000.5
true

Conversion produces text, not a numeric value. If you need to perform arithmetic later, retain the numeric value or parse the string back into an appropriate number type.

24. The matches() Method

The matches() method checks whether the entire string matches a specified regular expression. It returns true or false.

Example

public class MatchesExample {
    public static void main(String[] args) {
        String digits = "12345";
        String letters = "Java";

        System.out.println(digits.matches("[0-9]+"));
        System.out.println(letters.matches("[A-Za-z]+"));
        System.out.println(digits.matches("[0-9]{3}"));
    }
}

Output:

true
true
false

The expression [0-9]+ matches one or more digits. The expression [A-Za-z]+ matches one or more basic English letters. The expression [0-9]{3} requires exactly three digits, so it does not match the five-digit string.

Regular expressions are useful for basic input checks, but complex validation, such as email addresses or international phone numbers, may require more careful rules.

25. Common String Methods Reference Table

Method Purpose Example
length() Returns the number of UTF-16 code units "Java".length()
charAt() Returns a character value at an index "Java".charAt(0)
toUpperCase() Returns uppercase text "java".toUpperCase()
toLowerCase() Returns lowercase text "JAVA".toLowerCase()
trim() Removes traditional leading and trailing whitespace " Java ".trim()
strip() Removes leading and trailing Unicode whitespace " Java ".strip()
isEmpty() Checks whether length is zero "".isEmpty()
isBlank() Checks whether text is empty or whitespace-only " ".isBlank()
equals() Compares string contents exactly a.equals(b)
equalsIgnoreCase() Compares contents while ignoring case a.equalsIgnoreCase(b)
compareTo() Compares strings lexicographically a.compareTo(b)
startsWith() Checks the beginning of a string name.startsWith("A")
endsWith() Checks the end of a string file.endsWith(".txt")
contains() Checks for a character sequence text.contains("Java")
indexOf() Finds the first occurrence text.indexOf("a")
lastIndexOf() Finds the last occurrence text.lastIndexOf("a")
substring() Extracts a section of text text.substring(0, 3)
replace() Replaces literal characters or sequences text.replace("Java", "SQL")
replaceAll() Replaces all regex matches text.replaceAll("[0-9]", "")
split() Splits text into an array text.split(",")
String.join() Joins values with a delimiter String.join("-", "A", "B")
String.valueOf() Converts supported values to text String.valueOf(100)
matches() Checks whether the whole string matches a regex text.matches("[A-Z]+")

26. Handling Null Strings Safely

A String variable may contain null if it has not been assigned an object or if null was explicitly assigned. Calling a String method on a null reference causes a NullPointerException.

Incorrect Example

String name = null;
System.out.println(name.length());

This code throws a NullPointerException.

Safer Example

public class NullStringExample {
    public static void main(String[] args) {
        String name = null;

        if (name != null && !name.isBlank()) {
            System.out.println(name);
        } else {
            System.out.println("Name is missing or blank.");
        }
    }
}

Output:

Name is missing or blank.

The condition checks for null before invoking isBlank(). Because Java evaluates the && operator from left to right and short-circuits when the first condition is false, the method is not called on a null reference.

27. Practical Example: Validating a Username

This example combines trimming, length checking, and string comparison to demonstrate basic username validation.

public class UsernameValidation {
    public static void main(String[] args) {
        String username = "  Rahul123  ";

        if (username != null) {
            username = username.strip();

            if (username.isEmpty()) {
                System.out.println("Username cannot be empty.");
            } else if (username.length() < 5) {
                System.out.println("Username must contain at least 5 characters.");
            } else if (username.equalsIgnoreCase("admin")) {
                System.out.println("This username is reserved.");
            } else {
                System.out.println("Username accepted: " + username);
            }
        } else {
            System.out.println("Username is missing.");
        }
    }
}

Output:

Username accepted: Rahul123

This is a simple educational example. Real applications should also define allowed characters, uniqueness rules, and other account requirements.

28. Practical Example: Comparing Course Names

The following program demonstrates exact comparison, case-insensitive comparison, and searching for a keyword.

public class CourseComparison {
    public static void main(String[] args) {
        String selectedCourse = "Core Java";
        String enteredCourse = "core java";

        if (selectedCourse.equals(enteredCourse)) {
            System.out.println("Exact course match.");
        } else if (selectedCourse.equalsIgnoreCase(enteredCourse)) {
            System.out.println("Course matches when ignoring case.");
        } else {
            System.out.println("Course does not match.");
        }

        if (selectedCourse.contains("Java")) {
            System.out.println("Course includes Java.");
        }
    }
}

Output:

Course matches when ignoring case.
Course includes Java.

29. Practical Example: Formatting a Full Name

String methods can help clean and format text entered by a user.

public class FullNameFormatter {
    public static void main(String[] args) {
        String firstName = "  priya ";
        String lastName = " sharma  ";

        String first = firstName.strip();
        String last = lastName.strip();

        String fullName = first.substring(0, 1).toUpperCase()
                + first.substring(1).toLowerCase()
                + " "
                + last.substring(0, 1).toUpperCase()
                + last.substring(1).toLowerCase();

        System.out.println(fullName);
    }
}

Output:

Priya Sharma

This example assumes that both names contain at least one character after trimming. In production code, validate empty values before calling substring().

30. Troubleshooting Common String Problems

Problem Possible Cause Solution
Unexpected comparison result Using == to compare contents Use equals() for content comparison
NullPointerException Calling a method on a null reference Check the reference before invoking methods
String does not change Ignoring the returned value of a transformation Assign the result to a variable
StringIndexOutOfBoundsException Using an invalid index or substring range Check the length and index boundaries
Search returns false Case-sensitive matching or unexpected whitespace Check case requirements and normalize input when appropriate
replaceAll() gives unexpected output Using regex syntax as though it were literal text Use replace() for literal replacement or escape regex metacharacters
split() returns unexpected parts Incorrect delimiter expression Review the regex and consider the limit argument
Incorrect text ordering Assuming Unicode order is identical to dictionary order Use locale-aware comparison when appropriate

31. Best Practices for String Methods and Comparisons

  • Use equals() to compare string contents and == only when reference identity is intended.
  • Use equalsIgnoreCase() when a case-insensitive comparison is appropriate.
  • Use compareTo() to determine lexicographical ordering rather than attempting to use numeric comparison operators on strings.
  • Check for null before invoking methods on values that may be missing.
  • Validate indexes and substring boundaries to avoid runtime exceptions.
  • Remember that most string transformation methods return new strings.
  • Use strip() when Unicode-aware whitespace removal is needed and the project targets Java 11 or later.
  • Use replace() for literal replacement and regex-based methods only when regular expressions are needed.
  • Use a suitable locale for language-sensitive case conversion and sorting.
  • Use StringBuilder for many repeated modifications in performance-sensitive loops.
  • Choose descriptive variable names and write small methods for repeated validation logic.

32. Practice Exercises

Exercise 1: String Length

  • Create a string containing your favorite programming language.
  • Print its length.
  • Print the first and last character after checking that the string is not empty.

Exercise 2: Case Conversion

  • Create a string containing your full name.
  • Print it in uppercase and lowercase.
  • Explain why the original string does not change.

Exercise 3: String Comparison

  • Create two strings containing the same text with different letter case.
  • Compare them using equals() and equalsIgnoreCase().
  • Explain the difference between their results.

Exercise 4: Search and Extract

  • Create a string containing a sentence about Java programming.
  • Search for the word "Java" using indexOf().
  • Extract a portion using substring().

Exercise 5: Replace and Split

  • Create a comma-separated list of programming languages.
  • Replace one language using replace().
  • Split the resulting string into an array and print the elements.

Exercise 6: Safe Input Validation

  • Create a String variable that might be null.
  • Check for null before calling a method.
  • Check whether the value is empty or blank.
  • Display an appropriate message.

33. Mini Project: Student Registration Data Validator

Objective: Create a small Java program that validates a student's name, compares a selected course, and checks a basic email format using String methods.

Requirements

  • Remove surrounding whitespace from the student's name.
  • Reject a missing or blank name.
  • Compare the selected course with an expected course name.
  • Check that the email contains an at-sign and a dot as a basic demonstration.
  • Display a success or error message.

Sample Solution

public class StudentRegistrationValidator {
    public static void main(String[] args) {
        String name = "  Ananya Rao  ";
        String course = "core java";
        String email = "[email protected]";

        if (name == null || name.isBlank()) {
            System.out.println("Student name is required.");
            return;
        }

        name = name.strip();

        if (!course.equalsIgnoreCase("Core Java")) {
            System.out.println("Invalid course selection.");
            return;
        }

        if (email == null
                || !email.contains("@")
                || !email.substring(email.indexOf("@")).contains(".")) {
            System.out.println("Please check the email address.");
            return;
        }

        System.out.println("Registration details validated.");
        System.out.println("Name: " + name);
        System.out.println("Course: " + course);
        System.out.println("Email: " + email);
    }
}

Sample Output:

Registration details validated.
Name: Ananya Rao
Course: core java
Email: [email protected]

This project demonstrates common string operations but does not implement complete email validation. Real registration systems should use stronger validation and appropriate security controls.

34. Interview Questions and Answers

Q1. What is the String class in Java?

Answer: The String class represents an immutable sequence of characters and provides methods to examine, search, transform, and compare text.

Q2. What does length() return?

Answer: It returns the number of UTF-16 code units in the string.

Q3. What is the difference between equals() and ==?

Answer: equals() compares string contents, while == checks whether references point to the same object.

Q4. What is the purpose of equalsIgnoreCase()?

Answer: It compares string contents without treating ordinary case differences as unequal.

Q5. What does compareTo() return?

Answer: It returns a negative integer, zero, or a positive integer depending on the lexicographical ordering of the strings.

Q6. What is the difference between compareTo() and equals()?

Answer: equals() checks exact content equality and returns a boolean. compareTo() compares ordering and returns an integer.

Q7. What does substring() do?

Answer: It extracts a specified portion of a string and returns it as a new String value.

Q8. What does indexOf() return when a value is not found?

Answer: It returns -1.

Q9. What is the difference between replace() and replaceAll()?

Answer: replace() performs literal character or sequence replacement, while replaceAll() interprets its search argument as a regular expression.

Q10. What is the difference between trim() and strip()?

Answer: trim() removes a traditional limited range of leading and trailing characters. strip(), available from Java 11, uses Java's Unicode-aware whitespace rules.

Q11. What is the difference between isEmpty() and isBlank()?

Answer: isEmpty() checks whether the string has zero length. isBlank() also returns true when the string contains only recognized whitespace characters.

Q12. What does contains() do?

Answer: It checks whether a string contains a specified character sequence.

Q13. Why does a String method sometimes throw NullPointerException?

Answer: The method was invoked through a null reference rather than an actual String object.

Q14. What does split() return?

Answer: It returns an array of strings created by dividing the original string according to a regular-expression delimiter.

Q15. Why is String considered immutable?

Answer: Once a String object is created, its character contents cannot be changed. Operations that transform text return new string results.

35. Quick Revision Checklist

  • Understand String immutability.
  • Know how to use length() and charAt().
  • Practice uppercase, lowercase, trimming, and stripping methods.
  • Distinguish empty strings from blank strings and null references.
  • Use equals() and equalsIgnoreCase() correctly.
  • Understand lexicographical comparison with compareTo().
  • Use prefix, suffix, and substring-search methods.
  • Extract text using substring().
  • Understand literal replacement versus regular-expression replacement.
  • Practice split(), join(), and valueOf().
  • Validate null values and string indexes before using methods.
  • Apply string operations in practical Java programs.

36. Conclusion

String methods and comparisons are essential components of Core Java programming. Methods such as length(), charAt(), substring(), contains(), and replace() help developers process textual information. Comparison methods such as equals(), equalsIgnoreCase(), and compareTo() support reliable equality checks and ordering.

To use these methods effectively, remember that String objects are immutable, indexes begin at zero, and reference comparison is different from content comparison. Practice the examples and exercises in this lesson to build a strong foundation for more advanced Core Java programming.


Explore More: Visit the JustAcademy Core Java Training Course to explore course details, register for a course demo, or visit the JustAcademy website.

whatsapp