String strName = "My String"; //Use double quotes String strEmpty = ""; //Not same as null
Concatenation using the + symbol:
String strFirst = "John"; String strLast = "Brown"; String strFullName = strFirst + " " + strLast;
The following are useful in manipulating strings. If we have a string variable,
String strName = "John Brown";
| Method | Description | Return Value |
|---|---|---|
| strName.charAt(6); | Returns a single character | B |
| strName.length(); | Determines length of string | 10 |
| strName.substring(6,10); | Extracts part of a string | Brown |
| strName.toLowerCase(); | Formats string to lower case | john brown |
| strName.toUpperCase(); | Formats string to upper case | JOHN BROWN |
| strName.endsWith("own"); | True or false if the string ends in the given suffix | true |
| strName.beginsWith("own"); | True or false if the string begins with the given suffix | false |
| strName.indexOf("hn"); | Returns the position of the given string within the string | 3 |
| strName.replace("o", "z"); | Replaces first character with second | Jzhn Brzwn |
To test if two strings are equal then don't use == but use,
strName.equals("John Brown");
strName.equalsIgnoreCase("john brown");
API for the java.lang.String package