Java String Methods with Examples (contains, equals, substring, join)

String methods in Java are built-in functions in the java.lang.String class that let you compare, search, extract and transform text. Java’s String class includes over 60 methods; mastering around a dozen — such as equals(), contains(), substring() and join() — covers roughly 90% of real-world string handling tasks.

  • String objects in Java are immutable, so every method returns a new String rather than changing the original.
  • Use equals(), not ==, to compare string content; == compares memory addresses, not characters.
  • substring(int beginIndex, int endIndex) extracts a slice of text using zero-based indexing.
  • contains(), indexOf() and startsWith() handle all common search tasks cleanly.
  • Mastering string methods in Java is one of the fastest ways to clear coding rounds in campus placements and technical interviews at Indian IT companies.

How String Methods in Java Work

The String class lives in java.lang, which Java imports automatically, so you never need an explicit import statement to use it. When you write String name = "Riya";, Java stores that literal in the string pool, a special area of heap memory that reuses identical string values to save space. According to the Oracle Java SE 22 release notes, the string pool optimisation has been part of the JVM since Java 1.0 and continues to be a core memory efficiency feature.

Because strings are immutable, calling any method on a string does not alter the original object. It returns a brand new String. This trips up beginners constantly: they call name.toUpperCase() and then print name and wonder why nothing changed. Always capture the return value.

The String Class at a Glance

Here is a reference table of the most used string methods in Java, their syntax and what they return. Every method listed below works in Java 8 and above.

Method Syntax Returns Common Use
length() str.length() int Count characters
charAt() str.charAt(i) char Get character at index
equals() str.equals(other) boolean Case-sensitive comparison
equalsIgnoreCase() str.equalsIgnoreCase(other) boolean Case-insensitive comparison
contains() str.contains(seq) boolean Check for substring
indexOf() str.indexOf(s) int Find first position of substring
substring() str.substring(start, end) String Extract part of a string
concat() str.concat(other) String Join two strings
join() String.join(delim, parts) String Join with a separator
toString() obj.toString() String Convert object to text
toUpperCase() str.toUpperCase() String Convert to uppercase
trim() str.trim() String Remove leading/trailing spaces
replace() str.replace(old, new) String Swap characters or substrings
split() str.split(regex) String[] Break string into array
isEmpty() str.isEmpty() boolean Check for empty string

If you’re just starting out with Java and want a broader view of which software development tools to learn first, that guide pairs well with this one. String handling is foundational to almost everything else you’ll build.

Comparison Methods: equals and compareTo

The equals method in Java is the correct way to compare two strings by their actual content. The == operator checks whether two variables point to the same object in memory, which gives unpredictable results with strings created at runtime. This is one of the most common bugs in beginner Java code, and it shows up in nearly every Java interview at companies like TCS, Infosys and Wipro.

Using equals() and equalsIgnoreCase()

The equals() function in Java is case-sensitive. "Java".equals("java") returns false. If you’re validating user input, like a login form where someone types their city name in mixed case, use equalsIgnoreCase() instead. It treats “Mumbai” and “mumbai” as identical.

Here’s the practical pattern you’ll use most often:

  • str1.equals(str2) returns true only if every character matches in the same case.
  • str1.equalsIgnoreCase(str2) returns true regardless of case differences.
  • Always call equals on a known non-null string: write "expected".equals(userInput) rather than userInput.equals("expected") to avoid a NullPointerException.

Speaking of NullPointerException, that’s one of the most frequent runtime errors Java developers face. Our guide on Java exceptions and common runtime errors covers exactly how to handle it.

Using compareTo()

compareTo() does something different from equals(). It compares two strings lexicographically (dictionary order) and returns an integer. A return value of 0 means the strings are equal. A negative value means the calling string comes before the argument alphabetically. A positive value means it comes after.

This method is what Java’s sorting algorithms use internally when you sort a list of strings. If you’ve ever called Collections.sort() on a list of names, compareTo() was doing the work behind the scenes.

