Thursday 15 December 2011

Example of volatile keyword in Java:

To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.

public class Singleton{
private static volatile Singleton _instance;

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.


Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.
So in Summary apart from synchronized keyword in java, volatile keyword is also used to communicate content of memory between threads.

Let’s see another example of volatile keyword in Java:

most of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't  use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory  and  "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads.


 boolean bExit;

 while(!bExit) {
    checkUserPosition();
    updateUserPosition();
 }

In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bExit" as volatile in java ensures this will not happen.



Important points on Volatile keyword in Java

1. Volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.

2. Volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.

3. In Java reads and writes are atomic for all variables declared using java volatile keyword (including long and double variables).

4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

5. From Java 5 changes to a volatile variable are always visible to other threads. What’s more it also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.

6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java.

7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.
8. A java volatile variable that is an object reference may be null.

9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.


Difference between synchronized and volatile keyword in Java

1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods.

2. Synchronized obtains and releases lock on monitor’s java volatile keyword doesn't require that.

3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java.

4. Synchronized method affects performance more than volatile keyword in Java.

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory  and "main" memory  while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.

6. You can not synchronize on null object but your volatile variable in java could be null.

7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire

In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in java

Difference Between hashtable and hashmap

1) hashtable extends Dictionary interface which is quite old while hashmap extends Map interface.
2) hashtalbe doesn't have counterpart like ConcurrentHashMap.
3) another important difference between hashtable and hashmap is , hashtable is less secure than hashmap because of Enumeration it uses. while hashmap uses iterator which prevents Concurrent Modification of HashMap, which is not possible in case of hashtable.
4) stay out of hashtable use hashmap instead.

HashMap

HashMap accept null while hashtable doesn't , HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc.
1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is  fail-fast  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove()  method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception wjavascript:void(0)ill be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

3)Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Hope this will be useful.


 

Monday 30 May 2011

Reading an XML document using JDOM

ReadingxmlusingJdom.java
/*
 * @Program to read an XML document using JDOM?
 * ReadingxmlusingJdom.java
 * Author:-RoseIndia Team
 * Date:-10-Jun-2008
 */
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.util.List;
public class ReadingxmlusingJdom {
  public static void main(String[] args) throws Exception {
  String data =
  "<root>" +
  "<Companyname>" +
  "<Employee name=\"Girish\" Age=\"25\">Developer</Employee>" +
  "</Companyname>" +
  "<Companyname>" +
  "<Employee name=\"Komal\" Age=\"25\">Administrator</Employee>" +
  "</Companyname>" +
  "</root>";
  SAXBuilder builder = new SAXBuilder();
  Document document = builder.build(
  new ByteArrayInputStream(data.getBytes()));
  Element root = document.getRootElement();
  List row = root.getChildren("Companyname");
  for (int i = 0; i < row.size(); i++) {
  Element Companyname = (Element) row.get(i);

  List column = Companyname.getChildren("Employee");
  for (int j = 0; j < column.size(); j++) {
 Element Employee = (Element) column.get(j);
 String name = Employee.getAttribute("name").getValue();
 String value = Employee.getText();
 int length = Employee.getAttribute("Age").getIntValue();
 System.out.println("Name = " + name);
 System.out.println("Profile = " + value);
 System.out.println("Age = " + length);
  }
  }
  }
}

Output of the program:-
Name = Girish
Profile = Developer
Age = 25
Name = Komal
Profile = Administrator
Age = 25

Storing xml data into the database


I have to store this file into database

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<entertainment category="video">
<movie genre="hollywood">
<title>Ironman2</title>

<artist >
<male>Robert Downing Junior</male>
<female>gwyneth paltrow</female>
</artist>

<country>USA</country>
<company>Columbia pictures</company>
<cost>1000 million</cost>
<release>2010 7 may</release>
</movie>
<movie genre="bollywood">
<title>Kites</title>
<artist >
<male>Hrithik Roshan</male>
<female>barbara mori</female>
</artist>
<country>India</country>
<company>FilmKraft India</company>
<cost>500 million</cost>
<release>2010 17 may</release>
</movie>


</entertainment>

import javax.xml.parsers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.sql.*;

