When you’re writing automated test cases in Java, you’ll often want to use string methods to see if your test results match expectations.
What are string methods? They let you perform various operations on strings, like checking how many characters they have, or whether they contain certain words.
Below, you’ll find a list of some of the most common Java string methods. If you don’t understand how to use them, don’t worry — you can scroll down to see real live examples of code using each string method on the list below.
Common Java String Methods:
- String length() — returns the length of the string
- String charAt() — returns a char value at the given index number
- String concat() — adds a given string at the end of the string
- String contains() — returns true if chars are found in the string
- String startsWith() — checks if a string starts with a given prefix
- String endsWith() — checks if a string ends with a given suffix
- String equals() — compares the contents of two given strings
- String indexOf() — returns the index of a given character value or substring
- String isEmpty() — checks if the string is empty
- String replace() — returns a string replacing all of the old char with new char
- String substring() — returns a part of the string
- String toCharArray() — returns the string converted into character array
- String toLowerCase — returns the string in lowercase letter(s)
- String toUpperCase() — returns the string in uppercase letter(s)
- String trim() — removes leading and trailing spaces
Test Cases Using String Methods:
You can view a suite of TestNG test cases using these string methods here, on my Github profile. This isn’t meant to be a comprehensive or real test plan, but rather a fun way to see what types of things the above list of string methods can do in an automated test.
Note that if it doesn’t make sense to you, that’s okay — everyone has to start from somewhere, and there are a ton of great free and low-cost resources online that can help you learn Java (or whatever language you’d like to write automated test scripts in). Two of the best cheap and/or free resources that I recommend are Codecademy and Udemy. Good luck!