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 :)
     




WHAT IS A VARIABLE AND WHAT ARE THE TYPES OF VARIABLE IN JAVA..??

INTRODUCTION :


      Hei.. all !! here we are.. !! In this post, I am going to explain the types of variable available..
The variable which is almost common to all programming languages are
  •  Local variable and
  •  Global variable



WHAT IS A LOCAL VARIABLE..??

        Yeah..  as soon as you read the heading you would have guessed the definition .. (I hope :D ) !! Of course ..your definition is correct.. !!
 The variable which is available locally is called local variable ..!!
 But what does it mean by local ?? :/
Okies.. Lets jump into the example..

EXAMPLE :

Class happy
     {
           public void add( )
                  {
                    int sad = 5 ;
                    System.out.println( “ My num is “ + sad );

                  }
         public static void main(String args[])
            {
              happy ha= new happy( ); // creating an object
              ha.add( ); // accessing the method using object
            }
     }

OUTPUT:

My num is 5.

EXPLANATION:


     Now here.. class name is happy and the method which is present inside it is add ( ) .
Now the variable ‘sad’ is present inside the method add( ) .
    If a variable is present inside any method it is called ‘local variable’. It is locally available to that method alone.
      If any method tries to access the variable then it will throw an error saying the variables and method can’t be accessed directly. The way to access them is to use the object.
      So, in short the variable which is present inside any method is called ‘local varible’.

WHAT IS A GLOBAL VARIABLE..?

    The variable which is declared globally is called ‘global variable’.
       That is,if the variable is declared outside the method it is called global variable

MEMBER VARIABLE:

      There are 3 types of member variable. They are,
  • Instance variable
  • Static variable and
  • Final variable




WHAT IS AN INSTANCE VARIABLE..?


       The variable which is declared inside the class but outside the method is called ‘instance variable’

 EXAMPLE:

  Class Happiest
     {
           int happier = 5 ;
            public void happy( )
             {
                 System.out.println( “ My num is “ + happier );

            }
         public static void main(String args[])
          {
          Happiest ha = new Happiest( );
          ha.happy( );
          }
}

EXPLANATION:

       Here ‘happier’ is the variable here an ‘instance variable’. This variable is declared inside the class ‘Happiest’ but it is declared outside the method ‘happy’

       This ‘ happier’ variable is tooo happy because this is available through out the class.

DIFFERENCE BETWEEN INSTANCE VARIABLE AND LOCAL VARIABLE:

       The main difference between local and instance variable is,

        If the local variable is not initialized it will throw out the error but it we fail to initialize ‘INSTANCE VARIABLE’ it will get initialized on its own.

EXAMPLE:

Class Happiest
     {  
              int happier ;
               public void happy( )
                 {
                    System.out.println( “ My num is “ + happier);

                 }
          public static void main(String args[])
            {
               Happiest ha = new Happiest( );
               ha.happy( );
           }
}

OUTPUT:
0

EXPLANATION:

     The output is 0 and it didn’t throw any error because it is an ‘INSTANCE VARIABLE’.

     If we didn’t initialize or assign any value to it , it will assign the default value 0 for Integer data type and ‘null’ for string datatype.

EXAMPLE FOR LOCAL VARIABLE:

    Class Happiest
       {
           public void happy( )
                {
                   int happier ;
                   System.out.println( “ My num is “ + happier);

                }
         public static void main(String args[])
          {
             Happiest ha = new Happiest( );
               ha.happy( );
         }
    }

OUTPUT:

      Compile time error. The local variable ‘happier’ is without initialization and it will throw error to initialize it.

STATIC VARIABLES:

      Static variables are independent of objects meaning they don’t belong to specific objects.

     Only one copy of ‘static variable’ exists and they will be shared among all of the objects.

      Static variables are rare . They are unique and have more demand and so only copy exists for a class ; )

DOES STATIC VARIABLE HAVE AN ALTERNATE NAME.. ??

       Yes … static variable is also called as ‘CLASS VARIABLE’ as they belong to the entire class  and not to any specific object.

       The static variable won’t see any partiality .It wont think like.. Oh..man !! This object looks good and polite and so I will be available only to them…” :D

      Instead.. I am one and I will be available to all the objects. There is no partiality when it comes to availability is what this ‘static variable’ thinks..

