String is a set of characters. Java provides a class named “String” to handle strings. The “String” class has several built-in functions to support different operations on strings. Though String is a class, the instantiation of the objects need not be done using the keyword ‘new’. The string value can be directly assigned to String object. A java String is not a character array and it is not terminated by null character.
String can be initialized in many ways.
· String s1 = “Apoorva”;
· String s2 = new String(“Ramu”);
· String s3 = new String(new char[] {‘a’,’b’,’c’});
Here, the argument could be any character array. s3 will have “abc”.
· String s4 = new String(new byte[] {65,66,67});
Here, the argument could be any byte array. s4 will have “ABC”.
Another important point to be remembered is String objects are not mutable (self-changeable) i.e. when you perform some kind of manipulation using methods the value will not be changed but the Object what it returns may have the modified string. For example, the following code will not convert ‘s1’ to upper case. But ‘s2’ will have the upper-case string.
String s1 = “abcd”
String s2 = s1.toUpperCase()
To find out the string length, we use length() method of String class .
int length = s1.length();
It is also possible to write set of strings (array of strings) as follows
String s[]={ “amar”, “kiran”, “ravi”, “ramu”};
To print all the strings we write
for (i=0;i<4;i++)
System.out.println(s[i]);
0 comments:
Post a Comment