According to the Stack Overflow Developer Survey 2024, Java remains one of the top five most-used programming languages globally, with around 30% of professional developers working with it regularly. Getting string comparison right is non-negotiable at that scale.

Search and Extract: contains, indexOf, substring

These three string methods in Java cover almost every “find something in a string” task you’ll encounter. They’re heavily tested in coding assessments for BTech and MCA placements, and they come up constantly in backend development work.

contains() in Java

The contains() method checks whether a string includes a specific sequence of characters and returns a boolean. It’s the simplest way to check if a string contains text in Java.

Example: String email = "student@iit.ac.in"; email.contains("iit") returns true. You’d use this to validate that an email belongs to a particular domain before allowing access to a resource.

One practical tip: contains() is case-sensitive. If you need a case-insensitive check, convert the string to lowercase first with str.toLowerCase().contains("keyword"). This pattern appears constantly in search filters and data validation logic across Indian fintech and edtech backends.

indexOf()

indexOf(String s) returns the zero-based index of the first occurrence of a substring. If the substring doesn’t exist, it returns -1. That -1 return value is the standard Java signal for “not found”, and checking for it is a common interview question at FAANG and Indian IT companies alike.

Example: "Bengaluru, Karnataka".indexOf("Karnataka") returns 11. You can use this to locate a position before calling substring() to extract the part you need.

substring() in Java

The Java substring method extracts a portion of a string. It takes either one or two arguments: substring(int beginIndex) extracts from that index to the end, and substring(int beginIndex, int endIndex) extracts from beginIndex up to but not including endIndex.

Example: "GATE2025".substring(4) returns "2025". "GATE2025".substring(0, 4) returns "GATE". The end index is exclusive, which catches a lot of beginners off guard.

A common mistake is passing an endIndex larger than the string’s length. That throws a StringIndexOutOfBoundsException at runtime. Always validate your index values if they come from user input or dynamic data. If you’re studying for placements and want context on where Java fits in broader career paths, the BSc Computer Science subjects and scope article gives a solid overview.

Utility String Methods: trim, replace, split

These string methods in Java handle everyday data-cleaning tasks. They appear constantly in form validation, file parsing and API response processing.

trim()

trim() removes leading and trailing whitespace from a string. " Priya ".trim() returns "Priya". This is essential when processing user input from web forms or CSV files where accidental spaces cause comparison failures. For more granular whitespace removal, Java 11 introduced strip(), which also handles Unicode whitespace characters that trim() misses.

replace()

replace(CharSequence old, CharSequence new) swaps every occurrence of a character or substring with a replacement. "roll_no".replace("_", " ") returns "roll no". Use replaceAll() when you need regex-based replacement, such as stripping all digits from a string.

split()

split(String regex) breaks a string into an array of substrings wherever the delimiter matches. "Delhi,Mumbai,Chennai".split(",") returns an array of three city names. This is one of the most-used string methods in Java for parsing CSV data, reading config files and processing API responses. According to the TIOBE Index (April 2025), Java ranks consistently in the top three programming languages worldwide, and string parsing operations like split() are among the most frequently executed in production Java codebases.

Build and Convert: concat, join, toString

These methods are about assembling and converting strings rather than reading from them. They’re used in everything from building SQL queries to formatting output for REST APIs.

concat() in Java

The concat() method joins two strings end to end and returns the result. "Hello, ".concat("Arjun") gives you "Hello, Arjun". It’s functionally similar to the + operator, but there’s a subtle difference: concat() throws a NullPointerException if the argument is null, while + converts null to the string "null".

In production code, most developers prefer StringBuilder or String.join() over repeated concat() calls inside loops, because each concat() creates a new object. In a loop of a thousand iterations, that’s a thousand throwaway objects sitting in heap memory.

join() in Java

String.join() is a static method introduced in Java 8. It takes a delimiter and then either a list of strings or an array, and joins them with that separator. It’s cleaner than writing your own loop with concat().

Example: String.join(", ", "Delhi", "Mumbai", "Chennai") returns "Delhi, Mumbai, Chennai". You’d use this when building comma-separated output for a report or a CSV export in a data pipeline.

toString() in Java

