Reference

The String Class

Declaration

  String strName = "My String";  //Use double quotes
  String strEmpty = "";    //Not same as null

Common Methods

Concatenation using the + symbol:

  String strFirst = "John";
  String strLast = "Brown";
  String strFullName = strFirst + " " + strLast;

String Editing

The following are useful in manipulating strings. If we have a string variable,

  String strName = "John Brown";
MethodDescriptionReturn Value
strName.charAt(6);Returns a single characterB
strName.length();Determines length of string10
strName.substring(6,10);Extracts part of a stringBrown
strName.toLowerCase();Formats string to lower casejohn brown
strName.toUpperCase();Formats string to upper caseJOHN BROWN
strName.endsWith("own");True or false if the string ends in the given suffixtrue
strName.beginsWith("own");True or false if the string begins with the given suffixfalse
strName.indexOf("hn");Returns the position of the given string within the string3
strName.replace("o", "z");Replaces first character with secondJzhn Brzwn

Testing Strings for Equality

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