Java String Contains Sample Code

What is a String in Java? Fair question indeed. In short, a String is a sequence of characters that are grouped together.

Let’s say you have a long String and you want to find out if that long String happens to have a single word in it. So let’s use the String.contains() method to test that.

The String.contains() method will return a boolean value. If the String contains the other String, it will return true, otherwise return false.


package com.jcd.java.tutorials;

public class JavaStringContains 
{

	public static void main(String[] args) 
	{
		//Define your base String
		String jcdString = "Online resource for java developers and programmers - providing working java code samples and tutorials.";
		
		//Define looking for String
		String jcdStringFind = "java code samples";
		
		//Use contains() and check boolean return
		if(jcdString.contains(jcdStringFind))
		{
			System.out.println("Found "+jcdStringFind+ " within "+jcdString);
		}
		else
		{
			System.out.println("Did NOT Find "+jcdStringFind+ " within "+jcdString);
		}

	}

}

Found java code samples within Online resource for java developers and programmers - providing working java code samples and tutorials.



Useless Java Facts

Did you know that the String class, most often used class in Java, contains 15 different constructors? Did you also know the Java String class contains about 65 methods? Pretty cool and yet not all at the same time.



Concluding Comments

String.contains() method is a good option for testing the presence of a smaller String within a larger String.



Java References:

Add a Comment

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