EXAMPLE:

class StaticExample
    {
         static int count=0;
         public void increment()
           {
             count++;
           }

       public static void main(String args[])
         {
             StaticExample obj1=new StaticExample();
              StaticExample obj2=new StaticExample ();
              obj1.increment();
               obj2.increment();
               System.out.println("Obj1 count is="+obj1.count);
             System.out.println("Obj2 count is="+obj2.count);
        }
   }


OUTPUT:

Obj1 count is = 2
Obj2 count is= 2

EXPLANATION:

       Look at the above code.. obj1 and obj2 are the 2 objects created for the class StaticExample.

         When the method increment ( ) is called for the first time ie. obj1.increment ( ) then the method gets called and increments the value of the “count “

         The value of the count is now 1.

NOTE: COUNT IS A STATIC VARIABLE and so only one copy of the variable exists.

       Then when the same method is called using DIFFERENT OBJECT the value is incremented again and now the value of the count now turns to 2.

BIT COMPLEX EXAMPLE:

Class staticexample
      {
           static int X= 10;
           int Y=5; // non static variable
           public static void main(String [] args)
              {
                    staticDemo instance1 = new StaticDemo();  // creating object for a class

                    staticDemo instance2 = new StaticDemo();  // creating another object for a class
                    //printing the value of x and y using 1st object

                    System.out.println("instance1.X=" + instance1.X+ "instance1.Y="+instance1.Y); 
                    //printing the value of x and y using 1st object

                     System.out.println("instance2.X=" + instance2.X+ "instance2.Y="+instance2.Y); 

                     instance1.X=15; // changing the value of x and y

                     instance1.Y=10;

            System.out.println("After updating X value to 15 and Y value to 10 from instance1 : ");

            System.out.println("instance1.X="+instance1.X+"instance1.Y="+instance1.Y "); //explained below

          System.out.println("instance2.X="+instance2.X+"instance2.Y="+instance2.Y "); 
//explained below
               }
          }

    OUTPUT:

        instance1.X = 10 instance1.Y=5
        instance2.X = 10 instance2.Y=5
        After updating X value to 15 and Y value to 10 from instance1:
        instance1.X=15 instance1.Y=10
        instance2.X=15 instance2.Y=5

  Initially the values are 10 and 5 .

  Then the object ‘instance 1’ is accessing the variable x and y and trying to change the values.

  It is changing the value of x and y to 15 and 10.

  Note that for static variable there is only one copy and so when any changes happen to it will be reflected to all the objects.


   So the variable x erases its previous memory 10 and now updates its new value 15. 

   But lucky variable ‘Y’ has made  itself change its value only for object ‘instance 1’ ie. So, instance 1 has the variable value Y = 10 and instance 2 =5.

   Wow.. Instance 2 has the value Y= 5 and not 10 which is the updated value because Y is normal variable and only the instance 1 object has changed its variable’s value and not the instance 2.



When value changes to 15 then the initial value will get deleted from the variable’s memory and so VALUE = 15 will be available to both the objects where as for NORMAL VARIABLE



                                                     
                                                                                                                                   
                                                  

                       A copy of variable is available to each object and note we are changing the value of variables that is belonging to object instance1 and so the values resides within that object itself
                     Unless until the variable is static, each object will have its own set of values.

FINAL VARIABLES:

        When we apply "final" keyword to a variable,the value of that variable remains constant. (or) Once we declare a variable as final,the value of that variable cannot be changed.

EXAMPLE:

  Class Ex
   {
        public final int a= 10;
          public void add()
              {
                  Int a= 12;
                  System.out.println(“the value of a = “ +a);
              }
   
      public static void main(String args[])
       {
        Ex e = new Ex( );
        e.add( );
       }

OUTPUT:

Compile time error.

EXPLANATION:

     This is because we are trying to change the value of ‘a’ inside the method.
     ‘a’ is a final variable and so it can’t be changed.

DIFFERENCE BETWEEN STATIC AND FINAL KEYWORD:

      When a variable is declared ‘STATIC’ only one copy exists and it belongs to entire class .
       Whereas when a  FINAL VARIABLE is used then the value of a variable cannot be changed inside the program no matter what.

CONCLUSION:

        So, that's it for this post. We have seen a lot more about variable. 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 :)