String Class

by Michael Thomas

(Tutorial Home Page)

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.
equalsIgnoreCase()  
charAT()  
concat()  
indexOf()  
lastIndexOf()  
toString()  
trim()