public class xml{
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/register";, "root", "root");
Statement st=connection.createStatement();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("movie.xml");
NodeList n1= doc.getElementsByTagName("title");
NodeList n2= doc.getElementsByTagName("male");
NodeList n3= doc.getElementsByTagName("female");
NodeList n4= doc.getElementsByTagName("country");
NodeList n5= doc.getElementsByTagName("company");
NodeList n6= doc.getElementsByTagName("cost");
NodeList n7= doc.getElementsByTagName("release");
for(int i=0;i<n1.getLength();i++){
String st1= n1.item(i).getFirstChild().getNodeValue();
String st2= n2.item(i).getFirstChild().getNodeValue();
String st3= n3.item(i).getFirstChild().getNodeValue();
String st4= n4.item(i).getFirstChild().getNodeValue();
String st5= n5.item(i).getFirstChild().getNodeValue();
String st6= n6.item(i).getFirstChild().getNodeValue();
String st7= n7.item(i).getFirstChild().getNodeValue();
System.out.println(st1+" "+st2+" "+st3+" "+st4+" "+st5+" "+st6+" "+st7);
st.executeUpdate("insert into movie(title,male,female,country,company,cost,movierelease) values('"+st1+"','"+st2+"','"+st3+"','"+st4+"','"+st5+"','"+st6+"','"+st7+"')");
}
}
catch(Exception e){
e.printStackTrace();
}
}
}

For the above code, we have created following database table:

CREATE TABLE `movie` (
`id` bigint(255) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`male` varchar(255) default NULL,
`female` varchar(255) default NULL,
`country` varchar(255) default NULL,
`company` varchar(255) default NULL,
`cost` varchar(255) default NULL,
`movierelease` varchar(255) default NULL,
PRIMARY KEY (`id`)
)

Code To check the Range of Ip Address

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IpRange {
 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  String str1="192.168.1.101";
  String str2="192.168.1.199";
  int[] p1 = new int[4];
  int[] p2 = new int[4];
 
  int[] p3 = new int[4];
  System.out.println("Enter valid ip address");
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String str3=br.readLine();
  String[] s1 =str1.toString().split("\\.");
  String[] s2 =str2.toString().split("\\.");
  String[] s3 =str3.toString().split("\\.");
 
//  p1[0] = Integer.parseInt(s1[0]);
//
//  p1[1] = Integer.parseInt(s1[1]);
  p1[2] = Integer.parseInt(s1[2]);
  p1[3] = Integer.parseInt(s1[3]);
//  p2[0] = Integer.parseInt(s2[0]);
//
//  p2[1] = Integer.parseInt(s2[1]);
  p2[2] = Integer.parseInt(s2[2]);
  p2[3] = Integer.parseInt(s2[3]);
 
//  p3[0] = Integer.parseInt(s3[0]);
// 
//  p3[1] = Integer.parseInt(s3[1]);
  p3[2] = Integer.parseInt(s3[2]);
  p3[3] = Integer.parseInt(s3[3]);
 
  if ((p1[2] < p3[2] && p2[2] > p3[2])&&(p1[3] < p3[3] && p2[3] > p3[3]) )
  {
   System.out.println("valid ip address");
  }
  else
  {
   System.out.println("invalid ip address");
  }
 
 }
}

General pagenation code

