Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

The java.lang Package Certification - String Class

  • Strings can be created implicitly by:
    1. using a quoted string ie "Hello", or,
    2. by using + or += on two String objects to create a new one
  • strings can be created explicitly by using the new operator
  • new String() creates an empty string
  • new String(String value) creates a new string that is a copy of the string object value
  • two basic String methods are
    • public int length()
    • public char charAt(int index). Index values range from 0 to length()-1
  • any String method requiring an index will throw an IndexOutOfBoundsException if
    0 > index > length()-1
  • there are also a number of indexOf() methods which allow you to find the first and last position of a character or substring within a string
        indexOf(char ch)            // first position of 'ch'
        indexOf(String str)         // first position of 'str'
        lastIndexOf(char ch)        // last position of 'ch'
        lastIndexOf(String str)     // last position of 'str'
    
  • each of the above methods also have overloads that allow a second int start argument which specifies the character position other than 0 from which to begin the search
  • all the methods return -1 if the character or string is not found

Comparison

  • characters in strings are compared numerically by their Unicode values
  • equals() method returns true if both string objects are of the same length and have the same sequence of Unicode characters
  • equalsIgnoreCase() can be used to compare strings, ignoring wether a character is lowercase or uppercase
  • compareTo returns an int that is <, =, or > than 0 if one string, based on it's Unicode characters, is less-than, equal to or greater-than another string
  • regions of strings can also be compared
public boolean regionMatches(int start, String other, 
                             int ostart, int len)
public boolean regionMatches(boolean ignoreCase, int start,
                             String other,
                             int ostart, int len)
  • an area of each string is compared for the number of characters specified by len
  • simple tests for the beginning and ending of strings can be done using
public boolean startsWith(String prefix, int toOffset)
public boolean startsWith(String prefix)
public boolean endsWith(String suffix)
Note
  • These methods return true if a comparison is done with an empty string
    "String".endsWith("");    // true
    "String".startsWith("");  // true

Comparisons using intern()

  • two utility methods hashCode() and intern() are available
  • hashCode() returns the same hash value for any two strings having the same contents
  • intern() returns a String that has the same contents as the one it is invoked on AND any two strings having the same content return the same String object allowing comparisons to be done using String references vs string contents
  • using intern() for comparison purposes is equivalent to comparing contents but is much faster

Related strings

  • several methods return new strings that are like the original but with the specified modifications
    public String concat(String str)
    public String replace(char oldChar, char newChar)
    public String substring(int beginIndex)
    public String substring(int beginIndex, int endIndex)
    public String toLowerCase()
    public String toUpperCase()
    public String trim()
    

    Because all of the above methods return new strings; comparisons such as

 String s = "String";    // in the pool
 
 if(" String ".trim() == s)
    System.out.println("Equal");
 else
    System.out.println("Not Equal");
    
OR

 if(" String ".trim() == "String")
    System.out.println("Equal");
 else
    System.out.println("Not Equal");               
  • produce NOT EQUAL. The string pool is NOT checked for a matching string and as a result the string object references are always different or, not equal (refer to String Literals - intern() for more info on the string pool)
  • HOWEVER, if the invoked method does not produce a different string ie the resulting string, after the method invocation, is the same as the original, THEN the original object reference is returned by the method and the results are EQUAL
        if("String".substring(0,6) == "String") 
            System.out.println("Equal"); 
        else 
            System.out.println("Not Equal");
        
        if("String".replace('t','t') == "String") 
            System.out.println("Equal"); 
        else 
            System.out.println("Not Equal");
    

Strings and Arrays

  • there are a number of constructors and methods that will convert a character array to a String and vice versa
public String(char[] value)
public String(char[] value, int offset, int count)

public static String copyValueOf(char[] data)
public static String copyValueOf(char[] data, 
                                 int offset, int count)
public void getChars(int srcBegin, intSrcEnd, 
                     char[] dst, int dstBegin)
public char[] toCharArray()
  • there are also a number of constructors and methods that convert 8-bit character arrays to and from 16-bit String objects
public String(byte bytes[], int offset, int length)
public String(byte bytes[])

public byte[] getBytes()
public String(byte bytes[], int offset, int length, String enc)
public String(byte, bytes[], String enc)
public byte[] getBytes(String enc)
  • where enc is the standard name for the character language encoding ie UTF8 or ISO-Latin-1

Also see

Sun Tech Tip: Interning Strings

Example Code

Main Classes Wrapper Classes Math Class String Immutability String Class StringBuffer Class