The toString() method converts an object to its string representation. Every class in Java inherits a default toString() from java.lang.Object, but the default version just prints the class name and hash code, which isn’t useful. You override it in your own classes to return something meaningful.

Example: If you have a Student class with fields name and rollNo, overriding toString() to return "Student{name='Priya', rollNo=42}" makes debugging and logging dramatically easier. Every serious Java developer overrides toString() in their model classes. It’s also what gets called automatically when you print an object with System.out.println(obj).

If you’re weighing career paths that use these skills daily, the comparison of full stack developer vs software developer roles is worth reading. Both rely heavily on string methods in Java for backend logic. Students looking at postgraduate paths might also find the guide on jobs and salary after MCA useful for understanding where Java skills take you in the job market.

And if you’re coming from C and want to see how string handling compares across languages, our article on how to write, compile and run a C program gives useful context on how much lower-level the equivalent work is in C.

Frequently Asked Questions

What are the string methods in Java?

String methods in Java are built-in functions from the java.lang.String class that let you compare, search, extract, join and convert text. Common examples include equals(), contains(), substring(), concat(), join() and toString(). They work on immutable String objects, so each method returns a new String rather than modifying the original.

How does equals work in Java?

The equals() method compares two strings character by character and returns true if they are identical in content and case. It’s the correct alternative to ==, which only checks if two variables point to the same memory location. Use equalsIgnoreCase() when you want the same comparison without caring about upper or lower case.

How do I use substring in Java?

Call str.substring(beginIndex) to extract from a position to the end of the string, or str.substring(beginIndex, endIndex) to extract a specific range. Indexing is zero-based, and the endIndex is exclusive, meaning the character at that position is not included. Passing an out-of-range index throws a StringIndexOutOfBoundsException.

How do I check if a string contains text in Java?

Use the contains() method: str.contains("keyword") returns true if the substring is found, false if not. It’s case-sensitive, so convert the string to lowercase first if you need a case-insensitive check. Use indexOf() instead if you also need to know the position of the match.

What does toString do in Java?

The toString() method converts an object into a human-readable string. Every Java class inherits a default version from java.lang.Object, but it only returns the class name and hash code. Override it in your own classes to return meaningful output, and Java will call it automatically whenever you print the object with System.out.println().

What is the difference between concat() and join() in Java?

concat() is an instance method that joins exactly two strings end to end. String.join() is a static method introduced in Java 8 that joins multiple strings with a specified delimiter. For joining more than two strings or building delimited output like CSV rows, join() is cleaner and more readable than chaining multiple concat() calls.

Is String immutable in Java and why?

Yes, String objects in Java are immutable. Once created, their character content cannot be changed. This design choice makes strings safe to share across threads without synchronisation, allows the JVM to cache them in the string pool to save memory, and prevents accidental modification when a string is passed to a method. If you need a mutable string, use StringBuilder instead.

What does compareTo() return in Java?

The compareTo() method returns an integer: 0 if both strings are equal, a negative number if the calling string comes before the argument alphabetically, and a positive number if it comes after. It performs a lexicographic (dictionary-order) comparison and is used internally by Java’s sorting algorithms when you call Collections.sort() on a list of strings.

String methods in Java are the building blocks of almost every application you’ll write, from input validation and data parsing to API responses and log messages. Once you’re comfortable with the methods covered here, you have the foundation to tackle collections, file I/O and web development with confidence.

  1. Practice this week: Write a small Java program that takes a user’s full name as input, trims whitespace, checks if it contains a middle name using indexOf(), and prints each part using substring().
  2. Go deeper: Explore StringBuilder and StringBuffer for cases where you’re building strings inside loops. They’re significantly more memory-efficient than repeated concat() calls.
  3. Level up your career: Strong programming fundamentals like these are the entry point to secure coding, ethical hacking and AI development. Explore 3.0 University’s full catalogue of online certification courses in Cybersecurity, Ethical Hacking, AI and Blockchain, or start directly with the CEH v13 AI online course if you want to apply your Java and programming skills in the cybersecurity space.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles