STRING INSTANCE METHODS
Java String contains() method
contains() checks whether text contains a specified character sequence. It returns trueif the sequence is found and falseif the sequence is absent.
Searching for part of a string
String tekstas = "Mokausi Java programavimo";
System.out.println(tekstas.contains("Java"));
System.out.println(tekstas.contains("Python"));true
false
- The variable
tekstasstores the sentence Mokausi Java programavimo. contains("Java")checks whether the sentence contains the text Java.- Because Java is found, the first result is
true. - Python is absent from this sentence, so the second result is
false.
Why is contains() an instance method?
contains() is called on a specific string because the search happens within that string:
boolean rasta = tekstas.contains("Java");
We therefore do not write String.contains(...). The left-hand tekstas object is where the supplied character sequence is searched for.
Method syntax
public boolean contains(CharSequence sequence)
| Part | Meaning |
|---|---|
| Calling object | tekstas in the line tekstas.contains("Java") |
| Parameter | sequence – the character sequence to search for |
| Parameter type | CharSequence, so accepted types include String, StringBuilder and StringBuffer |
| Return type | boolean |
true | The sequence was found |
false | The sequence was not found |
| Error | NullPointerExceptionwhen the argument is null |
Using contains() in a condition
String zinute = "Užduotis įvykdyta sėkmingai";
if (zinute.contains("sėkmingai")) {
System.out.println("Rodome žalią būseną");
} else {
System.out.println("Rodome klaidos būseną");
}Rodome žalią būseną
Because contains() returns boolean, it can be used directly in an if condition. This is common when checking messages, commands, user input or error text.
Uppercase and lowercase letters differ
String tekstas = "JavaQuest";
System.out.println(tekstas.contains("Java"));
System.out.println(tekstas.contains("java"));true
false
contains() is case-sensitive. JavaQuest contains the text Javabut not the text javabecause the first letter differs.
Searching without considering case
String tekstas = "JavaQuest";
String ieskoma = "java";
boolean rasta = tekstas.toLowerCase().contains(ieskoma.toLowerCase());
System.out.println(rasta);true
contains() has no separate parameter for ignoring case. In simple cases, convert both strings to lowercase with toLowerCase() and then search.
A CharSequence argument
String tekstas = "Sveiki atvykę į Java kursą";
StringBuilder ieskoma = new StringBuilder("Java");
System.out.println(tekstas.contains(ieskoma));true
The parameter type is CharSequence, so contains() can accept more than just String, but also in StringBuilder. Java compares the supplied sequence's textual contents.
An empty sequence is always found
String tekstas = "Java";
System.out.println(tekstas.contains(""));
System.out.println("".contains("Java"));true
false
Every string contains an empty sequence, so "Java".contains("") returns true. However, empty text does not contain the sequence Java, so the second result is false.
contains() finds substrings, not whole words
String tekstas = "JavaScript nėra Java";
System.out.println(tekstas.contains("Java"));
System.out.println(tekstas.contains(" Java "));true
false
contains("Java") finds Java even in the word JavaScriptbecause it searches for a sequence anywhere in the text. For whole words, using only contains() is often insufficient.
The connection to indexOf()
String tekstas = "Mokausi Java";
System.out.println(tekstas.contains("Java"));
System.out.println(tekstas.indexOf("Java") >= 0);
System.out.println(tekstas.indexOf("Java"));true
true
8
contains() only answers whether the sequence was found. For its position, use indexOf(). In the example, Java starts at index 8.
The argument cannot be null
String tekstas = "Java";
String ieskoma = null;
System.out.println(tekstas.contains(ieskoma));NullPointerException
If contains() receives null, Java cannot search for a nonexistent character sequence. It throws NullPointerException.
Checking safely before searching
String tekstas = "Java";
String ieskoma = null;
if (ieskoma != null && tekstas.contains(ieskoma)) {
System.out.println("Rasta");
} else {
System.out.println("Nėra ko ieškoti arba nerasta");
}Nėra ko ieškoti arba nerasta
If the search value may be null, check it first. The condition using && is safe because Java skips the second part when ieskoma != null is false.
Common mistakes
- Expecting
contains()to ignore uppercase and lowercase differences. - Using it to search for a whole word when it finds any matching substring.
- Passing a
nullargument to the method. - Confusing it with
indexOf():contains()returnsboolean, whileindexOf()returns an index. - Forgetting that the empty sequence
""is found in every string.
When should you use contains()?
contains() Use it for a simple check that text contains a specific sequence: in user input, messages, URL parts, files or commands. For the position, use indexOf(). To check a prefix or suffix, use startsWith() or endsWith().