Strings
Output :
- Strings in java are objects of class string.
- The String class is a standard class that comes with Java.
- String class is defined in java.lang package.
- A String literal is a sequence of characters in double quotes.
- Example : "Smell Tea for a better taste".
- Like for characters which cannot be entered directly from keyboard we use escape sequences in String Literals as well.
- Strings are stored internally as Unicode characters.
- A string variable only stores a reference to the object of class String.
- String mystring="This is a main String".
- This creates a String object with reference to mystring and initialises the same with "This is a maiden String".
- String objects are immutable i.e. they cannot be changed.This means that you cannot extend or otherwise modify the String that an object of type String represents.
- Whenever we perform operation on existing String objects we end up creating a new String object out of the same.
- If characters are represented as surrogates they may occupy 4 bytes in a String per character.
- You cannot leave a String variable only declared you must define it to a value if you do not want to use it now define it to "Null".
- String anyString; //Will give you an error.
- String anyString=null; //Will not give you an error.
- Literal "Null" is an object reference value that does not refer to anything.
- We can test weather a String variable refers to anything or not by a statement such as
- if(anyString==null)
- {
- System.out.println("This has no reference");
- }
- To discard a String object simply refer it to null
- String[] names=new String[5];
- This statement creates an array of String objects.
- We have seen earlier that how argument of the main method an array of Strings takes arguments from console.
Joining Strings
- We use "+" operator to join 2 strings and form a new String.
- This operation generates a completely new String Object that is separate from the two original String objects.
- If any operand is String the compiler converts the other operand into String and performs the merge operation.
- If a String object contains "null" then it is converted into String "null".
- The conversion of values of the basic types to type String is actually done by a static method "toString()".
- String class contains a method called as valueOf() which converts a primitive type to String.This is again a static method.
- The expression String 1 == String 2 checks whether 2 String variables refer to same String.
- To Compare two String variables we use equals method.
- Example string1.equals(string2) compares 2 objects of type String and check whether they are equal or not.
- To check equality of 2 String ignoring case of String characters, we use equalsIgnoreCase().
- String interning ensures that no two String objects encapsulate the same String.So all String objects encapsulate unique Strings.
- This means that if two String variables refer to Strings that are identical, the reference must be identical too.
- Whenever we create a new String we just call the intern() method.
- intern() method checks the String of caller object against all the String objects currently in existence.If a reference exists then current String object is discarded and caller object will contain reference to existing object encapsulating same String.
- All the String constants and constant String expressions are automatically interned.
- Any String object explicitly defined is automatically interned.Only String expressions involving reference to String variables need to be interned.
- String str4="This is a cat"; - will be automatically interned.
- String myString3=myString2.substring(0,23); - needs to be interned.
- startsWith()
- str4.startsWith("This");
- checks whether the String starts with a sequence.
- is case sensitive
- endsWith()
- str4.endsWith("Cat");
- compareTo()-checks weather one String is greater than or less than another.
- Compares the String object for which it is called to a String argument and returns an integer.
- It is negative if String object is less than argument.
- It is positive if String object is greater than argument.
- It is zero if String object is equal to the argument.
- It compares the String by comparing successive corresponding characters starting with each character in String.
- Characters are compared by comparing their Unicode representations.
- One String is greater than another if the first character that differs from the corresponding character in the other String is greater than the character in corresponding String.
- Extracting String characters is done using charAt();
- Accepts integer argument that is the offset of the character position from the beginning of the String.
- If the index is less than zero or greater than the index for last the last position in the String an exception is thrown
- "StringIndexOutOfBoundsException"
- Two methods
- indexOf();
- lastIndexOf();
- Searching character - indexOf() will search the contents of String text from the beginning and return the index position of the first occurrence of character from beginning of String.
- If String is not found - 1 is returned
- If we want to find the last occurrence of a character in String we use method lastIndexOf();
- This method searches the String backward starting with last character in String.
- To find the index of another character of first character use the following
- bIndex=text.indexOf("b",++aIndex);
- where aIndex is the Index of occurrence of first character.
- You must check for a Index to be not equal to -1 in this case.
- Count the occurance of Character in String can be accomplished using
- while((aIndex=text.indexOf('a',++aIndex))>-1){++count;}
- The indexOf() and lastIndexOf() methods also come in versions that accept a string as the first argument, which will search this String rather than a single character.
- Substring() method is used to extract a substring from a string.
- String place = "Java Implant".
- String lastWord=place.substring(5);
- This will return the last word "Implant".
- Substring(5,1) will return characters that starts from 5th position till 1st position from this position.
- An exception is thrown if index is outside the bounds of the String.
- Split method is for splitting a String into tokens.
- Regular Expressions are used for splitting a String.
- The split() method expects two arguments.
- The first argument is a String object that specifies a pattern for delimiter.
- The second argument is an integer value that is an integer value that is a count of the maximum number of times the pattern can be applied to find tokens.
- This affects the maximum number of tokens that can be found.
- The tokens returned by String method are an array of type String[].
Modifying String Objects
- String objects are immutable so each of its member functions provide or return a new String object.
Replacing characters in a String
- replace() - replace() function replaces a character throughout a String with another.
- String newtext=text.replace(' ','/');
- first argument specifies character to be replaced.
- Second argument specifies character to be substituted.
- The object returned is a new String object.
- trim() - removes whitespaces from end and beginning of a String.
Creating a character Array from String
- toCharArray() - creates a character array from a String object.
- returns an array of characters that constituted String in sequential order.
- We can also extract substring as an array of characters using the method getChars();
- Four arguments are
- the index position of first character
- the index position of last character
- Name of the array to hold characters extracted(type char[])
- index of the array to hold the first character(type int)
- text.getChars(9,12,textArray,0);
- Text Array must be large enough to hold the characters.
- We can iterate a String using chars in a collection based for loop.
- for(char ch:str.toCharArray()){}
- Here str is a string.
- getBytes() is used to get the characters in a String as Array of bytes.
- byte[] textArray=text.getBytes();
- copyValueOf() method is used to create String object from an array of characters.
- This is a static method and can be used as
- String text=String.copyValueof(textArray);
- This can also be achieved by creating a new String object and initialising the same using an array of characters.
- String text = new String(textArray);
- copyValueOf function can also be used as
- String text=String.copyValueOf(textArray,9,3);
- Similarly we can use constructor
- String text=new String(textArray,9,3);
- There are two classes for Mutable Strings
- String Builder
- String Buffer
- Strings that can be changed are called as mutable strings.
- String Buffer class is used internally to perform many operations on Strings.Once we have the required String we convert it to object of type String.
- String Buffer objects are safe for use by multiple threads, where as String Builder objects are not.
- Threads are independent execution processes within a program that can execute concurrently.
- e.g. an application that involves acquiring data from several remote sites could implement data transfer from each remote site as a separate thread.
- For concurrent thread operations we use String Buffer class object i.e. where one thread is trying to access object while other is trying to modify the same.
- If our mutable String object will be accessed by only a single thread then we should use String Builder Objects.
- StringBuffer aString=new StringBuffer("Golden Eggs");
- We cannot directly initialise a String Buffer object as in case of String.
- We can also create a String Buffer object using a reference stored in variable of type String.
- StringBuffer buffer =new StringBuffer(String object);
- To set a String Buffer object to null use
- StringBuffer obj=null;
- StringBuffer contains a block of memory called as "buffer".
- This may or may not contain String
- So the length of the String a StringBuffer object contains is different from the length of the buffer that the object contains.
- The length of the buffer is referred to as the capacity of the String Buffer object.
- Once you create a StringBuffer object, you can find the length of the String it contains, by using length() method.
- When we create a StringBuffer object the capacity is the length of the String + 16 bytes.
- The capacity grows automatically as we add to the String to accommodate a String of any length.
- You can also specify an initial capacity when we create an object e.g.
- StringBuffer newString=new StringBuffer(50);
- The default capacity of String Buffer object is 16 characters.
- To find out capacity of a String Buffer object at any given time use capacity() method.
- Ensure capacity() enables you to change the default capacity of a StringBuffer object.
- We can change the length of a String Buffer using setLength();
- If the length is reduced the letters chopped off are lost.
- If we set the length greater than capacity is increased to a value twice the original capacity plus two.If the length is still greater than the new capacity will be same as length you set.
- If you specify a negative length we get a StringIndexOutOfBoundsException().
Adding to StringBuffer object
- String aString=new StringBuffer("Time is rare");
- aString.append("don't spare");
- .append() method enables you to add a String to the end of the existing String stored in StringBuffer object.
- The length of the String contained in StringBuffer object is increased by the length of the String that you add.
- The capacity is automatically increased whenever we try to accommodate a longer String.
- append("") method returns reference to an extended StringBuffer object.
- Another version of the append() method adds part of a String object to a StringBuffer object.
- This version of append() requires you to specify two additional arguments
- Index position of first character in String object that is to be appended.
- Total number of characters to be appended.
- StringBuffer buf=new StringBuffer("Ok");
- String sappend="Then its fine";
- buf.append(append,0,4);
- The capacity of StringBuffer object is automatically increased by the length of the appended Substring.
- We have set of versions of append() method that will enable you to append the String equivalent of values of following primitive types: boolean, char,byte,short,int,long,float and double.
- In each case the value is converted to a String equivalent which is then appended to the object.
- Append may take boolean which is appended as "True" or "False".
- Append may take char array the contents of array are appended to the String Buffer object as a String.
- lastIndexOf() method - The simpler of the two versions of this method requires just 1 argument i.e. String we are looking for.
- This method returns the last position of the occurrence of String you are searching for as a value of type Int.
- method returns -1 if substring is not found.
- second version is
- position=str.lastIndexOf("substr",3);
- This statement starts teaching from position 3.
- replace() method is used
- 3 arguments are required
- first 2 are of type int and specify the start index in the buffer and one beyond the end index of the substring to be replaced.
- The third argument is of type String and is the String to be inserted.
- insert() method of the object is used to insert String into a StringBuffer object.
- First argument specifies the index position of the object where first character needs too be inserted.
- Second argument specifies the text to be inserted.
- Two methods can be used for this purpose
- charAt()
- getchars()
- Both these methods work in the same way as methods of String class.
- buf.setCharAt(3,'Z');
- buf.deleteCharAt(10);
- buf.delete(5,9)
- deletes characters between the first argument and (last argument -1) positions.
- Reverse function reverses a String.
- toString() - this method of StringBuffer class returns a String() object.
- String saying=proverb.toString)();
public class stringOps
{
public void checkNull(String str)
{
if(str==null)
{
System.out.println("This has no reference");
}
}
public void traceArray(String[] arr)
{
System.out.println("Players in Team are : ");
for(String str:arr)
{
System.out.println(str);
}
}
public void joinStrings(String str1,String str2)
{
System.out.println(str1+" "+str2);
}
public void compareStrings(String str1,String str2)
{
if(str1==str2)
{
System.out.println("Both Strings are same and belong to same object");
}
else
{
if(str1.equals(str2))
{
System.out.println("Both Strings are same but belong to different objects");
}
else
{
System.out.println("Both Strings are different");
}
}
}
public int checkCharacterOccurance(String str,char c)
{
int aIndex=-1;
int count=0;
while((aIndex=str.indexOf(c,++aIndex))>-1)
{
++count;
}
return count;
}
public static void main(String args[])
{
String myString="This is a maiden String"; //A reference to a new String is created
String nullString=null;
stringOps s1=new stringOps();
s1.checkNull(nullString);
//Array of Strings
String []players={"RG Sharma","S Dhawan","RR Pant","SK Raina","MK Pandey","KD Karthik","V Shankar","Washington Sundar","SN Thakur","JD Unadkat","YS Chahal"};
s1.traceArray(players);
String str1="Empty in String is represented as";
// Null String
s1.joinStrings(str1,nullString);
String myString1="This is a maiden String"; //A reference to a new String is created
String myString2="This is a maiden String copy";
String myString3=myString2.substring(0,23);
// compare Strings
s1.compareStrings(myString, myString1);
s1.compareStrings(myString, myString2);
s1.compareStrings(myString, myString3);
// Intern Example
myString3=myString3.intern();
s1.compareStrings(myString, myString3);
//Starts With
if(myString.startsWith("An"))
{
System.out.println("Second letter starts with a vowel");
}
else
{
System.out.println("Second letter does not start with a vowel");
}
//Ends With
if(myString2.endsWith("copy"))
{
System.out.println("Ends With Copy");
}
//character At
int pos=3;
char ch=myString1.charAt(pos);
System.out.println("Character at position "+pos+" is "+ch);
//Index of
ch='s';
pos=myString1.indexOf(ch);
int lpos=myString1.lastIndexOf(ch);
System.out.println("Position of "+ch+" is "+pos);
System.out.println("Last Position of "+ch+" is "+lpos);
//check Character Occurance
int inl=s1.checkCharacterOccurance(myString,'i');
System.out.println("Occurance of character is "+inl);
//Substring
String name="Java Implant";
String substr1=name.substring(5);
System.out.println(substr1);
String substr=myString.substring(10,16);
System.out.println(substr);
//Tokenizing a String
String [] nameArr=name.split(" ");
for(String str:nameArr)
{
System.out.println(str);
}
nameArr=myString.split(" ",3);
for(String str:nameArr)
{
System.out.println(str);
}
//Replacing characters
String text="There are a boy";
System.out.println(text);
text=text.replace("are","is");
System.out.println(text);
//Trim
String text1=" These whitespaces in a sentence needs to be removed ";
System.out.println(text1);
text1=text1.trim();
System.out.println(text1);
//Character Array
char [] textArray=new char[30];
textArray=text1.toCharArray();
for(char ch1:textArray)
{
System.out.println(ch1);
}
System.out.println("=================>");
char [] textArray1=new char[12];
text1.getChars(6,17,textArray1,0);
for(char ch1:textArray1)
{
System.out.println(ch1);
}
//String from array of chars
String halfString=new String(textArray1);
System.out.println(halfString);
//Array of Bytes from String
byte[] byteArray=halfString.getBytes();
for(byte b1:byteArray)
{
System.out.println(b1);
}
//StringBuffer
StringBuffer buffStr=new StringBuffer("Golden Eggs");
int len=buffStr.length();
int cap=buffStr.capacity();
System.out.println(len+" is length amd capacity is adding 16 to it i.e. "+cap);
//Increasing length of StringBuffer.
buffStr.setLength(40);
len=buffStr.length();
cap=buffStr.capacity();
System.out.println(len+" is length amd capacity is adding 16 to it i.e. "+cap);
}
}
No comments:
Post a Comment