[edit] Java strings
String, as the name suggest it is the regular sequence of the characters and having done the operations on them. In Java , string is a sequence of characters and is treated as an object of String type. Since strings is available in java as built in objects it facilitates the comparison of two strings, concatenation, searching etc in a very simple and easy way.
Normally it is very difficult to change the string which is once created so java provides us with the availability of string and string buffer in java.lang through which we can create the copies of the existing string and then can do the changes on the string object that has been created. Both these classes are declared final which means that neither of theses classes can be sub classed in any ways.
String constructors:
As any other class, string class also provides support to various number of constructors .
For instance
1. String s= new String ( );
Will create an instance of String with no characters.
2. String (char [ ])
Will create a String initialized by an array of characters.
3. String(char chars[ ], int startIndex, int numChars)
In this , startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.
4. String(String strObj)
In this, strObj is a String object.it will create a String object that contains the same character sequence as another String.
Now let’s have a look on the various methods which are related to Strings and how they work with the Strings.
1. String Length
It is used to find out the length of any given String, which means the number of characters it holds in it.
length( ) method,
int length( )
Example:
char chars[] = { 'a', 'b', 'c', ’d’ };
String s = new String(chars);
System.out.println(s.length());
This will give 4 as the output of the statements written above as it contains four characters a,b,c,d.
2 . Special String Operations
Java has come up with the special support features to Strings like automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the
Conversion of other data types to Strings and Java does all this automatically thus making programming much easier for the Java Programmers.
Let’s have a brief understanding of each one of them in the section below:
a. Creation of new String Instances from String Literals:
Normally a String instance can bre created using the new operator but Java automatically constructs a String Object and thus we can use a String literal to initialize a String Object.
For example,
the following code fragment creates two equivalent strings:
char chars[] = { 'a', 'b', 'c'};
String s1 = new String(chars);
String s2 = "abc"; // use string literal
This will give two equivalent Strings as the output.
b.String Concatenation
Java allows an exception as it gives the permission to implement the + operator on the string for the Concate nation of two strings and producing a String Object as the output of the operation.
For example, the following fragment concatenates three strings:
String age = "12";
String s = "He is " + age + " years” + “old.";
System.out.println(s);
The output of these statements will add up these four Strings and will show :
He is 12 Years old.
c. String Concatenation with Other Data Types. We can also concatenate strings with other types of data. For example, consider this
int age = 15;
String s = "He is " + age + " years old.";
System.out.println(s);
In this Example although, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as we saw in the above example.
Hence, the oupput will be:
He is 15 years old.
3. Character Extraction
The Characters can be easily extracted from a String Object.
Each one of them is mentioned below:
a. charAt( )
We can directly refer to an individual character and can extract a single character from a String.
String.charAt( ) method.
char charAt(int where)
where is the index of the character that we want to obtain. The value of where must be nonnegative and specify a location within the string.
charAt( ) returns the character at the specified location.
For example
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch.
b. getChars( )
It is used to get more than one character at a time, getChars( ) method.
getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
sourceStart specifies the index of the beginning of the substring, sourceEnd specifies an index that is one past the end of the desired substring.
public class GetCharsExample {
public static void main(String[] args) {
String str = "GetCharsExample";
char chars[] = new char[5];
str.getChars(1, 6, chars, 0);
System.out.println(chars);
}
}
Output
etCha
In java all index starts from 0. So in the above program it will start extracting character from 1st index(second character) and not from 0th index. The end index is 6 so it extracts from second character to seventh character.
c. getBytes( )
This methodT stores the characters in an array of bytes and it uses the default character-to-byte conversions provided by the platform.
byte[ ] getBytes( )
It is most useful when we are exporting a String value into an environment that does not support 16-bit Unicode characters.
d. toCharArray( )
It is used to convert all the characters in a String object into a character array. It returns an array of characters for the entire string.
char[ ] toCharArray( )
4. String Comparison
The String class includes several methods that compare strings or substrings within strings.
Let’s discuss each of these methods in bried in the section below:
a. equals( ) and equalsIgnoreCase( )
equals ( ) is used to compare two strings for equality.
boolean equals(Object str)
str is the String object which is being compared with the invoking String object.
It will return value as “true” if the Strings have same characters in same order else will give “ False” as the output. Please keep it in mind that it is case sensitive.
We can use equalsIgnoreCase ( ) to do comparison that ignores case differences.
boolean equalsIgnoreCase(String str)
str is the String object being compared with the invoking String object. It,also returns true if the strings contain the same characters in the same order, else false.
public class EqualsAndEqualIgnoreCaseExample {
public static void main(String[] args) {
String str = "EqualsAndEqualIgnoreCaseExample";
String strWithSmallLetters = "equalsandequalignorecaseexample";
// equals() is case sensitive
System.out.println(str.equals(strWithSmallLetters));
// equalsIgnoreCase is case insensitive
System.out.println(str.equalsIgnoreCase(strWithSmallLetters));
}
}
Output
false
true
5. regionMatches( )
This method is used to compares a specific region inside a string with another specific region in another string.
It also has two methods one for case sensitive as:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
Another was non case sensitive:
boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)
in both the syntaxes startIndex specifies the index at which the region begins within the invoking String object.
Str2 specifies the String being compared .
The index at which the comparison will start within str2 is specified by str2StartIndex.
The length of the substring being compared is passed in numChars. In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case is significant.
6. startsWith( ) and endsWith( )
As the term illustrates , startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) determines whether the String in question ends with a specified string.
startswith ( ): boolean startsWith(String str)
endswith ( ): boolean endsWith(String str)
str is the String being tested. If the string matches, true is returned else false.
7. equals( ) Versus == equals( ) method and the == operator have two different functionality for which the programmers normally get confused.
The equals( ) method compares the characters inside a String object while . The == operator compares two object references to see whether they refer to the same instance.
public class StringEqualityExample {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
String str3 = new String("bcd");
String str4 = new String("bcd");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
System.out.println(str3 == str4);
System.out.println(str3.equals(str4));
}
}
Output generate by the above code
true
true
false
true
8. compareTo( )
This method helps us to find out which string is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order.
A string is greater than another if it comes after the other in dictionary order.
int compareTo(String str)
str is the String being compared with the invoking String.
The results havre the following meanings :
1.Less than zero The invoking string is less than str.
2. Greater than zero The invoking string is greater than str.
3. Zero The two strings are equal.
We can also do the comparison without having the case sensitivity been applied by
compareToIgnoreCase( ),
int compareToIgnoreCase(String str)
This method returns the same results as compareTo( ), except that case differences are ignored.
9. Searching Strings
We can search a string for a specified character or substring with the below mentioned tow methods:
■ indexOf( ) it will Search for the first occurrence of a character or substring.
int indexOf(int ch)
■ lastIndexOf( ) it will Search for the last occurrence of a character or substring.
int lastIndexOf(int ch)
ch is the character being sought.\ in both the above written statements.
To search for the first or last occurrence of a substring, use int indexOf(String str)
int lastIndexOf(String str)
str specifies the substring.
10. Modifying a String
as it was mentioned earlier too that whenever we waqnt to modify a string we must create a copy with the help of Stringbuffer and then do the modifications.
a. substring( )
A substring can be extracted using substring( ). It has two forms.
1. String substring(int startIndex)
startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.
2. substring( ) allows you to specify both the beginning and ending index of the substring:
String substring(int startIndex, int endIndex)
startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
Give Example.
b. concat( )
This method helps to concatenate two strings using concat( ), the syntax is :
String concat(String str)
This method creates a new object that contains the invoking string with the contents of str appended to the end. It actually does the same function as +.
For example
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
c. replace( )
This method replaces all occurrences of one character in the invoking string with another character. It’s syntax is :
String replace(char original, char replacement)
original specifies the character to be replaced by the character specified by replacement. The resulting string is returned.
For example,
String s = "India".replace('l', 's');
puts the string “sndsa” into s.
d. trim( )
This method is used to get the same copy of the string after deletions of the white space if nay exists. The syntax for this is :
String trim( )
For example:
String s = " Java language ".trim();
This puts the string "Java language" into s
11. String Buffer:
As we have been discussing about the facility provided by String Buffer to represent the characters in java in a growable and modifiable manner. It makes very convenient to the programmers to modify or play around over the strings with the help of String Buffer.
StringBuffer defines these three constructors:
1. StringBuffer( )
2. StringBuffer(int size)
3. StringBuffer(String str)
String buffer ( ) reserves room for 16 characters without reallocation.
StringBuffer( int Size) accepts an integer argument that explicitly sets the size of the buffer.
StringBuffer ( String Str) accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.
1. append( )
This method as name defines is used to concatenate the string representation of any other type of data to the end of the invoking StringBuffer object.
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
First String.valueOf( ) method is called for each parameter to obtain its string representation and then the result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ).
2. charAt( ) and setCharAt( )
This method provides us with the value of a single character from a StringBuffer
char charAt(int where)
where specifies the index of the character being obtained.
We can set the value of a character within a StringBuffer using setCharAt( ).
void setCharAt(int where, char ch)
where specifies the index of the character being set, and ch specifies the new value of that character.
3. delete ( ) and deleteCharAt( )
These two methods can be used to delete the characters from a stringBuffer., their syntaxes are shown below as :
StringBuffer delete(int startIndex, int endIndex)
The delete ( ) method deletes a sequence of characters from the invoking object. startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted
runs from startIndex to endIndex–1. The resulting StringBuffer object is returned.
StringBuffer deleteCharAt(int loc)
The deleteCharAt( ) method deletes the character at the index specified by loc.
It returns the resulting StringBuffer object.
4. ensureCapacity( )
This method is used to set the size of buffer after it has been constructed. Its syntax is :
void ensureCapacity(int capacity)
where, capacity specifies the size of the buffer.
5. getChars( )
This method is used to copy a substring of a StringBuffer into an array, Its syntax is void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) sourceStart specifies the index of the beginning of the substring, and sourceEnd
specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. of characters in the specified substring.
6. insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. Few of the forms in which it can be implemengted are :
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.
7. length( ) and capacity( )
length ( ) method is used to find the length of a StringBuffer and , its total allocated capacity can be found with capacity( ) method. Their syntax is:
int length( )
int capacity( )
8. replace ( )
This method replaces one set of characters with another set inside a StringBuffer object. Its syntax is:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. And returned as an object.
9. reverse( )
We can reverse the characters within a StringBuffer object using reverse( ), its syntax is :
StringBuffer reverse( )
10. setLength( )
This is used to set the length of the buffer within a StringBuffer object, its syntax is :
void setLength(int len)
where, len specifies the length of the buffer. This value must be nonnegative.
11. substring( )
It returns a portion of a StringBuffer. Its syntax is
String substring(int startIndex)
It returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object.
String substring(int startIndex, int endIndex
It returns the substring that starts at startIndex and runs through endIndex–1
|