Wednesday 13 November 2013



Java supports three types of comments. The first two are the // and the /* */. The third type is called a documentation comment. It begins with the character sequence /** and it ends with */.
Documentation comments allow you to embed information about your program into the program itself. You can then use the javadoc utility program to extract the information and put it into an HTML file.
Documentation comments make it convenient to document your programs.

The javadoc Tags:

The javadoc utility recognizes the following tags:
TagDescriptionExample
@authorIdentifies the author of a class.@author description
@deprecatedSpecifies that a class or member is deprecated.@deprecated description
{@docRoot}Specifies the path to the root directory of the current documentationDirectory Path
@exceptionIdentifies an exception thrown by a method.@exception exception-name explanation
{@inheritDoc}Inherits a comment from the immediate superclass.Inherits a comment from the immediate surperclass.
{@link}Inserts an in-line link to another topic.{@link name text}
{@linkplain}Inserts an in-line link to another topic, but the link is displayed in a plain-text font.Inserts an in-line link to another topic.
@paramDocuments a method's parameter.@param parameter-name explanation
@returnDocuments a method's return value.@return explanation
@seeSpecifies a link to another topic.@see anchor
@serialDocuments a default serializable field.@serial description
@serialDataDocuments the data written by the writeObject( ) or writeExternal( ) methods@serialData description
@serialFieldDocuments an ObjectStreamField component.@serialField name type description
@sinceStates the release when a specific change was introduced.@since release
@throwsSame as @exception.The @throws tag has the same meaning as the @exception tag.
{@value}Displays the value of a constant, which must be a static field.Displays the value of a constant, which must be a static field.
@versionSpecifies the version of a class.@version info

Documentation Comment:

After the beginning /**, the first line or lines become the main description of your class, variable, or method.
After that, you can include one or more of the various @ tags. Each @ tag must start at the beginning of a new line or follow an asterisk (*) that is at the start of a line.
Multiple tags of the same type should be grouped together. For example, if you have three @see tags, put them one after the other.
Here is an example of a documentation comment for a class:
/**
* This class draws a bar chart.
* @author Zara Ali
* @version 1.2
*/

What javadoc Outputs?

The javadoc program takes as input your Java program's source file and outputs several HTML files that contain the program's documentation.
Information about each class will be in its own HTML file. Java utility javadoc will also output an index and a hierarchy tree. Other HTML files can be generated.
Since different implementations of javadoc may work differently, you will need to check the instructions that accompany your Java development system for details specific to your version.

Example:

Following is a sample program that uses documentation comments. Notice the way each comment immediately precedes the item that it describes.
After being processed by javadoc, the documentation about the SquareNum class will be found in SquareNum.html.
import java.io.*;

