String and StringBufferString and StringBuffer e examples.pptx
1.
String isa group 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 as final, so there cannot be subclasses of these classes. The default constructor creates an empty string. String s = new String(); confidentia 1 String
2.
Creating Strings confidentia 2 To Create a String in JA V A is String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data); If data array in the above example is modified after the string object str is created, then str remains unchanged. Construct a string object by passing another string object. String str2 = new String(str);
3.
String class Methods confidentia3 The length() method returns the length of the string. Eg: System.out.println("Varun".length()); // prints 5 The + operator is used to concatenate two or more strings. Eg: String myName = "Varun"; String s = "My name is" + myName+ "."; For string concatenation the Java compiler converts an operand to a String whenever the other operand of the + is a String object.
4.
String class Methods(Contd.). confidentia 4 Characters in a string can be retrieved in a number of ways public char charAt(int index) Method returns the character at the specified index. An index ranges from 0 to length() – 1 char c; c = "abc".charAt(1); // c = “b”
5.
String class Methods(Contd.). confidetial 5 equals() Method- This method is used to compare the invoking String to the object specified. It will return true, if the argument is not null and it is String object which contains the same sequence of characters as the invoking String. public boolean equals(Object anObject) equalsIgnoreCase() Method- Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case. public boolean equalsIgnoreCase(String anotherString)
6.
Strings created usingassignment operator String s1 = “HELLO”; String s2 = “HELLO”; HELLO 3e25a e s1 3e25a e s 2 confidentia 6
7.
Comparing Strings using== operator What is the output ? public class StringTest{ public static void main(String[] args){ String s1="Hello"; String s2="Hello"; if(s1==s2) System.out.println("String objects referenced are same"); else System.out.println("String objects referenced are not same"); } } Output: String objects referenced are same confidentia 7
8.
Comparing Strings usingequals method What is the output ? public class StringTest{ public static void main(String[] args){ String s1="Hello"; String s2="Hello"; if(s1.equals(s2)) System.out.println("Strings are equal"); else System.out.println("Strings are not equal"); } } Output: Strings are equal confidentia 8