Monday, January 24, 2011

Javascript : Simple Check Uncheck all checkbox



/* Here is the complete code */


<html>
 <head>
  <title> Check - Uncheck all checkbox </title>
 </head>
 <script language="javascript">
    function checkedAll (frm1)
    {
        var aa= document.getElementById('frm1');
       
        for (var i =0; i < aa.elements.length; i++)
        {
            aa.elements[i].checked = true;
        }
    }
   
    function uncheckedAll (frm1)
    {
        var aa= document.getElementById('frm1');
       
        for (var i =0; i < aa.elements.length; i++)
        {
            aa.elements[i].checked = false;
        }
    }

 </script>
 <body>
  Select : <a href="#" onclick="checkedAll();">All</a>/<a href="#" onclick="uncheckedAll();">None</a> <br/>
  <form id="frm1">
  <input id="chk" type="checkbox"> Java <br/>
  <input id="chk" type="checkbox"> J2ee <br/>
  <input id="chk" type="checkbox"> Javascript <br/>
  <input id="chk" type="checkbox"> Linux <br/>
  <input id="chk" type="checkbox"> Oracle <br/>
  </form>
 </body>
</html>

Output



Tuesday, December 21, 2010

Simple AJAX Example

AJAX = Asynchronous JavaScript and XML.

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page. ie Within the same web page we can communicate with other web page without getting out of current page.

Lets see a simple AJAX Example using .html files, directly you can run this example no need of any server.

Here we have a MainPage.html, as the name suggest this is our Main Page which will communicate with another simple page called SimplePage.html. MainPage.html will fetch data from SimplePage.html and display it without refreshing the whole page. lets see the codes.


<!-- MainPage.html -->
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MainPage.html</title>
<script TYPE="text/javascript" LANGUAGE="JavaScript">

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

function stateChanged()
{
// if request finished and response is ready
if (xmlHttp.readyState==4)
{
//get the response data as a string
var response = xmlHttp.responseText;

alert("Response :: "+response);

document.getElementById("myDiv").innerHTML=response;
}
}

function AJAXTest()
{
document.getElementById("myDiv").innerHTML="Fetching data...";

alert("AJAXTest function called");

xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}

//Stores a function (or the name of a function) to be called automatically each time the readyState property changes
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET","SimplePage.html",true);
xmlHttp.send();
}

</script>
</head>

<body>
This is a Main page. <br/><br/>
<a href="#" onclick="AJAXTest()">Click Here</a> to call SimplePage.html<br/><br/>

<div id="myDiv"> </div>

</body>
</html>



Add a simple text line in another page, which will be displayed on main page.

<!-- SimplePage.html -->


<h1>This is a Simple Page</h1>



Output







Friday, November 26, 2010

Java Collections

Collections

The Collections Framework in Java, which took shape with the release of JDK 1.2 and was expanded in 1.4 and again in Java 5, gives you lists, sets, maps, and queues to satisfy most of your coding needs. They've been tried, tested, and tweaked. Pick the best one for your job and you'll get—at the least—reasonable performance. And when you need something a little more custom, the Collections Framework in the java.util package is loaded with interfaces and utilities.

So What Do You Do with a Collection?

There are a few basic operations you'll normally use with collections
  •  Add objects to the collection.
  •  Remove objects from the collection.
  • Find out if an object (or group of objects) is in the collection.
  • Retrieve an object from the collection (without removing it).
  • Iterate through the collection, looking at each element (object) one after another.
 Key Interfaces and Classes of the Collections Framework 

The collections API begins with a group of interfaces, but also gives you a truckload of concrete classes.

MapsSetsListsQueuesUtilities
HashMapHashSetArrayListPriorityQueueCollections
HashtableLinkedHashSetVectorArrays
TreeMapTreeSetLinkedList
LinkedHashMap

Not all collections in the Collections Framework actually implement the Collection interface. In other words, not all collections pass the IS-A test for Collection. Specifically, none of the Map-related classes and interfaces extend from Collection. So while SortedMap, Hashtable, HashMap, TreeMap, and LinkedHashMap are all thought of as collections, none are actually extended from Collection-with-a-capital-C (see below Figure). To make things a little more confusing, there are really three overloaded uses of the word "collection":
  • collection (lowercase c), which represents any of the data structures in which objects are stored and iterated over.
  • Collection (capital C), which is actually the java.util.Collection interface from which Set, List, and Queue extend. (That's right, extend, not implement.
    There are no direct implementations of Collection.)
  • Collections (capital C and ends with s) is the java.util.Collections class that holds a pile of static utility methods for use with collections.
