How to Compare String Methods Using Length & CharAt in Java
The Java programming language comes with a large library of tools called classes. You can use these classes to perform many common programming tasks quickly and efficiently. For example, you can compare the contents of two strings using the class methods "length" and "charAt." If two strings are identical, they will have the same length and every character at each index in the string will be the same. This simple test can confirm whether or not two strings are identical.
Things You'll Need
- Java Software Development Kit with NetBeans Integrated Development Environment (IDE) Bundle
Instructions
-
-
1
Download and install the Java Software Development Kit with NetBeans Integrated Development Environment (IDE) Bundle, if you haven't already done so.
-
2
Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right-hand side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains an empty main method.
-
-
3
Declare two strings by writing the following between the curly brackets of the main method:
string str0 = "String";
string str1 = "String";
-
4
Declare a Boolean data type that will tell you whether or not the strings match. Write the following statement below the declarations made in the previous step:
bool match = False;
-
5
Test to see if the strings have the same length by writing the following IF statement:
if(str0.length == str1.length) {}
-
6
Iterate through the strings and test to see if the characters in either string are identical. You can do this by writing a FOR loop that loops through every character in the strings and compares them using the "charAt" method. Write the following within the curly brackets of the IF statement:
for (int i = 0; i < str0.length; i++) { }
-
7
Compare the characters in each string using an IF-ELSE statement. Write the following within the curly brackets of the FOR loop:
if (str0.charAt(i) != str1.charAt(i) { }
else {}
-
8
Set the Boolean value to false if any of the characters do not match. Write the following within the curly brackets of the IF statement:
match = False;
-
9
Set the Boolean value to true if all of the characters match. Write the following within the curly brackets of the ELSE statement:
match = True;
-
10
Print the result of the comparison to the output window by writing the following statement:
System.out.println(match);
-
11
Execute the program by pressing the F6 key. The program will output the word "True" because both "Str0" and "Str1" match. Try changing the values of these strings and rerunning the program.
-
1