Showing posts with label String tutorial. Show all posts
Showing posts with label String tutorial. Show all posts

Monday, November 7, 2016

Why String is Immutable in Java

Java Designer knows String is going to be most used data type in all kind of java applications. Therefore they want optimize from start. Here,mutable objects are those objects whose contents can be modified whereas immutable objects can not be modified. In java String class objects are immutable that means once we create String objects we are not allowed to perform any changes in the existing object. If you are trying to perform any changes a new String object will be created this behavior is nothing but immutability  of the string object.

The fallowing are the several benefits of String because it's immutable and final:


  1. It increases security because any hacker can not change it's value and it is used for storing sensitive information such as database username and password etc..
  2. Since String is immutable,it is safe to use in multithreading and we do not need any synchronization .
Importance of String Constant Pool(SCP):

In our program if any string object is repeatedly going to use, we can create only one object in the String Constant Pool and shared by several required references. The main purpose of SCP is instead of creating several string objects with the same content creating only one object improves the performance of the system and memory utilization also.

As the several references pointing to the same object in SCP by using one reference if you are allowed to change the content the remaining references may be effected. Hence,once we created a String Object we are not allowed to change it't content. If you are trying to change with those changes a new object will be created and there is no impact on the remaining references. This behavior is nothing but immutability of String object. SCP is only reason why the string objects are immutable.


Let us take a program to understand whether the string objects are immutable or not

class Demo
{
public static void main(String args[])
{
String s1="java";
String s2="program";
s1=s1+s2;
System.out.println(s1);
}
}

Output:




Observe, the output of the program is "javaprogram". It seems that s1 content is modified. Earlier s1 holds "java" and s2 holds "program". after s1+s2 joined and the total string becomes "javaprogram". This total string assigned to s1 again.That means s1 is mutable. But we said that String objects are immutable.

Do not hesitate String objects are definitely immutable. You people thinking about the output of above program. I will give clarity about it now. In that program, JVM create two objects s1 and s2 separately like below program. When s1+s2 done,JVM creates a new object and stores the string "javaprogram" in that object. But it doesn't modify the content of string s1. After creating the new object, the reference s1 is refer to that new object. We should notice one thing here the contents of the string s1 are not modified. Therefore,strings are immutable.





Since String class objects are immutable,their contents can not be modified between various applications. Thus,different applications can share the contents of String class objects.

Why String object is final:

Whenever we try to modify the contents, JVM will create a new object with modified data. It will not modify the same object, also there should not be any scope to override those string class methods. This is the reason String class if 'final' class. The methods of final class can not be overridden.

For More details about Final class: Final keyword in java

Tuesday, November 17, 2015

String handling in java

String:

  • String is nothing but sequence of characters
  • An array of characters works same as java String
For Example:  "luckysir" is a String of 8 characters
  • In java, String is immutable object  
  • immutable means it is constant and can not be changed once it has been created.
  • Once we created String objects we are not allowed to perform any changes in the existing object
  • If you are trying to perform any changes with those changes a new string  object will be created this behavior is nothing but"immutable" of the string object

Creating a string:                                          

                                                                                      
There are two ways  to create a String in java:           

a)String literal
b)using new keyword

a) String literal:
java String literal is created by using double quotes.

Example:

String s1="lucky";
String s2="lucky";//will not create new object 

  • In the above example, only one object will be created
  • First time JVM will not find any string object with the value "lucky"in string constant pool
  • so it will create a new object. After  that it will find a with the same value "lucky"in the pool
  • It will not create a new object but will return reference to the same instance

Important Note:

String objects are stored in a special memory area known as string constant pool

b) using new keyword:

 Ex:  String s=new String("lucky");

  • In the above example, two objects will be created one is on heap and another one is on string constant pool(SCP) and 's' is referring to heap object  
                                        



  • object creation in SCP is optional
  • If the object is not available then only new object will be created
Note:      

  • The object present in the SCP is not eligible for garbage collection even though the object does not have any reference variable
  • All the SCP objects will be destroyed at the time of JVM shutdown

Important methods of String class:

charAt():

  The java String charAt() method returns a char value at the given index number.
   the index number start from 0.

Syntax:
    public char charAt(int index);

    Ex:  String s="lucky";
            System.out.println(s.charAt(2));// returns the char value as'c'
            System.out.println(s.charAt(8));// StringIndexOutOfBoundException

Concat():

The java String Concat() method combines specified string at the end of this string.
It returns combined string. It is like appending another string

Syntax:
public String Concat(String s);

 Ex:   String s="lucky";
          s1=s.concat("sir");
          System.out.println(s1);// returns string as luckysir


equals():

The java string equals()method compares two given strings based on the content of the string.If any character is not matched it returns false,if all characters are matched it returns true.

Syntax:
public Boolean equals(Object o);
    


 Ex:   

public class EqualsTest{
public static void main(String args[]){
String s="luckysir";
String s1="luckysir";
String s3="LUCKYSIR";
String s4="java";
System.out.println(s1.equals(s2));//return true because content and case is same
System.out.println(s1.equals(s3));//return false  because case not the same
System.out.println(s1.equals(s4));//return false because content not the same
}
}
}

equalsIgnoreCase():

Syntax:
public Boolean equalsIgnoreCase(String s);


Ex:   String s="lucky";
         System.out.println(s.equalIgnoreCase("LUCKY")); // return True

Note:  Usually for validating username(where case sensitive not important method, we can use equlsIgnorecase) but for validating password we can use equals method where the case is important.
  
                
 length():
 The java string length()method  is used to find length of the string.

Syntax:

public int legnth(String s);

 Ex:    String s="lucky";
           System.out.println(s.length);//compile time error
           System.out.println(s.length());//5

NOTE:  length is the variable applicable for array object, length() is method applicable for string object

Replace():

The java string replace()method returns a string replacing old string to new string(charsequence or char)

Syntax:
public String replace(char old, char new);

Ex:

String s="ababa";
System.out.println(s.replace('a','b'));

Output:
 bbbbb

SubString():

The java string subsring() method returns a part of the string.

Syntax:
public String substring(int begin);

Ex 1:  
String s="lucky";
System.out.println(s.substring(3));// return ky
public String substring(int begin,int end);

Ex 2:    
String s="luckysir";
System.out.println(s.substring(2,5));//cky

toLowerCase():
The java string toLowerCase()method returns the string in lower case letters.

Syntax:

public String toLowerCase();

Ex:  String s="LUCKYSIR";
        String lower=s.toLowerCase();
        System.out.println(lower);


toUpperCase():
The java string toUpperCase()method returns string in uppercase letters.

Syntax:

public String toUpperCase();

Ex:  
String s="luckysir";
String upper=s.toUpperCase();
System.out.println(upper);

trim():

It removes blank spaces present at starting and ending of the string.

But not middle blanks.

Syntax:
public String trim();

Ex:
String s="  lucky sir";
System.out.println(s.trim());//lucky sir


indexOf():
It returns index of given character value or substring
if it is not found it returns -1.

Syntax:
 public int indexOf(char ch);

// returns first occurrence of index

 public int lastIndexOf(char ch);
 // returns last occurrence of index



Recommended to Read:

                          


              

             





      

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...