BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String contains() method

Last Updated: June 10, 2024 by Chaitanya Singh | Filed Under: java

Java String contains() method checks whether a particular sequence of characters is part of a given string or not. This method returns true if a specified sequence of characters is present in a given string, otherwise it returns false.

For example:

String str = "Game of Thrones";  

//This will print "true" because "Game" is present in the given String
System.out.println(str.contains("Game"));

// This will print "false" because "aGme" is not present, the characters
// must be present in the same sequence as specified in the contains method
System.out.println(str.contains("aGme"));

Syntax of contains() method

public boolean contains(CharSequence str)

The return type is boolean which means this method returns true or false. When the character sequence found in the given string then this method returns true else it returns false.

If the CharSequence is null then this method throws NullPointerException. For example: calling this method like this would throw NullPointerException.

str.contains(null);

Java String contains() method Examples

Let’s see some examples to understand how to use this method in various scenarios:

1. Simple Example to Demonstrate case sensitive nature of contains()

The second print statement displayed false because the contains() method is case sensitive. You can also use the contains() method for case insensitive check, I have covered this at the end of this tutorial.

class Example{  
   public static void main(String args[]){  
	String str = "Do you like watching Game of Thrones";  
	System.out.println(str.contains("like"));
		
	/* this will print false as the contains() method is
	 * case sensitive. Here we have mentioned letter "l" 
	 * in upper case and in the actual string we have this
	 * letter in the lower case. 
	 */
	System.out.println(str.contains("Like")); 
	System.out.println(str.contains("Game")); 
	System.out.println(str.contains("Game of")); 
   }
}

Output:

true
false
true
true

2. Using the method in if-else statement

As we know that the contains() method returns a boolean value, we can use this method as a condition in if-else statement.

class JavaExample{  
public static void main(String args[]){
String str = "This is an example of contains()";
/* Using the contains() method in the if-else statement, since
* this method returns the boolean value, it can be used
* as a condition in if-else
*/
if(str.contains("example")){
System.out.println("The word example is found in given string");
}
else{
System.out.println("The word example is not found in the string");
}
}
}

Output:

Java String contains method example

3. How to use String contains() method for case insensitive check

In the above example, we have seen that the contains() method is case sensitive, however with a little trick, you can use this method for case insensitive checks. Lets take an example to understand this:

Here, we are using the toLowerCase() method to convert both the strings to lowercase so that we can perform case insensitive check using contains() method. We can also use toUpperCase() method for this same purpose as shown in the example below.

class Example{  
  public static void main(String args[]){  
	String str = "Just a Simple STRING"; 
	String str2 = "string";
	//Converting both the strings to lower case for case insensitive checking
	System.out.println(str.toLowerCase().contains(str2.toLowerCase()));
		
	//You can also use the upper case method for the same purpose.
	System.out.println(str.toUpperCase().contains(str2.toUpperCase()));
  }
}

Output:

true
true

4. Example with Case Sensitivity and Null Check

In this example, we are handling case sensitivity by converting both string to lowercase before comparison. We are also handling NullPointerException if substring is null.

public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
String subStr = "world";

// Case sensitive check
boolean containsSubStr = str.toLowerCase().contains(subStr.toLowerCase());
System.out.println("Does the string contain 'world' (case insensitive)? " + containsSubStr); // Output: true

// Null check
try {
String nullStr = null;
boolean containsNull = str.contains(nullStr);
System.out.println("This will not be printed.");
} catch (NullPointerException e) {
System.out.println("Cannot check if a string contains null."); // Output: This message
}
}
}
❮ Java String Class

Top Related Articles:

  1. Why String Immutable or Final in Java
  2. Java 8 StringJoiner with example
  3. Java Math.sin() Method
  4. Java String split() Method with examples
  5. Java Integer byteValue() Method

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap