Sunday, 13 March 2016

Java String Class and its methods

String Class and its methods:-

Q what is string?
ans-String is nothing but a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and can cannot be changed once it has been created. 

Creating a String

There are two ways to create a String in Java
  1. String literal
  2. Using new keyword

Difference between string object and string literal  :


  • Whenever you call new() in JAVA it create an object in heap.
  • String literals will go into String Constant Pool.
  • For objects JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area.
  • Example program:
  1. public class StringCreationDemo {     
  2.                                                                                   
  3. public static void main (String args[]) {
  4.  
  5.     String str1 = "Hello"; 
  6.     String str2 = "Hello";
  7.  
  8.     System.out.println("str1 and str2 : literal");   
  9.     System.out.println("str1 == str2 is " + (str1 == str2)); 
  10.  
  11.     String str3 = new String("Hello"); 
  12.     String str4 = new String("Hello");
  13.  
  14.     System.out.println("str3 and str4 : new operator");   
  15.     System.out.println(" str3 == str4 is " + (str3 == str4)); 
  16.  
  17.     String str5 = "Hel"+ "lo"; 
  18.     String str6 = "He" + "llo";
  19.  
  20.     System.out.println("str5 and str6 : expression.");   
  21.     System.out.println("    str5 == str6 is " + (str5 == str6)); 
  22.  
  23.   }
  24. }  
Q-what is string literal?
ans-string literal is collection of reference to string object.
example:-if we define same content two different object, it refer to same object in string pool.
String str1="welcome"; 
String str2="Welcome";

Using New Keyword:-

but using new keyword if we create two object using new keyword than it refer to two diffrent object

when we tried to assign the same string object to two different literals, compiler only created one object and made both of the literals to point the same object. To overcome that approach we can create strings like this:
example:-
String str1 = new String("Welcome");
String str2 = new String("Welcome");
In this case compiler would create two different object in memory having the same text.

Why Strings are immutable in java?

ans:-Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "welcome".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
example:-all wrapper class are example of string immuatable 
Advantage:-to improve the heap memory.
String is immutable for several reasons:-
1-requirement of string pool:-
2:-Security
3:-Synchronization:-
4:-Caching:-

1. Requirement of String Pool.

The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
Here is how it looks:
java-string-pool
2. Security
String is widely used as a parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to a serious security threat
Here is a code example:
boolean connect(string s){
    if (!isSecure(s)) { 
throw new SecurityException(); 
}
    //here will cause problem, if s is changed before this by using other references.    
    causeProblem(s);
}

3-Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminates the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.
4.Caching Hashcode
Q- how to make immutable class?
ans:-1:- decalare the class as a  final so subclass we should not modify,
             2:-declare the variable firstname as private last name as a final.


============String Methods=========

  1. char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.
  2. boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
  3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison
  4. int hashCode(): It returns the hash code of the string.
  5. int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
  6. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
  7. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
  8. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
  9. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
  10. int indexOf(String str): This method returns the index of first occurrence of specified substring str.
  11. int lastindexOf(String str): Returns the index of last occurrence of string str.
  12. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
  13. String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
  14. String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
  15. String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
  16. String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
  17. String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
  18. String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.
  19. String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
  20. String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
  21. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
  22. String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.






No comments:

Post a Comment