String
Date: 05-14-2001
String
In Java a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String.
When you create a String object, you are creating a string that cannot be changed. Once a String object has been created, you cannot change characters that comprise that string.
Each time you need an altered version of an existing String, a new String object is created that contains the modifications.
The original String is left unchanged. This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones. For those cases in which a modifiable string is desired, use StringBuffer.
Both String and StringBuffer classes are defined in java.lang.
Constructors:
String s = new String ( ) ;
String (char chars[ ])
Ex.
char chars[ ] = {‘a’, ‘b’, ‘c’, ‘d’};
String s = new String (chars); //s is initialized with “abcd”
String (char chars[ ], int startIndex, int numChars)
Ex.
char chars[ ] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
String s = new String (chars, 2, 3); //s is initialized with “cde”
String (String strObj)
Ex.
char chars[ ] = {‘J’, ‘a’, ‘v’, ‘a’};
String s1 = new String (chars); //s1 is initialized with “Java”
String s2 = new String (s1); //s2 is initialized with “Java”
String (byte asciiChars[ ])
String (byte asciiChars[ ], int startIndex, int numChars)
Ex.
byte ascii[ ] = {65, 66, 67, 68, 69, 70};
String s1 = new String (ascii); //s1 is initialized with “ABCDEF”
String s2 = new String (ascii, 2, 3); //s2 is initialized with “CDE”
int length()
Ex.
char chars[ ] = {‘a’, ‘b’, ‘c’, ‘d’};
String s = new String (chars); //s is initialized with “abcd”
System.out.println(s.length());
Output:
4
Ex.
char chars[ ] = {‘a’, ‘b’, ‘c’, ‘d’};
String s1 = new String (chars); //s is initialized with “abcd”
String s2 = “abcd” // using string literal
System.out.println(“abcd”.length());
String Concatenation
Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a string object as a result.
Ex.
String age = “9”;
String s = “He is ” + age “ years old.”;
System.out.println(s);
int age = 9;
String s = “He is ” + age “ years old.”;
System.out.println(s);
String s = “four: “ + 2 + 2;
System.out.println(s);
Output:
four: 22
String s = “four: “ + (2 + 2);
System.out.println(s);
Output:
four: 4
When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf(), defined by String. ValueOf() is overloaded for all simple types and for Object.
For simple types, valueOf() returns a string that contains human-readable equivalent of the value with which it is called. For objects, valueOf() calls the toString() method on the object. Every class implements toString() because it is defined by Object.
String toString().
charAt()
char charAt(int where)
char ch;
ch = “abcd”.charAt(1);
getChars()
void getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
getBytes()
character-to-byte conversion. Useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters.
byte[ ] getBytes()
toCharArray()
char[ ] toCharArray()
equals() and equalsIgnoreCase()
boolean equals(Object str)
boolean equalsIgnoreCase(String str)
Sample Code
class equalsDemo {
public static void main(String args[ ]) {
String s1= “Hello”;
String s2= “Hello”;
String s3= “Good-Bye”;
String s1= “HELLO”;
System.out.println(s1 + “equals” + s2 + “ :” + s1.equals(s2));
System.out.println(s1 + “equals” + s3 + “ :” + s1.equals(s3));
System.out.println(s1 + “equals” + s4 + “ :” + s1.equals(s4));
System.out.println(s1 + “equalsIgnoreCase” + s4 + “ :” + s1.equalsIgnoreCase(s4));
}
}
Output:
Hello equals Hello: true
Hello equals Good-Bye: false
Hello equals HELLO: false
Hello equalsIgnoreCase HELLO: true
regionMatches()
boolean regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex, String str2,
int str2StartIndex, int numChars)
startsWith() and endsWith()
boolean startsWith(String str)
boolean endsWith(String str)
“Football”.endsWith(“ball”)
“Football”.startsWith(“Foot”)
boolean startsWith(String str, int startIndex)
“Football”.startsWith(“ball”,4)
equals() Versus ==
equals() method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.
Ex.
class Equality {
public static void main(String args[ ]) {
String s1 = “Hello”;
String s2 = new String (s1);
System.out.println(s1 + “ equals ” + s2 + “:” + s1.equals(s2));
System.out.println(s1 + “ == ” + s2 + “:” + (s1 == s2));
}
}
Output:
Hello equals Hello: true
Hello == Hello: false
CompareTo()
For sorting, you ned to know which is less than, equal to, or greater than that the next.
int compareTo(String str)
Less than zero The invoking string is less than str
Greater than zero The invoking string is greater than st
Zero The two strings are equal
Sample Code
class SortString {
static String arr [ ] ={“Now”, “is”, “the”, “time”, “for”, “all”, “good”, “men”, “to”, “come”, “to”, “the”, “aid”, “aid”, “of”, “their”, “country”};
public static void main (String args[ ]) {
//bubble sort for Strings
for (int j = 0; j< arr.length; j++ ){
for(int i = j + 1; i< arr.length; i++ ){
if (arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Output:
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
int compareToIgnoreCase(String str)
indexOf()
Searches for the first occurance of a character or substring
lastIndexOf()
Searches for the last occurance of a character or substring
They return the index at which the character or substring was found, or –1 on failure.
int indexOf(int ch)
int lastIndexOf(int ch)
int indexOf(String str)
int lastIndexOf(String str)
int indexOf(int ch,int startIndex)
int lastIndexOf(int ch,int startIndex)
int indexOf(String str,int startIndex)
int lastIndexOf(String str,int startIndex)
subString()
String subString(int startIndex)
String subString(int startIndex, int endIndex)
concat()
String concat(String str)
Ex.
String s1 = “one”;
String s2 = s1.concat(“two”);
replace()
String replace(char original, char replacement)
Ex.
String s = “Henno”.replace(‘n’, ‘l’);
trim()
String s = “ Hello World “.trim();
toLowerCase() and toUpperCase()
Nonalphabetical characters are unaffected.
String toLowerCase()
String toUpperCase()
Ex.
String s1 = “Original String.”;
String s2 = s1.toLowerCase();
String s3 = s1.toUpperCase();
StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences. StringBuffer represents growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automaticallt grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.
StringBuffer() // reserves room for 16 characters without reallocation
StringBuffer(int size) //explicitly specify the size of the buffer
StringBuffer(String str) //initial contents specified, reserves room for 16 characters…
length() and capacity()
int length()
int capacity()
class StringBufferDemo{
public static void main (String args[ ]) {
StringBuffer sb = new StringBuffer(“Hello”);
System.out.println(“buffer = ” + sb );
System.out.println(“length = ” + sb.length() );
System.out.println(“capacity = ” + sb.capacity() );
}
}
Output:
buffer = Hello
length = 5
capacity = 21
ensureCapacity()
To preallocate room for a certain number of characters after a StrinfBuffer has been constructed, call ensureCapacity() to set the size of the buffer.
void ensureCapacity(int capacity)
setLength()
To set the length of the buffer. If set to value less than the current value returned by length(), then characters stored beyond the new length will be lost.
void setLength()
charAt() and setCharAt()
char charAt(int where) //where must be nonnegative
void setCharAt(int where, char ch) //where must be nonnegative
Sample Code
class setCharAtDemo{
public static void main(String args[ ]) {
StringBuffer sb = new StringBuffer(“Hello”);
System.out.println(“buffer before =” + sb);
System.out.println(“chatAt(1) before =” + sb.charAt(1));
sb.setCharAt(1, ‘i’);
sb.setLength(2);
System.out.println(“buffer after =” + sb);
System.out.println(“chatAt(1) after =” + sb.charAt(1));
}
}
Output:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
getChars()
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
append()
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
insert()
StringBuffer insert (int index, String str)
StringBuffer insert (int index, char ch)
StringBuffer insert (int index, Object obr)
reverse()
StringBuffer reverse()
class ReverseDemo {
public static void main(String args[ ]) {
StringBuffer s = new StringBuffer (“abcdef”);
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output:
abcdef
fedcba
delete() and deleteCharAt()
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
replace()
StringBuffer replace(int startIndex, int endIndex, String str)
subString()
String subString(int startIndex)
String subString(int startIndex, int endIndex)