/**
* This class demonstrates documentation comments.
* @author Ayan Amhed 
* @version 1.2
*/
public class SquareNum {
   /**
   * This method returns the square of num.
   * This is a multiline description. You can use
   * as many lines as you like.
   * @param num The value to be squared.
   * @return num squared.
   */
   public double square(double num) {
      return num * num;
   }
   /**
   * This method inputs a number from the user.
   * @return The value input as a double.
   * @exception IOException On input error.
   * @see IOException
   */
   public double getNumber() throws IOException {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader inData = new BufferedReader(isr);
      String str;
      str = inData.readLine();
      return (new Double(str)).doubleValue();
   }
   /**
   * This method demonstrates square().
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
   public static void main(String args[]) throws IOException
   {
      SquareNum ob = new SquareNum();
      double val;
      System.out.println("Enter value to be squared: ");
      val = ob.getNumber();
      val = ob.square(val);
      System.out.println("Squared value is " + val);
   }
}
Now, process above SquareNum.java file using javadoc utility as follows:
$ javadoc SquareNum.java
Loading source file SquareNum.java...
Constructing Javadoc information...
Standard Doclet version 1.5.0_13
Building tree for all the packages and classes...
Generating SquareNum.html...
SquareNum.java:39: warning - @return tag cannot be used\
                      in method with void return type.
Generating package-frame.html...
Generating package-summary.html...
Generating package-tree.html...
Generating constant-values.html...
Building index for all the packages and classes...
Generating overview-tree.html...
Generating index-all.html...
Generating deprecated-list.html...
Building index for all classes...
Generating allclasses-frame.html...
Generating allclasses-noframe.html...
Generating index.html...
Generating help-doc.html...
Generating stylesheet.css...
1 warning
$

AJAX Poll

The following example will demonstrate a poll where the result is shown without reloading.


Example Explained - The HTML Page

When a user choose an option above, a function called "getVote()" is executed. The function is triggered by the "onclick" event:
<html>
<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("poll").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>
The getVote() function does the following:
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":
<?php
$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
  {
  $yes = $yes + 1;
  }
if ($vote == 1)
  {
  $no = $no + 1;
  }

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
The value is sent from the JavaScript, and the following happens:
  1. Get the content of the "poll_result.txt" file
  2. Put the content of the file in variables and add one to the selected variable
  3. Write the result to the "poll_result.txt" file
  4. Output a graphical representation of the poll result

The Text File

The text file (poll_result.txt) is where we store the data from the poll.
It is stored like this:
0||0
The first number represents the "Yes" votes, the second number represents the "No" votes.
Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just the web server (PHP).
The PHP array functions are part of the PHP core. No installation is required to use these functions.
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made function, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array recursively
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_replace() Replaces the values of the first array with the values from following arrays
array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an array
arsort() Sorts an associative array in descending order, according to the value
asort() Sorts an associative array in ascending order, according to the value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an associative array in descending order, according to the key
ksort() Sorts an associative array in ascending order, according to the key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive "natural order" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
uasort() Sorts an array by values using a user-defined comparison function
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function
The calendar extension contains functions that simplifies converting between different calendar formats.
It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C.
Note: To convert between calendar formats, you must first convert to Julian Day Count, then to the calendar of your choice.
Note: The Julian Day Count is not the same as the Julian Calendar!

Installation

For these functions to work, you have to compile PHP with --enable-calendar.
The Windows version of PHP has built-in support for this extension.

PHP 5 Calendar Functions

Function Description
cal_days_in_month() Returns the number of days in a month for a specified year and calendar
cal_from_jd() Converts a Julian Day Count into a date of a specified calendar
cal_info() Returns information about a specified calendar
cal_to_jd() Converts a date in a specified calendar to Julian Day Count
easter_date() Returns the Unix timestamp for midnight on Easter of a specified year
easter_days() Returns the number of days after March 21, that the Easter Day is in a specified year
frenchtojd() Converts a French Republican date to a Julian Day Count
gregoriantojd() Converts a Gregorian date to a Julian Day Count
jddayofweek() Returns the day of the week
jdmonthname() Returns a month name
jdtofrench() Converts a Julian Day Count to a French Republican date
jdtogregorian() Converts a Julian Day Count to a Gregorian date
jdtojewish() Converts a Julian Day Count to a Jewish date
jdtojulian() Converts a Julian Day Count to a Julian date
jdtounix() Converts Julian Day Count to Unix timestamp
jewishtojd() Converts a Jewish date to a Julian Day Count
juliantojd() Converts a Julian date to a Julian Day Count
unixtojd() Converts Unix timestamp to Julian Day Count

PHP 5 Predefined Calendar Constants

Constant Type PHP Version
CAL_GREGORIAN Integer PHP 4
CAL_JULIAN Integer PHP 4
CAL_JEWISH Integer PHP 4
CAL_FRENCH Integer PHP 4
CAL_NUM_CALS Integer PHP 4
CAL_DOW_DAYNO Integer PHP 4
CAL_DOW_SHORT Integer PHP 4
CAL_DOW_LONG Integer PHP 4
CAL_MONTH_GREGORIAN_SHORT Integer PHP 4
CAL_MONTH_GREGORIAN_LONG Integer PHP 4
CAL_MONTH_JULIAN_SHORT Integer PHP 4
CAL_MONTH_JULIAN_LONG Integer PHP 4
CAL_MONTH_JEWISH Integer PHP 4
CAL_MONTH_FRENCH Integer PHP 4
CAL_EASTER_DEFAULT Integer PHP 4.3
CAL_EASTER_ROMAN Integer PHP 4.3
CAL_EASTER_ALWAYS_GREGORIAN Integer PHP 4.3
CAL_EASTER_ALWAYS_JULIAN Integer PHP 4.3
CAL_JEWISH_ADD_ALAFIM_GERESH Integer PHP 5.0
CAL_JEWISH_ADD_ALAFIM Integer PHP 5.0
CAL_JEWISH_ADD_GERESHAYIM Integer PHP 5.0
The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways.
Note: These functions depend on the locale settings of your server. Remember to take daylight saving time and leap years into consideration when working with these functions.

Installation

The PHP date/time functions are part of the PHP core. No installation is required to use these functions.

Runtime Configuration

The behavior of these functions is affected by settings in php.ini:
Name Description Default PHP Version
date.timezone The default timezone (used by all date/time functions) "" PHP 5.1
date.default_latitude The default latitude (used by date_sunrise() and date_sunset())  "31.7667" PHP 5.0
date.default_longitude The default longitude (used by date_sunrise() and date_sunset()) "35.2333" PHP 5.0
date.sunrise_zenith The default sunrise zenith (used by date_sunrise() and date_sunset()) "90.83" PHP 5.0
date.sunset_zenith The default sunset zenith (used by date_sunrise() and date_sunset()) "90.83" PHP 5.0


PHP 5 Date/Time Functions

Function Description
checkdate() Validates a Gregorian date
date_add() Adds days, months, years, hours, minutes, and seconds to a date
date_create_from_format() Returns a new DateTime object formatted according to a specified format
date_create() Returns a new DateTime object
date_date_set() Sets a new date
date_default_timezone_get() Returns the default timezone used by all date/time functions
date_default_timezone_set() Sets the default timezone used by all date/time functions
date_diff() Returns the difference between two dates
date_format() Returns a date formatted according to a specified format
date_get_last_errors() Returns the warnings/errors found in a date string
date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of the string
date_interval_format() Formats the interval
date_isodate_set() Sets the ISO date
date_modify() Modifies the timestamp
date_offset_get() Returns the timezone offset
date_parse_from_format() Returns an associative array with detailed info about a specified date, according to a specified format
date_parse() Returns an associative array with detailed info about a specified date
date_sub() Subtracts days, months, years, hours, minutes, and seconds from a date
date_sun_info() Returns an array containing info about sunset/sunrise and twilight begin/end, for a specified day and location
date_sunrise() Returns the sunrise time for a specified day and location
date_sunset() Returns the sunset time for a specified day and location
date_time_set() Sets the time
date_timestamp_get() Returns the Unix timestamp
date_timestamp_set() Sets the date and time based on a Unix timestamp
date_timezone_get() Returns the time zone of the given DateTime object
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local date and time
getdate() Returns date/time information of a timestamp or the current local date/time
gettimeofday() Returns the current time
gmdate() Formats a GMT/UTC date and time
gmmktime() Returns the Unix timestamp for a GMT date
gmstrftime() Formats a GMT/UTC date and time according to locale settings
idate() Formats a local time/date as integer
localtime() Returns the local time
microtime() Returns the current Unix timestamp with microseconds
mktime() Returns the Unix timestamp for a date
strftime() Formats a local time and/or date according to locale settings
strptime() Parses a time/date generated with strftime()
strtotime() Parses an English textual datetime into a Unix timestamp
time() Returns the current time as a Unix timestamp
timezone_abbreviations_list() Returns an associative array containing dst, offset, and the timezone name
timezone_identifiers_list() Returns an indexed array with all timezone identifiers
timezone_location_get() Returns location information for a specified timezone
timezone_name_from_ abbr() Returns the timezone name from abbreviation
timezone_name_get() Returns the name of the timezone
timezone_offset_get() Returns the timezone offset from GMT
timezone_open() Creates new DateTimeZone object
timezone_transitions_get() Returns all transitions for the timezone
timezone_version_get() Returns the version of the timezone db


PHP 5 Predefined Date/Time Constants

Constant Description
DATE_ATOM Atom (example: 2005-08-15T16:13:03+0000)
DATE_COOKIE HTTP Cookies (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_ISO8601 ISO-8601 (example: 2005-08-14T16:13:03+0000)
DATE_RFC822 RFC 822 (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_RFC850 RFC 850 (example: Sunday, 14-Aug-05 16:13:03 UTC)
DATE_RFC1036 RFC 1036 (example: Sunday, 14-Aug-05 16:13:03 UTC)
DATE_RFC1123 RFC 1123 (example: Sun, 14 Aug 2005 16:13:03 UTC)
DATE_RFC2822 RFC 2822 (Sun, 14 Aug 2005 16:13:03 +0000)
DATE_RSS RSS (Sun, 14 Aug 2005 16:13:03 UTC)
DATE_W3C World Wide Web Consortium (example: 2005-08-14T16:13:03+0000)