//function to return the pagination string
function getPaginationString($page = 1, $totalitems, $limit = 15, $adjacents = 1, $targetpage = "/", $pagestring = "?page=")
{       
    //defaults
    if(!$adjacents) $adjacents = 1;
    if(!$limit) $limit = 15;
    if(!$page) $page = 1;
    if(!$targetpage) $targetpage = "/";
   
    //other vars
    $prev = $page - 1;                                    //previous page is page - 1
    $next = $page + 1;                                    //next page is page + 1
    $lastpage = ceil($totalitems / $limit);                //lastpage is = total items / items per page, rounded up.
    $lpm1 = $lastpage - 1;                                //last page minus 1
   
    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case we want to draw it more than once.
    */
    $pagination = "";
    if($lastpage > 1)
    {   
        $pagination .= "<div class=\"pagination\"";
        if($margin || $padding)
        {
            $pagination .= " style=\"";
            if($margin)
                $pagination .= "margin: $margin;";
            if($padding)
                $pagination .= "padding: $padding;";
            $pagination .= "\"";
        }
        $pagination .= ">";
        //previous button
        if ($page > 1)
            $pagination .= "<a href=\"$targetpage$pagestring$prev\">« prev</a>";
        else
            $pagination .= "<span class=\"disabled\">« prev</span>";   
       
        //pages   
        if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
        {   
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination .= "<span class=\"current\">$counter</span>";
                else
                    $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
            }
        }
        elseif($lastpage >= 7 + ($adjacents * 2))    //enough pages to hide some
        {
            //close to beginning; only hide later pages
            if($page < 1 + ($adjacents * 3))       
            {
                for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">$counter</span>";
                    else
                        $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
                }
                $pagination .= "...";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lpm1 . "\">$lpm1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lastpage . "\">$lastpage</a>";       
            }
            //in middle; hide some front and some back
            elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "1\">1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "2\">2</a>";
                $pagination .= "...";
                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">$counter</span>";
                    else
                        $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
                }
                $pagination .= "...";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lpm1 . "\">$lpm1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lastpage . "\">$lastpage</a>";       
            }
            //close to end; only hide early pages
            else
            {
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "1\">1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "2\">2</a>";
                $pagination .= "...";
                for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">$counter</span>";
                    else
                        $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
                }
            }
        }
       
        //next button
        if ($page < $counter - 1)
            $pagination .= "<a href=\"" . $targetpage . $pagestring . $next . "\">next »</a>";
        else
            $pagination .= "<span class=\"disabled\">next »</span>";
        $pagination .= "</div>\n";
    }
   
    return $pagination;
}

Friday 22 April 2011

Example code --How to copy elements of Arraylist to vector

Method to copy elements from Arraylist to Vector-- Collections.copy(v,arrayList);
  1. /*
  2. Copy Elements of ArrayList to Java Vector Example
  3. This java example shows how to copy elements of Java ArrayList to Java Vector using
  4. copy method of Collections class.
  5. */
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.Vector;
  9. public class CopyElementsOfArrayListToVectorExample {
  10. public static void main(String[] args) {
  11. //create an ArrayList object
  12. ArrayList arrayList = new ArrayList();
  13. //Add elements to Arraylist
  14. arrayList.add("1");
  15. arrayList.add("4");
  16. arrayList.add("2");
  17. arrayList.add("5");
  18. arrayList.add("3");
  19. //create a Vector object
  20. Vector v = new Vector();
  21. //Add elements to Vector
  22. v.add("A");
  23. v.add("B");
  24. v.add("D");
  25. v.add("E");
  26. v.add("F");
  27. v.add("G");
  28. v.add("H");
  29. /*
  30. To copy elements of Java ArrayList to Java Vector use,
  31. static void copy(List dstList, List sourceList) method of Collections class.
  32. This method copies all elements of source list to destination list. After copy
  33. index of the elements in both source and destination lists would be identical.
  34. The destination list must be long enough to hold all copied elements. If it is
  35. longer than that, the rest of the destination list's elments would remain
  36. unaffected.
  37. */
  38. System.out.println("Before copy, Vector Contains : " + v);
  39. //copy all elements of ArrayList to Vector using copy method of Collections class
  40. Collections.copy(v,arrayList);
  41. /*
  42. Please note that, If Vector is not long enough to hold all elements of
  43. ArrayList, it throws IndexOutOfBoundsException.
  44. */
  45. System.out.println("After Copy, Vector Contains : " + v);
  46. }
  47. }
  48. /*
  49. Output would be
  50. Before copy Vector Contains : [A, B, D, E, F, G, H]
  51. After Copy Vector Contains : [1, 4, 2, 5, 3, G, H]
  52. */

how to make class Singleton

Singleton Design Pattern Example Program
>> Monday, April 18, 2011

Singleton Design pattern will allow only one object per Class(JVM).

Before Writing Singleton Design pattern you should follow these steps.

#1). create an instance as static and return type as The same class, and it should be assigned as null.

private static Singletonn instance = null;



#2). "Create a Constructor as private" to deny the creation of object from other class.

private Singletonn(){
       
    }



