Wednesday, 14 October 2015

JAVA BASICS WITH REAL TIME EXAMPLES ..



INTRODUCTION:
         Hello friends! In this article I am going to explain basics in  Java programming with real time examples. This article will be more useful for those who are preparing for Interviews and for those who find it difficult to memorize the definitions and concepts in programming languages.   When the Interviewer  asks the definition for (say) 'x' we might have read it already but we might not recollect due to stress or we might know but we don't know how to present it !!  So, Is there any way to make a way out of it?? The answer is Absolutely..!!  My intention is to help you understand the mere concept with some real time examples and come out with flying colors in Interviews .. :)

NOTE:

      In this article I have explained the concepts of java pgmg language .Definitions in pgmg language will be almost similar so map the definitions given in this article with other programming languages too !! Have chosen JAVA pgmg for explanation because once you are thorough with JAVA you can jump to ANDROID and other pgmg languages too !! As a grad its a must to know basics in JAVA .!!

What is Java Virtual Machine (JVM) ???
 
     JVM is a virtual machine which provides runtime environment  to execute java byte code
   So, what this definition actually mean??
   JVM controls execution of each and every java program. It has got features such as automated exception handling and Garbage collected heap.
    (We will look about exception handling and Garbage collected heap in detail later.)

What JVM actually does ???

 
    Have you ever thought what actually happens when we compile the program in JAVA??
  Who does all these works ??
  Its JVM ..

How JVM helps ??


   JVM has got its own architecture. It has many components and few of its components helps for JVM to complete its own work..

 After compiling when you try to run the byte code(.class file),the following steps are performed
  • Class loader(one of the component in JVM)loads the java class
  • Byte code verifier checks  the code whether it is legal or illegal code that can violate access rights to object
  • Interpreter read the byte code steam and executes the instruction.
So, this is what JVM actually does ..!!

What is a Variable??

 
     A variable is a name of memory location that is allocated by the compiler depending upon the datatype of  a variable(datatype is explained below)
   It is used for storing values
   
   Eg. int a=5;

Here 'a' is a variable

What is an Identifier??

   Identifier is the name of a variable, method or a class.


  What is the difference between variable and an Identifier??


   Both of them may seem to be similar but they are actually not..!!


Example:


   Assume, you are the owner of  a bank..!! You are planning to buy some land in XYZ place and construct a huge bank say ABC bank . You are going to an agent to buy a land but the agent is saying .."Sorry sir we don't have a huge land in XYZ place but rather we have in MNO place."

    Finally owner accepted for constructing in MNO place. After months construction is been completed and you are inviting the clients to your bank by letting the bank address and name of the bank to the clients..!!

  So, just map with the variable definition now..

   Here memory location is the MNO
   Compiler refers to agent and
"depending upon the data type of a variable" actually refers to huge land
   Just because the land is huge the agent is suggesting(allocating) the bank to MNO place rather suggesting  XYZ place
  "Variable is used for storing values " meaning "bank  is for storing some money"

Then what does Identifier actually mean??

 
  Mapping the example with its definition,
  The name of the bank is the identifier. just like how you all have a name ,even the programming class and methods have to be given some name !! So, the name is the identifier. It has got nothing to do with it other than that!!

So, now clear with the differences?? Identifier is just the name where the variable actually means memory location for storage !!

What is a Data-type ???


   Data type actually specify the size and type of a values that can be stored in an identifier.
   Example:
    Consider , Citi Union Bank for example .The head of the bank  lets the customer to withdraw 10000rs per day from ATM!! Lets assume the bank accepts only 'savings' account.
   Now, map with the definition ..
 What is the identifier here?? Its Citi Union Bank ie. name of the bank
   Size here refers to 10000 and type refers to savings account
   The head of the bank refers to the Data-type. He is specifying how much amount (size)the customer can withdraw and what type(type of value) of account can the customer have !! :)

  Eg. int b=100;


Here 'int' refers to the data type 'b' is the variable and the value 100 is stored inside the variable 'b'

  If 'b' has address 26/2, xxx,yyy
                               Chennai-1
then value will be stored in that address given below! The address actually will be from 0001 to 9999

The data type is of 2 types

  •  Primitive data type
  •  Non primitive data type

Primitive Data type:

   It is of 8 types

  •       char
  •       Boolean
  •       byte
  •       short
  •       int
  •       long
  •       float
  •      double

Non-primitive(Reference )Data type:
  
    A reference data type is used to refer an object.

What is a Camel Case:

     If there are more than one word that is stuck up together to make a single variable name then it is called camel case
 Example:
   
          int  personName = 150;

         The rule actually implies the first letter in the word must be 'small'  and first letter in the second word must be in in 'capital'. Look at this camel's hump it is like a slope and so the rule is actually called 'camel case'



Control Statements:
              There are 3 types of Control Statements in java

           Selection statement

  •                      if
  •                      if - else
  •                      switch

           Iteration statement

  •                   while
  •                   for
  •                   do-while

           Jumping statement

  •                   break
  •                   continue
  •                   return


Iteration Statement
.
       While Loop:
                  In this the loop condition is evaluated first and if the condition is true, it will execute the body of the loop else it will come out of the loop

  Example:
      
           public class Sample
                 {
                      public static void main(String args[])
                          {
                               int i=0;
                                while( i < 5)
                                   {
                                      System.out.println("i =" +i);
                                       i ++;
                                    }
                           }
                }
                     
    Code Explanation:
   
          The value of i is initially assigned to 0 and the condition is evaluated first (i < 5 ). If the condition is true it goes inside the loop and prints the value of "i" .
         The value of i gets incremented and it again goes to the top of the loop, condition is evaluated again and again and it comes out of the loop until the value of "i" becomes greater than 5.

The output is as follows:

  i = 0
  i = 1
  i = 2
  i = 3
  i = 4

   do - while loop :

        In this loop, the condition is evaluated at the end of it and the body of the loop is executed at least once.
      
 Example:

            public class Sample
                 {
                      public static void main(String args[])
                          {
                               int i=5;
                                   do
                                      {
                                      System.out.println("i =" +i);
                                       i ++;
                                      }
                                 while( i < 5);
                          }
                }


       Code Explanation:

                          Here the condition  while( i < 5)  is evaluated at  the end of the body where the block under "do" will get executed until the condition becomes false ie. till the value of i is greater than 4  .
      So, when we use this do - while ,the body of the loop will get executed at least once since the condition is evaluated at the end.

For Loop:

      This loop provides a compressed way to iterate a range of values.

The Syntax is as follows,


         for(initialization; condition; increment/decrement)
           {
                  body of the loop
           }  


      initialization : It is executed once at the beginning of the loop.
      Condition: It will get executed for every iteration and will continue until it becomes false
     increment/decrement : It will start executing after the first iteration.


Example:

      for ( i =0 ; i <= 4 ; i ++ )
           {
                       System.out.println("hai" + i);
            }


Here the value of 'i' will get initialized to 0 and the condition is evaluated next i < =4
    0 <= 4  -------->  Condition true
    So, goes inside the loop and prints the value.
    Next, the value of i gets incremented (i ++ ) gets executed.
    The value of i becomes 1.
    The condition is evaluated again ie.
    1<=4  -------->  Condition true
    So, goes inside the loop and prints the value
    Next, the value of i gets incremented (i ++ ) gets executed.
    The value of i becomes 2.
       The condition is evaluated again and again till it becomes false.

Enhanced For loop:
  
       It is a special type of 'for loop' with the following syntax
        for(declaration : expression)
           {
               body of the loop
           }
      
    Let's look at the example..


     public class Sample
                 {
                      public static void main(String args[])
                          {
                             int [] numbers = {10,20,30,40,50};
                             for(int i : numbers)
                              {
                               System .out. println(i);
                             }
                          }
                }
 Output:
    10
    20
    30
    40
    50


   Explanation:


            numbers  is the name of the array which holds the values 10,20 etc
         Enhanced for loop contains the variable i and the array name 'numbers'.
        Initially ,  the variable i stores the value 10 which is supposed to be the first value in the array .

       It goes inside the body of the loop and prints the value of 'i'.
       Next the variable 'i' stores the value '20' which is the next value in the array ,goes inside the loop and prints it.
       The specialty in 'Enhanced For Loop' is there is no need for increment and decrement operator and no need for initialization in the 'for loop'.
       It will automatically retrieve the value store it inside the variable and print it.

Break Statement:

       When the break statement is executed it will terminate the corresponding body of the loop and it will continue executing the statements which is immediately following the loop.

Example:


          public class Sample

                 {
                      public static void main(String args[])
                          { 
                          for(int i=0;i<=4;i++)
                           { 
                              if(i==3)
                               { 
                               break;
                                  System.out.println("This statement wont   get  executed since it is inside the body of  the loop  where the same break statement  exists");
                               }
                                 System.out.println("This statement will get executed as it is outside the body of the loop");
                          }
                }

           Output:


            This statement will get executed as it is outside the body of the loop
                 

           Explanation:
                     As soon as the compiler sees the break statement it obeys the command "Hey im gona break the loop and go out of the loop... Hurrahh !! " and yea.. as the compiler wishes it comes out of the loop and starts executing the things which is outside the loop.. !!

Continue Statement:

          If we use the continue statement then the compiler will skip the current iteration and will continue executing.  
     

      Example  :

             public class Sample
                 {
                      public static void main(String args[])
                          { 
                          for(int i=0;i<=4;i++)
                           { 
                              if(i==3)
                               { 
                                continue;
                               }
                                 System.out.println("Hai.. I came out and I am printing " +i);
                          }
                }
                                                                
                     
       Output:


          Hai.. I came out and I am printing 1
          Hai.. I came out and I am printing 2
          Hai.. I came out and I am printing 4
          Hai.. I came out and I am printing 5

 
        Explanation:

     The value "3" is been skipped,meaning the compiler on seeing the "continue" statement will think " oh wow .. I can skip executing the number '3' but the worst part is I have been asked to "continue"... oh crap.. !!
         Pity compiler.. !! The compiler skips the number '3' alone but keeps executing loop. 

Difference between the Break and Continue statement:

       In case of "Break" keyword, if the condition is satisfied, it will come out of the body of the loop and will never continue with the loop but the 'continue' statement will skip only the current condition but will continue executing the loop.

Conclusion:

    So..That's all folks.. !! We have completed few important basic concepts . Clap your hands and say a big "hurraaahhhhh" if you have understood these concepts well .. !! Stay tuned for more tutorials..and feel free to drop your comments below. Hit the Like button if you like the tutorial. Your support is much more needed for me to keep posting !! Enjoy your day :)



  

  

No comments :

Post a Comment