String Methods

From CompSciWiki
Revision as of 10:55, 22 March 2007 by Umelazza (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Calling Methods


Introduction

Although the String class has a plethora of methods that you may use, you will find three of them to be the most useful at this point. Two are very similar (comparing the equality of two Strings), and the other is used to find the length of the String you are working with.

   

{{{Body}}}

String Methods

In the beginning of the Java programming learning process, you have learned that the equal sign "==" determines equality of primitive types (eg. int, double, char). However, other built-in String methods are used to find the equality of two Strings. String is just another toolbox and its methods are the tools to simplify work related to Strings.

equals()

This method compares two Strings and returns a boolean result (true or false). Think of it as a method that is applied to a String to see if it equals another. Example:

String testString;
testString = "I am test";

if testString.equals("I am test")
{
     //testString equals "I am test"
}
else
{
     //testString does not equal "I am test"
}

The above example will result in the if statement being true. Note that equals() must be applied to a string variable.

equalsIgnoreCase()

This method is the same as the one above but the result will be true even if the cases are different. "I AM TEST" would be the same as "i am test".

length()

This method simply returns the number of characters (including spaces, tabs, etc.) in the String that calls it. For example:

String test = "I am test";
int length = test.length();

System.out.println("The string's length is: " + length);

Which gives the result:

The string's length is: 9

More Methods

For a full list of all the String methods you can visit The API String Methods and scroll down to the Method Summary table.