Thursday, 19 June 2014

Arrays In JavaScript

Arrays

To declare a variable that contains an empty array, you use square brackets with nothing between them:
var a = [];
Console:
typeof a;
Output:
"object"
*typeof returns "object"

To define an array that has three elements, you do this:
var a = [1,2,3];
When you simply type the name of the array in the Firebug console, it prints the contents of the array: 
Console:
Output:
[1, 2, 3]

So what is an array exactly? It's simply a list of values. Instead of using one variable to store one value, you can use one array variable to store any number of values as elements of the array.
The elements contained in an array are indexed with consecutive numbers starting from zero. The first element has index (or position) 0, the second has index 1 and so on.

Here's the three-element array from the previous example: 
Index Value
0 1
1 2
2 3
In order to access an array element, you specify the index of that element inside square brackets. So a[0] gives you the first element of the array a , a[1] gives you the second, and so on. 
Console:
a[0] 
Output:
Console:
a[1] 
Output:
2

Adding/Updating Array Elements

Using the index, you can also update elements of the array. The next example updates the third element (index 2) and prints the contents of the new array. 
Console:
a[2] = 'three'; 
Output:
"three" 
Console:
Output:
[1, 2, "three"] 
You can add more elements, by addressing an index that didn't exist before. 
Console:
a[3] = 'four';
Output:
[1, 2, "three", "four"]

If you add a new element, but leave a gap in the array, those elements in between are
all assigned the undefined value. Check out this example: 
Console:
var a = [1,2,3];
a[6] = 'new';
Output:
[1, 2, 3, undefined, undefined, undefined, "new"] 

Deleting Elements

In order to delete an element, you can use the delete operator. It doesn't actually
remove the element, but sets its value to undefined . After the deletion, the length of
the array does not change. 
Console:
var a = [1, 2, 3];
delete a[1];
Output:
[1, undefined, 3]

Arrays of arrays

An array can contain any type of values, including other arrays. 
Console:
var a = [1, "two", false, null, undefined];
Output:
[1, "two", false, null, undefined] 
Console:
a[5] = [1,2,3]
Output:
[1, "two", false, null, undefined, [1, 2, 3]]

Let's see an example where you have an array of two elements, each of them being an array. 
Console:
var a = [[1,2,3],[4,5,6]];
Output:
[[1, 2, 3], [4, 5, 6]] 
The first element of the array is a[0] and it is an array itself. 
Console:
a[0] 
Output:
[1, 2, 3] 
To access an element in the nested array, you refer to the element index in another set of square brackets. 
Console:
a[0][0] 
Output:
Console:
a[1][2] 
Output:


Note also that you can use the array notation to access individual characters inside a string. 
Console:
var s = 'one';
s[0] 
Output:
"o" 
Console:
s[1] 
Output:
"n" 
Console:
s[2] 
Output:
"e"

Remembering that:

  • An array is a data store
  • An array contains indexed elements
  • Indexes start from zero and increment by one for each element in the array
  • To access array elements we use the index in square brackets
  • An array can contain any type of data, including other arrays

Saturday, 5 April 2014

Closure- Real worl Problem of Syncronyse setTimeout within for loop

Before starting solution., Let discuss the problem. What exactly problem is all about and how we will resolve it

First look at the below given code:
function myFunction()
{
   for(var i=0;i<10;i++){
   setTimeout(function(){alert(i)},3000);
   }
}

//output:
//Predictable in case if for loop completes before 3000milisec.
//i.e Output would be 1o times 10.

Now suppose i want to print all possible values of the i, in alert. i.e. 0,1,2...9 what we will do??

Here closure comes in picture.

Closure:The function defined in the closure 'remembers' the environment in which it was created in. 

As definition you can see that a closure method remembers its value the environment it was create. So we will modify our code, so that it can synchronized for loop with setTmeout method.