The interface and class hierarchy for collections

Collections come in four basic flavors:

  • Lists Lists of things (classes that implement List).
  • Sets Unique things (classes that implement Set).
  • Maps Things with a unique ID (classes that implement Map).
  • Queues Things arranged by the order in which they are to be processed.
The structure of a List, a Set, and a Map
Ordered When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order.

Sorted A sorted collection means that the order in the collection is determined according to some rule or rules, known as the sort order.

List Interface
A List cares about the index. The one thing that List has that non-lists don't have is a set of methods related to the index. Those key methods include things like get(int index), indexOf(Object o), add(int index, Object obj), and so on. All three List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end. The three List implementations are described in the following sections.

1 . ArrayList Think of this as a growable array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted. You might want to know that as of version 1.4, ArrayList now implements the new RandomAccess interface—a marker interface (meaning it has no methods) that says, "this list supports fast (generally constant time) random access." Choose this over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion.

2 . Vector Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two original collections, the rest were added with Java 2 versions 1.2 and 1.4. A Vector is basically the same as an ArrayList, but Vector methods are synchronized for thread safety. You'll normally want to use ArrayList instead of Vector because the synchronized methods add a performance hit you might not need. And if you do need thread safety, there are utility methods in class Collections that can help. Vector is the only class other than ArrayList to implement RandomAccess.

3. LinkedList A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-linked to one another. This linkage gives you new methods (beyond what you get from the List interface) for adding and removing from the beginning or end, which makes it an easy choice for implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion. As of Java 5, the LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now supports the common queue methods: peek(), poll(), and offer().


Set Interface
A Set cares about uniqueness—it doesn't allow duplicates. Your good friend the equals() method determines whether two objects are identical (in which case only one can be in the set). The three Set implementations are described in the following sections.

1. HashSet A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it.

2. LinkedHashSet A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

3. TreeSet The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure (but you knew that), and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.

Map Interface
A Map cares about unique identifiers. You map a unique key (the ID) to a specific value, where both the key and the value are, of course, objects. You're probably quite familiar with Maps since many languages support data structures that use a key/value or name/value pair. The Map implementations let you do things like search for a value based on the key, ask for a collection of just the values, or ask for a collection of just the keys. Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

1. HashMap The HashMap gives you an unsorted, unordered Map. When you need a Map and you don't care about the order (when you iterate through it), then HashMap is the way to go; the other maps add a little more overhead. Where the keys land in the Map is based on the key's hashcode, so, like HashSet, the more efficient your hashCode() implementation, the better access performance you'll get.HashMap allows one null key and multiple null values in a collection.

2. Hashtable Like Vector, Hashtable has existed from prehistoric Java times. For fun, don't forget to note the naming inconsistency: HashMap vs. Hashtable. Where's the capitalization of t? Oh well, you won't be expected to spell it. Anyway, just as Vector is a synchronized counterpart to the sleeker, more modern ArrayList, Hashtable is the synchronized counterpart to HashMap. Remember that you don't synchronize a class, so when we say that Vector and Hashtable are synchronized, we just mean that the key methods of the class are synchronized. Another difference, though, is that while HashMap lets you have null values as well as one null key, a Hashtable doesn't let you have anything that's null.

3. LinkedHashMap Like its Set counterpart, LinkedHashSet, the LinkedHash-Map collection maintains insertion order (or, optionally, access order). Although it will be somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

4. TreeMap You can probably guess by now that a TreeMap is a sorted Map. And you already know that by default, this means "sorted by the natural order of the elements." Like TreeSet, TreeMap lets you define a custom sort order (via a Comparable or Comparator) when you construct a TreeMap, that specifies how the elements should be compared to one another when they're being ordered.

Queue Interface
A Queue is designed to hold a list of "to-dos," or things to be processed in some way. Although other orders are possible, queues are typically thought of as FIFO (first-in, first-out). Queues support all of the standard Collection methods and they also add methods to add and subtract elements and review queue elements.

1. PriorityQueue This class is new with Java 5. Since the LinkedList class has been enhanced to implement the Queue interface, basic queues can be handled with a LinkedList. The purpose of a PriorityQueue is to create a "priority-in, priority out" queue as opposed to a typical FIFO queue. A PriorityQueue's elements are ordered either by natural ordering (in which case the elements that are sorted first will be accessed first) or according to a Comparator. In either case, the elements' ordering represents their relative priority.

Tuesday, November 9, 2010

Legal Java Identifiers

Technically, legal identifiers must be composed of only Unicode characters,numbers, currency symbols, and connecting characters (like underscores).

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier. Below table lists all of the Java keywords including one new one for 5.0, enum.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
Examples of legal and illegal identifiers follow, first some legal identifiers:

  int _a;
  int $c;
  int ______2_w;
  int _$;
  int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal:

  int :b;
  int -d;
  int e#;
  int .f;
  int 7g;

Complete List of Java Keywords (assert added in 1.4, enum added in 1.5)

abstractbooleanbreakbytecasecatch
charclassconstcontinuedefaultdo
doubleelseextendsfinalfinallyfloat
forgotoifimplementsimportinstanceof
intinterfacelongnativenewpackage
privateprotectedpublicreturnshortstatic
strictfpsuperswitchsynchronizedthisthrow
throwstransienttryvoidvolatilewhile
assertenum

Tuesday, August 31, 2010

Java : How to throw custom Exception

In java many times we required to throw our own custom Exception. We can throw our custom Exception by creation our own Exception class which will extend from class java.lang.Exception.

Before going to example lets look at few points about Exception Handling from book "Sun Certified Java Programmer SCJP 5" by Kathy sierra.

Handling Exceptions
  • Exceptions come in two flavors: checked and unchecked.
  • Checked exceptions include all subtypes of Exception, excluding classes
    that extend RuntimeException.
  • Checked exceptions are subject to the handle or declare rule; any method
    that might throw a checked exception (including methods that invoke methods
    that can throw a checked exception) must either declare the exception
    using throws, or handle the exception with an appropriate try/catch.
  • Subtypes of Error or RuntimeException are unchecked, so the compiler
    doesn't enforce the handle or declare rule. You're free to handle them, or to
    declare them, but the compiler doesn't care one way or the other.
  • If you use an optional finally block, it will always be invoked, regardless of
    whether an exception in the corresponding try is thrown or not, and regardless
    of whether a thrown exception is caught or not.
  • The only exception to the finally-will-always-be-called rule is that a finally
    will not be invoked if the JVM shuts down. That could happen if code
    from the try or catch blocks calls System.exit().
  • Just because finally is invoked does not mean it will complete. Code in the
    finally block could itself raise an exception or issue a System.exit().
  • Uncaught exceptions propagate back through the call stack, starting from
    the method where the exception is thrown and ending with either the first
    method that has a corresponding catch for that exception type or a JVM
    shutdown (which happens if the exception gets to main(), and main() is
    "ducking" the exception by declaring it).
  • You can create your own exceptions, normally by extending Exception or
    one of its subtypes. Your exception will then be considered a checked exception,
    and the compiler will enforce the handle or declare rule for that exception.
  • All catch blocks must be ordered from most specific to most general.
    If you have a catch clause for both IOException and Exception, you must
    put the catch for IOException first in your code. Otherwise, the IOException
    would be caught by catch(Exception e), because a catch argument
    can catch the specified exception or any of its subtypes! The compiler will
    stop you from defining catch clauses that can never be reached.
  • Some exceptions are created by programmers, some by the JVM.

Lets see a simple example which will throw a custom Exception.

In this example we have a method acceptsEvenNumber(int number) which accepts only even number, it it encounters odd number it throws our custom Exception ie "MyException".
Here our class MyException extends java.lang.Exception also observe the constructor MyException(String message) which calls its super constructor.

To know more look API.

/* MyException.java */

public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
  
    //This method throws custom Exception
    public static void acceptsEvenNumber(int number) throws MyException {
      
        if(number %2 == 0) {
          
            System.out.println("It is Even number");
        }
        else {
          
            throw new MyException("Odd number not allowed");
        }
      
    }

    public static void main(String[] args) {
      
        try {
           

            //acceptsEvenNumber(23); //odd number
            acceptsEvenNumber(22); //even number
          
        } catch (MyException e) {
          
            e.printStackTrace();
        }
    }

}



Output

When Even Number

#>java MyException
It is Even number

When Odd Number

#>java MyException
MyException: Odd number not allowed
        at MyException.acceptsEvenNumber(MyException.java:16)
        at MyException.main(MyException.java:25)