String Class

by Michael Thomas

(Tutorial Home Page)

Topic Notes
String Class
  • The String object is immutable.  Which means once the String object it is created, it cannot be changed.
  • When you add two String objects together, a third object is created.
  • String objects can be created by using the "new" keyword or by using a literal.  Example:
    1.  String strTest = new String("Hello")
    2.  String strTest = "Hello"

Note: The StringBuffer object allows strings to be concatenated without creating a new object.

length() Gives the number of chars in a string.

Example

  • System.out.println( "Hello".length() ); - shows 5
  • String T = new String("Hello");
    System.out.println( T.length() );  - shows 5
substring()
  • substring(begin, end*);  - warning, returns the begining char (index starts with 0) through (end - 1).

Examples

  • "hello".substring(1,2) - returns "e"
toUpperCase()  
toLowerCase()  
String.equals() vs
StringBuffer.equals()
  • String's equals() is overridden to give you equality of the contents of the object.
  • StringBuffer's equals just checks for equality of the object references.  Note:   Object's equals() is not overridden.

Example:
String strExample = "Hello World"
if ( strExample.equalsIgnoreCase("Hello World") { etc...}

equalsIgnoreCase()  

Example:
String strExample = "Hello World"
if ( strExample.equalsIgnoreCase("hello world") { etc...}

charAT()  
concat()  
indexOf()  
lastIndexOf()  
toString()  
trim()  
Add examples Need to Add examples:

String strExNull;
strExNull = null;
if ( strExNull != null ) {} etc...
 

Regular Expressions java.util.regex Class Pattern
http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum

"\\d{5}" - any digit, exactly 5 times.  Good for zip codes.

match() Ex:
boolean valid = myZip.matches("\\d{5}"); // any digit, exactly 5 times
split() Ex:
String[] fields = myString.split(
"\\|");