Monday, 14 December 2015

STRING CLASS AND ITS METHODS IN JAVA..

INTRODUCTION:

      Hey folks..In this post I am going to explain about the String class and its methods in JAVA. Let’s jump directly into the post..
 
 

HOW TO CREATE A STRING IN JAVA..

        A String is nothing but Group of Characters. The ways in which a String can be created is using “Assignment Operator” and using “new” keyword .

        Java has an in-built “String class” . We all know a class can be accessed using objects, reference variable. 

     We will name it as a reference variable when “new” operator is not used. But when “new” operator is used we will call it as “object” . The ways of creating String in java are,

      Using Assignment operator, the syntax is,

      String s = “ hai “
      Here ‘ s ‘ is the variable and “hai” is the value we are storing inside the String “s”

HOW STORING WORKS FOR ASSIGNMENT OPERATOR..??

      For the above code, JVM creates an object and stores “hai “ in it. 

      Note that we are not using any new operator and we are using only “assignment operator” for creating this. 

     So, after creating the reference variable “s”, JVM uses separate block of memory called “String Constant pool “ where these reference variables are stored by JVM.

      If we use another line of code like,

       String s1= “hai”;

     Then , JVM will search if there is any objects with the same content holding..!! And Yea,, there is one such object which is holding the value “hai “ in String Constant Pool .
     So, JVM will just create another reference variable for the same object.

I know it will be really confusing. Let’s jump to a story..

    STORY BEGINS:

         Assume there is a grocery store. Inside the grocery store, there are few empty containers. The shop vendor has decided to fill those containers with chocolates so that he could make a sale with it.

        He has started filling those containers with chocolates and ended up in filling one complete container.

      The container is big so he wasn’t able to keep inside the shop. He chose go-down and kept the container there.

         After a week, he asked two of the sales-person to get the container inside the shop. Each of the sales-person chose a way to collect the container. One person chose left way and other right way.

      At last they ended up to the go-down , carried the container and went to the vendor.
Now, here..

      The container now refers to object.

      Chocolates refer to values

      Go-down refers to String Constant pool

      Two sales-person refer to “reference variables”

      So, Now just map it with the above technical terms..

      Object usually contains the address but we will say like it is holding the values.!! In this case, it is holding the value “hai “ . Consider it is stored in address “123”. 

     To access the value, a reference variable is created and accessed in that particular memory.
     When same value is stored, ie. hai then it will be stored in same address “123” because “JVM” will see whether object is storing the same value..

       The answer is yes..!! But it is creating 2 reference variable to access the object ie. 2 sales- person to access the container.

COMPARING TWO STRINGS USING ASSIGNMENT OPERATOR:

Consider the example,

    Class  Test
      {
        public static void main(String args[])
          {
           string s1= “baby”;
           string s2=”baby”;
           if(s1.equals(s2))
           {
              System.out.println(“Strings are equal”);
           }
         else
          {
           System.out.println(“Strings are not equal”);
         }

    }

OUTPUT:

    Strings are equal

EXPLANATION:

     In the above example, we are declaring 2 strings s1 , s2.

     The value of the String is stored in an address “123”. 

     Now initially the value of the String will be stored in an address and the object will hold that address then again after declaring the second String, The JVM will see whether there are any objects that is holding the value “123” and wow.. there is an object that is holding this value .. So I will store this inside the same object but let me create 2 reference variable s1, s2 so that it will be accessed easily.. is what the JVM thinks and does the creation..!!

      So Since both s1 and s2 value resides inside the same address, the COMPARISON operator will check for the references of s1 and s2 ie. it will check whether s1 and s2 belong to same object..Yes of course, they belong to the same object. So, it will return TRUE.

STRING CREATION USING NEW KEYWORD:

     Consider the Example,

      Class  Test
        {
        public static void main(String args[])
          {
            string s1= new String(“baby”);
           string s2= new string (“baby”);
           if(s1.equals(s2))
             {
                 System.out.println(“Strings are equal”);
             }
           else
            {
              System.out.println(“Strings are not equal”);
           }

      }

OUTPUT:

Strings are not equal

EXPLANATION:

       In the above example, the strings are created using New keyword. Here the s1 and s2 are objects and we are storing “baby” in 2 different address and it has 2 different variables.

    NOTE: Here the equals method will check if the value stored belongs to same object. !! In this case, they belong to different objects 

The value contained is baby for both the objects

And so the output will be..

OUTPUT:

Strings are not equal

COMPARING STRING USING EQUALS METHOD WITHOUT NEW KEYWORD:
EXAMPLE:

    Class  Test
     {
           public static void main(String args[])
            {
              string s1 = “baby”;
              string s2 = ‘baby”;
              if(s1.equals(s2))
               {
                  System.out.println(“Strings are equal”);
               }
            else
              {
                System.out.println(“Strings are not equal”);
              }

       }

OUTPUT:

Strings are equal

EXPLANATION:

       No matter in which means the strings are created , when we use equals method , it will check whether the values are equal and will not check whether it belongs to same object etc.

STRING METHODS:

       There are various in – built string methods.. There are many like,

Equals( ) – checks whether the strings are equals method ,

EXAMPLE:

 S1 = “hai”
  S2=”bye”;
If(s1.equals(s2))
{
// condition
}
else
{
//condition
}

StartsWith( ) – checks if the particular string starts with the string specified
Syntax :

Public Boolean startsWith(String prefix)
“January”.startsWith(“Jan”);
true

endsWith( ) – Tests if this string ends with the specified suffix
‘January”.ensdsWith(“ry”);

compareTo( ) – Compares two strings to know which is bigger or smaller
Syntax – public int compareTo(String anotherString)

indexOf( ) – Searches for first occurrence of the character or the sub string.
It returns -1 if the character doesn’t exist

EXAMPLE:

String str = “ I am anu”;
Str.indexOf(‘a’);
Str.indexOf(“anu”);
So the above will return the index

substring( ) – It returns the sub string . It extracts the characters from the starting index till the ending index

EXAMPLE:

“smiles”.substring(1,5)returns “mile”
concat( ) – Concatenates the specified string to the end of the string

Syntax:

String s1 = “happy”;
String s2 = “birthday”;
S1.concat(s2) returns happy birthday

replace( ) – Returns the new String by replacing the old characters with the characters we supply
string a = “sweet”;

a.replace(‘s’, ’a’);

returns “aweet” as the output

trim( ) – It trims all the extra white spaces

valueOf( ) – It is used to convert the character array into a string. This method is rarely used.
The Syntax is as follows

Public static string valueOf(char[] data)

toLowerCase( ) – It converts all the characters in a String to Lower case

EXAMPLE:

String s1 = “ Stay happy”
S1. toLowerCase( );
toUpperCase( ) – It converts all the characters in a String to Upper Case
String s1 = “ Stay happy”
S1. toUpperCase( );

CONCLUSION:

      So, that's it for this post. We have seen a lot more about Strings. I am sure you people will be clear about the concepts. If you have any doubts, post in the comments below. Your feedback is welcomed. Help me improve this blog with your valuable feedback. Hit like button and share this post if you find it useful. Have a pleasant day :)
     




No comments :

Post a Comment