String Class Tutorials

public boolean contains(CharSequence s)

The contains() method is very useful for searching strings to see if they contain a specific value. The method will return true if the parameter string is found inside of the current string instance, if not, it will return false.
For example,
String a = "hen fox house";
if ( a.contains("fox") ) {
        System.out.println("Found a fox in the hen house.");
}



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md StringContains
C:\Java>cd StringContains
C:\Java\StringContains>Notepad StringContains.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class StringContains {
	public static void main(String args[]) {
		String a = "hen fox house";
		String b = "sheeps wolf clothing";
		if (a.contains("fox")) {
			System.out.println("Found a fox in the hen house.");
		}
		if (b.contains("wolf")) {
			System.out.println("Found a wolf in sheeps clothing.");
		}
	}	
}


Now switch back to the command prompt (CMD) and type in javac StringContains.java and press Enter.
Now type in java StringContains and press Enter.


C:\Java\StringContains>javac StringContains.java
C:\Java\StringContains>java StringContains
Found a fox in the hen house.
Found a wolf in sheeps clothing


Final thoughts

One strategy that I regularly use to solidify my knowledge of Java is to browse through the actual source code. Due to some language in their copyright file, I can't actually show the source code in my videos. The source code is contained inside of a file called src.zip located in the folder where your JDK is installed. I recommend using notepad++ to browse the class files.


Tutorials