#3). Write a static method to create object for our class.It should be Once for a class.

public static Singletonn getInstance(){

}



#4). At last return the class Object.


Here We are creating the object once only not again and again.The first time created object is returning again when you called.

package javabynataraj.basic;

class Singletonn {
    private static Singletonn instance = null;
    private Singletonn(){
       
    }
    public static Singletonn getInstance(){
        if(instance==null){
            instance = new Singletonn();
        }
        return instance;
    }
}

public class Singleton{
    public static void main(String[] args) {
        System.out.println("before calling ...");
        System.out.println(Singletonn.getInstance());
        System.out.println("Once Called");
        System.out.println(Singletonn.getInstance());
        System.out.println("Second time called");
    }
}

why String is immutable?

Interview question on String in Java which starts with discussion of What is immutable object , what are the benefits of immutable object , why do you use it and which scenarios do you use it.

It can also come once interviewee answers some preliminarily strings questions e.g. What is String pool , What is the difference between String and StringBuffer , What is the difference between StringBuffer and StringBuilder etc.

Though there could be many possible answer for this question and only designer of String class can answer this , I think below two does make sense

1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as stirng , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.

In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file.

3)Since String is immutable it can safely shared between many threads ,which is very
important for multithreaded programming.

I believe there could be some more very convincing reasons also , Please post those reasons as comments and I will include those on this post.

Monday 18 April 2011

multithreading


How does multithreading improve the performance of Java?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Since multiple actions happen parallel (almost/virtually) to one another rather than one after the other, multithreading improves performance.

Ex: lets say there are three actions each that will take 5 seconds.

so, in a single threaded environment it will take atleast 15 seconds if they happen one after the other.

But, if we spawn three threads and have these actions started at the same time, all 3 will complete probably in around 6 or 7 seconds which is much faster than the earlier 15 seconds it took.

What advantages of multithreading in java?

http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
The advantage is the fact that multiple threads run parallel to one another and hence things happen faster than they would if they run one after the other

What is the Life cycle diagram of Thread in Java? Different states of thread?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Different states of a thread are :

New state - After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.

Runnable (Ready-to-run) state - A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.

Running state - A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.

Dead state - A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

Bocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

Sunday 17 April 2011

Difference between class variable and instance variable


What is Difference between class variable and instance variable with example?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Well, at the basic level, class fields, or static fields, as they are called sometimes, belong to the class and not to any particular instance of the class. Class fields can be assigned without instantiation of instance objects of a class. For example:

public class ExampleClass {
public static String classField = "";
public String instanceField = "";
}

I can assign a value to classField just like that:

ExampleClass.classField = "new value";

Instance fields, on the other hand, belong to a particular instance of the class. Thus, to assign an instance field a value, you have to first instantiate an object of the class just like that:

ExampleClass obj1 = new ExampleClass();
obj1.instanceField = "new value";

What is the difference between static global and local global variable?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
From Java point of view, static global class members are shared among all class instances and can be accessed from any class member [Methods]. While local global [attributes] can be accessed from any class member [method] but not shared with other class instances

Answer

The global variable can be shared across multiple files. But the global static variable cannot be shared across multiple files. Hence if you want the variable should be modified in some other file, you can make it a global variable and if you want a global variable only in the file you are declaring and not to shared across, you make it static global.
the following code snippet should be useful. //ext2.c int a=10; static int s_b=89;
//ext.c extern int a; extern int s_b; int main() { printf("a = %d\n",a); printf("static b = %d\n",s_b); return 0; }
then build the exe with ext.o and ext2.o and try running.. you will encounter an error like this "./ext.o(.text+0x20): undefined reference to `s_b'"
What is the difference between declaring static variable as local and global?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319

Answer

There are two ways to declare varibles.
1. Locally
2. Globally
When you declare a variable locally in any function that means it is only accessible by that function.
When you declare a variable globally so it is accessible by all the functions in the program.
Declaring variables with static keyword means you are setting its value null.

Difference between global variables and local variables?

http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Global Variable
It is a variable which is declared outside all the functions
It is a variable which is declared with in a function or with in a compound statement
Local Variable
It is accessible throughout the program
It is accessible only within a function/compound statement in which it is declared