function myFunction()
{
   //Closure example

   for(var i=0;i<10;i++){
   (function(i){ // here we have created an anonymous method.

      setTimeout(function(){alert(i)},3000);
   })(i); // It will self excute with the values of i

  }
}

//output:
//i.e Output would be 1,2,3....10

Here in above code we have added a closure anonymous method. It self invoked on each loop. 

 

Monday, 31 March 2014

Static class in Java

Static class in Java

Can a class be static in Java?

The answer is YES, we can have static class in java. In java, we have static instance variables as well as static methods and also static block. Classes can also be made static in Java.

Java allows us to define a class within another class. Such a class is called a nested class. The class which enclosed nested class is known as Outer class. In java, we can’t make Top level class static. Only nested classes can be static.

Nested Classes

The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {
...
     class NestedClass {
        ...
    }
}

Nested classes are divided into two categories: static and non-static. Nested classes that are declared  
What are the differences between static and non-static nested classes? 

static are called static nested classes. Non-static nested classes are called inner classes.
1) Nested static class doesn't need reference of Outer class but non static nested class or Inner class requires Outer class reference. You can not create instance of Inner class without creating instance of Outer class. This is by far most important thing to consider while making a nested class static or non static.
2) static class is actually static member of class and can be used in static context e.g. static method or static block of Outer class.
3) Another difference between static and non static nested class is that you can not access non static members e.g. method and field into nested static class directly. If you do you will get error like "non static member can not be used in static context". While Inner class can access both static and non static member of Outer class.

Static Nested Classes

As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.



Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.


here is the code sample of using both nested static class vs non static class :

/*
* Java program to demonstrate What is nested static and non static class.
* How to create instance of static and non static class and How to call
* methods of nested static and Inner class in Java. Overall comparison of
* static vs non static class.
*/
class Outer{
private static String message = "HelloWorld";

// Static nested class
private static class MessagePrinter{

//Only static member of Outer class is directly accessible 
//in nested static class

    public void printMessage(){
     // Compile time error if message field is not static
        System.out.println("Message from nested static class : " + message);
    }
}
//non static nested class - also called Inner class
private class Inner{
    // Both static and non static member of Outer class 

    //is accessible in this Inner class
    public void display(){
        System.out.println(" Message from non static nested or Inner class : " + message);
    }
}
// How to create instance of static and non static nested class
public static void main(String... args){
    // creating instance of nested Static class
    Outer.MessagePrinter printer = new Outer.MessagePrinter();
    //calling non static method of nested static class
    printer.printMessage();
    // creating instance of non static nested class or Inner class
    // In order to create instance of Inner class you need an 

    //Outer class instance 

    Outer outer = new Outer(); 

    //outer class instance for creating non static nested class

    Outer.Inner inner  = outer.new Inner();
    //calling non static method of Inner class


    inner.display();
    // we can also combine above steps in one step to 

    // create instance of Inner class

    Outer.Inner nonStaticIner = new Outer().new Inner();
    // similarly you can now call Inner class method
    nonStaticIner.display();
}

}

Output:
Message from nested static class : HelloWorld
Message from non static nested or Inner class : HelloWorld
Message from non static nested or Inner class : HelloWorld


Why Use Nested Classes?

Compelling reasons for using nested classes include the following:
  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

How To Restart MySQL Server

Each distribution comes with a shell script (read as service) to restart / stop / start MySQL server. First login as root user and open shell prompt (command prompt).
First login as root user. Now type the following command as per your Linux distro:



A) If you are using mysql on RedHat Linux (Fedora Core/Cent OS) then use following command:

  • To start mysql server:
/etc/init.d/mysqld start
  • To stop mysql server:
/etc/init.d/mysqld stop
  • To restart mysql server
 /etc/init.d/mysqld restart
Tip: Redhat Linux also supports service command, which can be use to start, restart, stop any service:
# service mysqld start
# service mysqld stop
# service mysqld restart


(B) If you are using mysql on Debian / Ubuntu Linux then use following command:

  • To start mysql server:
/etc/init.d/mysql start
  • To stop mysql server:
/etc/init.d/mysql stop
  • To restart mysql server
/etc/init.d/mysql restart

Thursday, 20 March 2014

Function Definition- Three Way to Define a JavaScript Function

There are 3 ways you can define a function.

1. Using Function constructor

var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30

2. Using Function declaration.

function sum(a, b)
{
    return a + b;
}

alert(sum(10, 10)); //Alerts 20;

3. Function Expression

var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10
 
 

Difference between declaration and expression: 

From ECMA Script specification:
FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }
FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
 
var sum = function mySum(a, b) { return a + b; }

Important point to note is that you can use 'mySum' only inside the mySum function body, not outside.

See following example:

var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

Sunday, 9 February 2014

Starting with jQuery (First program in jQuery)

jQuery Installation:


Adding jQuery to Your Web Pages

There are several ways to start using jQuery on your web site. You can:
       Download the jQuery library from jQuery.com
       Include jQuery from a CDN, like Google

Downloading jQuery

There are two versions of jQuery available for downloading:
       Production version
       Development version

Steps needs to follow:

1.    Open your favorite browser and point it to this address: http://www.jquery.com
2.    Find the section labeled “Grab the Latest Version!” Then, select the checkbox next to “Production.”.
3.    Click the “Download jQuery” button.
4.    The next page you’ll see will look something like this. Save the page into a folder called scripts on your drive



See figure:

What’s the difference between the Production and Development versions?

       The Production version of jQuery is a minified version, intended for speed of execution on a web server.
       The Development version is intended for developers interested in exploring and extending the inner workings of thejQuery library.



How to use downloaded jQuery library?

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>


Do you wonder why we do not have type="text/javascript" inside the <script> tag?

This is not required in HTML5. JavaScript is the default scripting language in HTML5 and in all modern browsers!

Alternatives to Downloading

If you don't want to download and host jQuery, you can include it from a CDN (Content Delivery Network). Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of the following:

Google CDN:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>

Microsoft CDN:

<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js">
</script>
</head>

One big advantage of using the hosted jQuery from Google or Microsoft
Many users already have downloaded jQuery from Google or Microsoft when visiting another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be served from the server closest to them, which also leads to faster loading time.


Starting with jQuery (First program in jQuery):

Open your editor -> Create a new document ->Paste given code -> Save as MyFirstPage.html -> Open that page in Browser
*Note:- While saving select “save as type” as all type(“.”)

MyFirstPage.html
<!DOCTYPEhtml>
<html>
<head>
<title>jQuery goes to DOM-ville</title>
<style>
#change_me {
       position: absolute;
       top: 100px;
       left: 400px;
       font: 24px arial;
}

#move_up#move_down#color#disappear {
       padding: 5px;
}
</style>
<script src="jquery.js" type="text/javascript">
      
</script>
</head>
<body>
       <button id="move_up">Move Up</button>
       <button id="move_down">Move Down</button>
       <button id="color">Change Color</button>
       <button id="disappear">Disappear/Re-appear</button>
       <div id="change_me">Make Me Do Stuff!</div>
       <script>
              $(document).ready(function() {
                     $("#move_up").click(function() {
                           $("#change_me").animate({
                                  top : 30
                           }, 200);
                     });//end move_up
                     $("#move_down").click(function() {
                           $("#change_me").animate({
                                  top : 500
                           }, 2000);
                     });//end move_down
                     $("#color").click(function() {
                           $("#change_me").css("color", "purple");
                     });//end color
                     $("#disappear").click(function() {
                           $("#change_me").toggle("slow");
                     });//end disappear
              });//end doc ready
       </script>
</body>
</html>

How does that work?

       The visitor clicks a button.
 The JavaScript interpreter “hears” the click event and runs the function attached to it.
The JavaScript interpreter changes the DOM representation of the page.

 The visitor sees the element move up the page.