Strings
Strings
Strings
Java string is a sequence of characters. They are
objects of type String.
Once a String object is created it cannot be
changed. Strings are Immutable.
To get changeable strings use the class called
StringBuffer.
String and StringBuffer classes are declared
final, so there cannot be subclasses of these
classes.
The default constructor creates an empty string.
String s = new String();
Creating Strings
String str = "abc"; is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
word “java"
“Java"
String Operations
The length() method returns the length of the
string.
Eg: System.out.println(“Hello”.length()); // prints
5
The + operator is used to concatenate two or
more strings.
Eg: String myname = “Harry”
String str = “My name is” + myname+ “.”;
String Operations
Characters in a string can be extracted in a
number of ways.
public char charAt(int index)
Returns the character at the specified index.
An index ranges from 0 to length() - 1. The first
character of the sequence is at index 0, the
next at index 1, and so on, as for array
indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”
String Operations
getChars() - Copies characters from this string
into the destination character array.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
String Operations
indexOf – Searches for the first occurrence of a character or
substring. Returns -1 if the character does not occur.
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
StringBuffer Operations
The principal operations on a StringBuffer are
the append and insert methods, which are
overloaded so as to accept data of any type.