Strings Strings represents a sequence of charcters Ex: char Name[]= new char[5]; Name[0]=‘r’ Name[1]=‘a’ Name[2]=‘j’ Name[3]=‘a’ Name[4]=‘h’ In java strings are class objects implemented by two classes 1. String class and 2. StringBuffer class String class is used to create strings of fixed length And StringBuffer class creates strings of flexible length which can be modified in terms of length and content
strings A java string is an instantiated object of String class A java string is not a character array and it is not Null terminated. A string can be created as follows String stringname ; stringname = new String(“string”); Ex: String collegename ; collegename = new String(“Rajah college”);
strings Like arrays we can find the length of a string by using length() method. Ex: int length= collegename.length (); length=13 Java strings can be concatenated using “+ “ operator ex: String strin1=“rajah” String string2=“college” String string3= string1+string2; string=“ rajahcollege ”
Srings String arrays: We can also creat arrays that contain strings. String names[]=new String[3]; String methods: s2=s1.toLowerCase Converts the string s1 to all lower case s2=s1.toUpperCase Convers the string s1 to all Upper case
STRINGS s2=s1.replace(‘x’ , ‘y’) Replaces all the appearance of ‘x’ with ‘y’ s2=s1.trim() Removes the white spaces at the beginning and end of the string s1. s1.equals(s2) Returns true if s1 is equal to s2 s1.equalsIgnoreCase(s2) Returns true if s1 is equal to s2 by ignoring case s1.length() Returns the length of the string s1
STRINGS s1.charAt(n) It returns the character at positon s1.compareTo(s2) Returns true if s1<s2, positive if s1>s2 and zero if s1=s2 s1.concate(s2) Concatenates s1 and s2
STRINGS s1.subString(n) Give s a substring starting from nth character s1.subString( n,m ) Gives a substring starting from nth character upto mth not including mth character. s1.indexOf(‘x’) Gives the postion of first appearance of x in string s1 s1.indexOf(‘ x’,n ) Gives the first appearance of ‘x’ after nth position in string s1
StringBuffer class StringBuffer class is used to create strings of flexible length. Strings that are created by using StringBuffer class can be modified both in terms of length and content. Ex: StringBuffer str = new StringBuffer (“object language”) StringBuffer class methods: s1.setCharAt( n,’x ’) Modifies the nth character to x. s1.append(s2) Appends the string s2 to the end of s1
StringBuffer class s1.insert(n,s2) Inserts the string s2 at the postion n of the string s1 s1.setLength(n) Set the length of the string s1 to n. If n<s1.length() S1 is truncated. If n>s1.length(). Zeros are added.