String:

  • Series of characters is known as string.
  • String is final class in java.
    public final class String
    extends Object
    implements Serializable, Comparable<String>, CharSequence.
  • We can create a String object in two ways.
  • 1. By using new operator
        String str= new String("Java");
    2.By using String literal.
       String str= "Java".

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, they introduced String constant pool. One of important characteristic of String constant pool is that it does not create same String object if there is already String constant in the pool.
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. }  

                                                                      
      
Output:


  1. str1 and str2 : literal 
  2. str1 == str2 is true. 
  3. str3 and str4 : new operator str3 == str4 is false. 
  4. str5 and str6 : expression 
  5. str5 == str6 is true.

       
                                                                                                                                        

String is immutable. What exactly is the meaning??

  • String is immutable means that you cannot change the object itself, but you can change the reference to the object. 
  •  String a="a";
           a = "str";
  • When you called a = "str", you are actually changing the reference of a to a new object created by the String literal "str". 
  • Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods)
  • String str="smiley";
    str=str+"bird";
    here new String object will be created.

Why Strings are immutable in java?

  • Security: Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

How to prove Strings are immutable?


  1. package com.instanceofjava;
  2.  
  3. public class StringImmutableDemo {
  4. public static void main(String[] args) {
  5.  
  6. String s1="Java";
  7. String s2 = "Rocks!";
  8.  
  9. System.out.println("The hascode of s1 = " + s1.hashCode());
  10. System.out.println("The hascode of s2 = " + s2.hashCode());
  11.  
  12. s1=s1 + s2;
  13.  
  14. System.out.println("The hascode [AFTER] s1 is changed = " + s1.hashCode());
  15.  
  16. }

 Output:


  1. The hascode of s1 = 2301506
  2. The hascode of s2 = -1841810349
  3. The hascode [AFTER] s1 is changed = 1248336149

String class constructors:

  • String class has 8 important constructors.

1.String():

  • Creates empty string object.

2.String(String value):

  •  Creates String objects with the string value

3.String(StringBuffer sb):

  • Creates String object with the given StringBuffer object.

4. String(StringBuilder sb):

  • Creates String object with the given StringBuilder object.

5.String(char[] ch):

  •  Creates String object  with the given array values.

6.String(char ch, int offset, int count):

  • Creates String object with the given array values start with offset by including with the  given count of characters.

7.String(byte[] b):

  • Creates String object with the given byte array values.

8.String(byte[] b, int offset, int count):

  • Creates String object with the given byte array values starts with offset by including with the given count of bytes

String methods:

1.isEmpty():

  • This method used to check whether String is empty or not

 2.length():

  • To find the length of given string.
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{
  3. public static void main (String args[]) {
  4. String str="";
  5. System.out.println(str.isEmpty()) ;
  6. System.out.println(str.length());
  7. }
  8. }
  9. Output: 
  10. true
  11. 0

3.equals();


  • To compare two strings

4.compareTo():

  • To Compare two string objects lexicographically, means after comparison method should return difference between string content

5.compareToIgnoreCase():

  • To Compare two string objects lexicographically, means after comparison method should return difference between string content ignores case.
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{
  3. public static void main (String args[]) {
  4. String str1="abc";
  5. String str2= new String("abc")
  6. System.out.println(str1.equals(str2)) ;
  7. String str3="a";
  8. String str4="A";
  9. System.out.println(str3.compareTo(str4)) ;
  10. String str5="a";
  11. String str6="A";
  12. System.ot.println(str3.compareToIgnoreCase(str4)) ;

  13. }
  14. }
  15. Output: 
  16. true
  17. 32
  18. 0

6.7. startsWith(), endsWith():

  • To check whether the string starts with specified string or ends with specified string
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java programming language";
  5. System.out.println(str1.startsWith("Java"));
  6. System.out.println(str1.endsWith("java"));

  7. }
  8. }
  9. Output: 
  10. true
  11. false

8.charAt(int index);

  • To find character at given index
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java";
  5. System.out.println(str1.charAt(1));
  6. System.out.println(str1.charAt(3));

  7. }
  8. }
  9. Output: 
  10. a
  11. a

9.indexOf(char ch):

  • Returns first occurrence of  given character
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java";
  5. System.out.println(str1.indexOf("J"));
  6. System.out.println(str1.indexOf("B"));

  7. }
  8. }
  9. Output: 
  10. 0
  11. -1



Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

1 comments for Java String

Select Menu