Part 2
String Handling
When you creating a string object that you are creating a string that cannot be deleted.
And Java has a method to compare two strings and concatenate two strings and change the case of letters with the string.
In the programming,Java a string is a sequence of characters.
New string object has contain the modifications and in some cases the fixed string is used.
So the Java define two types as StringBuffer and StringBuilder
The String,StringBuffer and StringBuilder are these classes defined in java.lang package.
From here all the classes are used and then then final statement describes the no more subclasses are used.
String class provides several constructors.To create a string
When you creating a string object that you are creating a string that cannot be deleted.
And Java has a method to compare two strings and concatenate two strings and change the case of letters with the string.
In the programming,Java a string is a sequence of characters.
New string object has contain the modifications and in some cases the fixed string is used.
So the Java define two types as StringBuffer and StringBuilder
The String,StringBuffer and StringBuilder are these classes defined in java.lang package.
From here all the classes are used and then then final statement describes the no more subclasses are used.
The string Constructors:
- The string class supports several constructors.To create a empty string call that default constructor.
Eg; String s = new String();
You will want to create strings that have initial values.
The String class provides a variety of constructors to handle this.
To create a String initialized by an array of characters use the constructor as,
String(char chars[],int startindex,int numchars)
StartIndex specify the index specify at which subrange begins and numchars specify the number of characters use it.
Javas Char types uses 16 bit byte code but string on internet uses 8 bit type.In these constructor byte to character conversion is done by default character.
Example;(ASCII to char):
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
You can construct a string from a StringBuffer by using constructor as,
String(String Buffer strBufObj)
You can construct a string from a StringBuilder by using constructor as,
String(String Builder strBuildObj)
String Length: The length of the string is the number of characters that it contains.To obtain these value call the length method as
int length()
Special String Operations:
- String are common and important in part programming.java has added a special feature as support for several string operations within the syntax of language.
These operations include new string instances into string literals and concatenation of multiple strings by using + operator.
Conversion of other data types into a string representation.And Java helps us to change all the conversions automatically so it helps the user.
String Literals:
For each string literal in program the java automatically construct the string object.And string literals are used to initialize the string object.
You can use string instance to initialize a string object.Thus the fragments are
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
And we can the length method of the string as,
System.out.println("abc".length());
String Concatenation:
Generally java not allow any operator in string objects except + operator it concatenates two strings producing a string object as a result.
For the long string example are
Examples:
// Using concatenation to prevent long lines.
class ConCat {
public static void main(String args[]) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
}
}
- The output are This could have been a very long line that would have wrapped around. But string concatenation prevents this.
String Concatenation with other Data Types:
Examples:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
In this case, 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.Be careful when you mix other types of operations with string concatenation expressions, You might get surprising results as
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays four: 22
- If you use a parenthesis as then output will change
String s = "four: " + (2 + 2);
System.out.println(s);
This fragment displays four: 4
String Conversion and toString();
For objects, valueOf( ) calls the toString( ) method is used to change data into string representation.In toString() determine the representation of classes of objects.
The toString( ) method has this general form:
String toString()
To implement toString( ), simply return a String object that contains the human-readable
String that appropriately describes an object of your class.
Examples:
// Override toString() for Box class.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions are " + width + " by " +depth + " by " + height + ".";
}
}
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}
- As you can see, Box’s toString( ) method is automatically invoked when a Box object is used in a concatenation expression or in a call to println( ).
Character Extraction:
- The String class provides a number of ways in which characters can be extracted from a String object.In array the string index begins at zero.
CharAt():
To extract a single character from a string you can refer directly to an individual character.
It has a general form as
char charAt( int where)
where is the index of the character .And value of where must be non-negative and specify the location of string.
CharAt() returns the character at specified location.
getChars();
More than one string is extracted in string object is called getchars().
In these general form:
(int SourceStart,int SourceEnd,char Target,int targetStart)
SourceStart specify the starting of index on the subString and SourceEnd is the ending of index on the substring
Target will receive the array of characters of both sourceStart and SourceEnd.
TargetStart is the index at target will be copied in it.
getBytes:
- It is an alternative to getchar() that store the characters of an array.
- And it uses the default character to byte conversion and general form is
bytes getBytes()
- getBytes() are useful when exporting a string value into environment which not support a 16 bit unicode characters.
toCharArray():
If you want to convert all characters in string object into a character array.It returns the array of characters for the entire string.
The general form is,
char() to CharArray()
String Comparison:
The string includes the number of methods that compare the strings or substrings within strings.
Equals and EqualsIgnoreCase():
To compare two strings we use equality and its general form is,
boolean equals(object Str)
Here str is the string object being compared to the invoking object.
It returns the true if the string that contains same characters in the same order and otherwise false.
To perform a comparison that ignores case differences so call equalsIgnoreCase( ).
When
it compares two strings, it considers A toZ to be the same as a to z.It has this general form:
boolean equalsIgnoreCase(String str)
Regionmatches:
- Regionmatches() compares a specific region inside a string with another specific another region in another string.
- The general form are,
boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)
In these StartIndex specify the string starting point of the invoking object.
The String being compared to str2 And str2 being compare by Str2StartIndex.
- And then numchars specify the length of the substring being compressed.
Starts with() and EndsWith():
- It is same as Regionmatches() the startswith() determine whether a given string is begins with specified string.
- Endswith() specify the questions end with specified string.
- The example are
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo")
In above examples are both true.
A second form of startsWith( ), shown here, lets you specify a starting point:
boolean startsWith(String str, int startIndex)
Here, startIndex specifies the index into the invoking string at which point the search will
begin.For example:
"Foobar".startsWith("bar", 3)
returns true.
Equals() Versus==:
In these equals method and the ==operator performs two different operations.
And then Equals method compares the character inside the string object.
And the == operator compares the two object references to see whether the instances is same.
And the examples are
// equals() vs == class EqualsNotEqualTo { 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)); } }
The variable s1 refers to the String instance created by "Hello".
The object referred to by s2 is created with s1 as an initializer.
Thus, the contents of the two String objects are identical, but they are distinct objects.
This means s1 and s2 are not same as represent
Hello equals Hello => True
Hello == Hello => False
CompareTo():
- For sorting you must know which is greater than or less than next in the string.
- If String is lesser than the another it will come before in the dictionary order.
- If String is greater than the another it will come after in the dictionary order.
- Its general form is,
intCompareTO(String Str)
- These program uses CompareTo:
// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};
public static void main(String args[]) {
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];
424 PART II The Java Library
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
From these condition the uppercase comes first and then lowercase.
- In these state if u want to ignore the Now case,use the syntax as
int compareToIgnoreCase(String str)
- In that Now will be ignored.