WP Notes 3year It
WP Notes 3year It
SCRIPTING.
Web page Designing using HTML, Scripting basics- Client side and server side scripting.
Java Script-Object, names, literals, operators and expressions- statements and features- events
- windows -documents - frames - data types - built-in functions- Browser object model -
Verifying forms.-HTML5-CSS3- HTML 5 canvas - Web site creation using tools.
</body>
</html>
Step 3: Save the HTML Page
Save the file on your computer. Select File > Save as in the Notepad menu.
Name the file "index.htm" and set the encoding to UTF-8 (which is the preferred encoding
for HTML files).
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Scripting Basics:
A shell script is a computer program designed to be run by the Unix/Linux shell which could
be one of the following:
• The Bourne Shell
• The C Shell
• The Korn Shell
• The GNU Bourne-Again Shell
A shell is a command-line interpreter and typical operations performed by shell scripts
include file manipulation, program execution, and printing text.
Extended Shell Scripts
Shell scripts have several required constructs that tell the shell environment what to do and
when to do it. Of course, most scripts are more complex than the above one.
The shell is, after all, a real programming language, complete with variables, control
structures, and so forth. No matter how complicated a script gets, it is still just a list of
commands executed sequentially.
The following script uses the read command which takes the input from the keyboard and
assigns it as the value of the variable PERSON and finally prints it on STDOUT.
#!/bin/sh
JavaScript Primitives
A primitive value is a value that has no properties or methods.
A primitive data type is data that has a primitive value.
JavaScript defines 5 types of primitive data types:
• string
• number
• boolean
• null
• undefined
Primitive values are immutable (they are hardcoded and therefore cannot be changed).
if x = 3.14, you can change the value of x. But you cannot change the value of 3.14.
Objects are Variables
JavaScript variables can contain single values:
Example
var person = "John Doe";
Objects are variables too. But objects can contain many values.
The values are written as name : value pairs (name and value separated by a colon).
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Object Properties
The named values, in JavaScript objects, are called properties.
Property Value
firstName John
lastName Doe
age 50
eyeColor Blue
Objects written as name value pairs are similar to:
• Associative arrays in PHP
• Dictionaries in Python
• Hash tables in C
• Hash maps in Java
• Hashes in Ruby and Perl
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor Blue
var x = person;
x.age = 10; // This will change both x.age and person.age
java scripting names, Literals:
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
Enabling JavaScript in Browsers
All the modern browsers come with built-in support for JavaScript. Frequently, you may
need to enable or disable this support manually. This chapter explains the procedure of
enabling and disabling JavaScript support in your browsers: Internet Explorer, Firefox,
chrome, and Opera.
JavaScript in Internet Explorer
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
• Follow Tools → Internet Options from the menu.
• Select Security tab from the dialog box.
• Click the Custom Level button.
• Scroll down till you find Scripting option.
• Select Enable radio button under Active scripting.
• Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio
button under Active scripting.
JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox −
• Open a new tab → type about: config in the address bar.
• Then you will find the warning dialog. Select I’ll be careful, I promise!
• Then you will find the list of configure options in the browser.
• In the search bar, type javascript.enabled.
• There you will find the option to enable or disable javascript by right-clicking on the
value of that option → select toggle.
If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is
disabled; it gets enabled upon clicking toggle.
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome −
• Click the Chrome menu at the top right hand corner of your browser.
• Select Settings.
• Click Show advanced settings at the end of the page.
• Under the Privacy section, click the Content settings button.
• In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow
all sites to run JavaScript (recommended)".
JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera −
• Follow Tools → Preferences from the menu.
• Select Advanced option from the dialog box.
• Select Content from the listed items.
• Select Enable JavaScript checkbox.
• Finally click OK and come out.
To disable JavaScript support in your Opera, you should not select the Enable JavaScript
checkbox.
Warning for Non-JavaScript Browsers
If you have to do something important using JavaScript, then you can display a warning
message to the user using <noscript> tags.
You can add a noscript block immediately after the script block as follows −
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the
message from </noscript> will be displayed on the screen.
JavaScript - Placement in HTML File
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows −
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.
JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows −
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
This code will produce the following results −
JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, you would not have
any function defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
JavaScript - Variables
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types −
• Numbers, eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines
only a single value. In addition to these primitive data types, JavaScript supports a
composite data type known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point
values. All numbers in JavaScript are represented as floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought
of as named containers. You can place data into these containers and then refer to the data
simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable
initialization at the time of variable creation or at a later point in time when you need that
variable.
For instance, you might create a variable named money and assign the value 2000.50 to it
later. For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during
variable declaration what type of value the variable will hold. The value type of a variable
can change during the execution of a program and JavaScript takes care of it automatically.
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.
• Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with
the same name. If you declare a local variable or function parameter with the same name as
a global variable, you effectively hide the global variable. Take a look into the following
example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind.
• You should not use any of the JavaScript reserved keywords as a variable name.
These keywords are mentioned in the next section. For
example, break or boolean variable names are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must begin
with a letter or an underscore character. For example, 123test is an invalid variable
name but _123test is a valid one.
• JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.
JavaScript Reserved Words
A list of all the reserved words in JavaScript are given in the following table. They cannot be
used as JavaScript variables, functions, methods, loop labels, or any object names.
abstract else instanceof switch
boolean enum int synchronized
double in super
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and
‘+’ is called the operator. JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give
"a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal, then the
condition becomes true.
Ex: (A != B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
Ex: ! (A && B) is false.
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
Exclusive OR means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. Shifting a value left by one position is
equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4,
and so on.
Ex: (A << 1) is 4.
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
The following code shows how to implement typeof operator.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
var a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
ADVERTISEMENT
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.
The following lines are equivalent:
var person = "Hege";
var person="Hege";
A good practice is to put spaces around operators ( = + - * / ):
var x = y + z;
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Visit our Reserved Words reference to view a full list of JavaScript keywords.
Here is a list of some of the keywords you will learn about in this tutorial:
JavaScript Events
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time
is?</button>
In the example above, the JavaScript code changes the content of the element with
id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event attributes calling
functions:
Example
<button onclick="displayDate()">The time is?</button>
ADVERTISEMENT
Documents:
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
The HTML DOM Tree of Objects
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
Browser Support
Syntax
window.frames
More Examples
Example
Loop through all frames on a page, and change the location of all frames to "w3schools.com":
var frames = window.frames;
var i;
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
var carName1 = "Volvo XC60"; // Using double quotes
var carName2 = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the
Example
var answer1 = "It's alright"; // Single quote inside double quotes
var answer2 = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer3 = 'He is called "Johnny"'; // Double quotes inside single quotes
You will learn more about strings later in this tutorial.
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
You will learn more about numbers later in this tutorial.
JavaScript Booleans
Booleans can only have two values: true or false.
Example
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
Booleans are often used in conditional testing.
You will learn more about conditional testing later in this tutorial.
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car
names):
Example
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
You will learn more about arrays later in this tutorial.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
You will learn more about objects later in this tutorial.
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Example
var car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also
be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
var car = ""; // The value is "", the typeof is "string"
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can empty an object by setting it to null:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
Primitive Data
A primitive data value is a single simple data value with no additional properties and
methods.
The typeof operator can return one of these primitive types:
• string
• number
• boolean
• undefined
Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof false // Returns "boolean"
typeof x // Returns "undefined" (if x has no value)
Complex Data
The typeof operator can return one of two complex types:
• function
• object
The typeof operator returns "object" for objects, arrays, and null.
The typeof operator does not return "object" for functions.
Example
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4] // Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
Built-in Functions:
Number Methods
The Number object contains only the default methods that are part of every object's
definition.
Sr.No. Method & Description
1 constructor()
Returns the function that created this object's instance. By default this is the Number
object.
2 toExponential()
Forces a number to display in exponential notation, even if the number is in the range in
which JavaScript normally uses standard notation.
3 toFixed()
Formats a number with a specific number of digits to the right of the decimal.
4 toLocaleString()
Returns a string value version of the current number in a format that may vary according
to a browser's locale settings.
5 toPrecision()
Defines how many total digits (including digits to the left and right of the decimal) to
display of a number.
6 toString()
Returns the string representation of the number's value.
7 valueOf()
Returns the number's value.
Boolean Methods
Here is a list of each method and its description.
Sr.No. Method & Description
1 toSource()
Returns a string containing the source of the Boolean object; you can use this string to
create an equivalent object.
2 toString()
Returns a string of either "true" or "false" depending upon the value of the object.
3 valueOf()
Returns the primitive value of the Boolean object.
String Methods
Here is a list of each method and its description.
Sr.No. Method & Description
1 charAt()
Returns the character at the specified index.
2 charCodeAt()
Returns a number indicating the Unicode value of the character at the given index.
3 concat()
Combines the text of two strings and returns a new string.
4 indexOf()
Returns the index within the calling String object of the first occurrence of the specified
value, or -1 if not found.
5 lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified
value, or -1 if not found.
6 localeCompare()
Returns a number indicating whether a reference string comes before or after or is the
same as the given string in sort order.
7 length()
Returns the length of the string.
8 match()
Used to match a regular expression against a string.
9 replace()
Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
10 search()
Executes the search for a match between a regular expression and a specified string.
11 slice()
Extracts a section of a string and returns a new string.
12 split()
Splits a String object into an array of strings by separating the string into substrings.
13 substr()
Returns the characters in a string beginning at the specified location through the specified
number of characters.
14 substring()
Returns the characters in a string between two indexes into the string.
15 toLocaleLowerCase()
The characters within a string are converted to lower case while respecting the current
locale.
16 toLocaleUpperCase()
The characters within a string are converted to upper case while respecting the current
locale.
17 toLowerCase()
Returns the calling string value converted to lower case.
18 toString()
Returns a string representing the specified object.
19 toUpperCase()
Returns the calling string value converted to uppercase.
20 valueOf()
Returns the primitive value of the specified object.
String HTML wrappers
Here is a list of each method which returns a copy of the string wrapped inside the
appropriate HTML tag.
Sr.No. Method & Description
1 anchor()
Creates an HTML anchor that is used as a hypertext target.
2 big()
Creates a string to be displayed in a big font as if it were in a <big> tag.
3 blink()
Creates a string to blink as if it were in a <blink> tag.
4 bold()
Creates a string to be displayed as bold as if it were in a <b> tag.
5 fixed()
Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
6 fontcolor()
Causes a string to be displayed in the specified color as if it were in a <font
color="color"> tag.
7 fontsize()
Causes a string to be displayed in the specified font size as if it were in a <font
size="size"> tag.
8 italics()
Causes a string to be italic, as if it were in an <i> tag.
9 link()
Creates an HTML hypertext link that requests another URL.
10 small()
Causes a string to be displayed in a small font, as if it were in a <small> tag.
11 strike()
Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
12 sub()
Causes a string to be displayed as a subscript, as if it were in a <sub> tag
13 sup()
Causes a string to be displayed as a superscript, as if it were in a <sup> tag
Array Methods
Here is a list of each method and its description.
Sr.No. Method & Description
1 concat()
Returns a new array comprised of this array joined with other array(s) and/or value(s).
2 every()
Returns true if every element in this array satisfies the provided testing function.
3 filter()
Creates a new array with all of the elements of this array for which the provided filtering
function returns true.
4 forEach()
Calls a function for each element in the array.
5 indexOf()
Returns the first (least) index of an element within the array equal to the specified value,
or -1 if none is found.
6 join()
Joins all elements of an array into a string.
7 lastIndexOf()
Returns the last (greatest) index of an element within the array equal to the specified
value, or -1 if none is found.
8 map()
Creates a new array with the results of calling a provided function on every element in
this array.
9 pop()
Removes the last element from an array and returns that element.
10 push()
Adds one or more elements to the end of an array and returns the new length of the array.
11 reduce()
Apply a function simultaneously against two values of the array (from left-to-right) as to
reduce it to a single value.
12 reduceRight()
Apply a function simultaneously against two values of the array (from right-to-left) as to
reduce it to a single value.
13 reverse()
Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.
14 shift()
Removes the first element from an array and returns that element.
15 slice()
Extracts a section of an array and returns a new array.
16 some()
Returns true if at least one element in this array satisfies the provided testing function.
17 toSource()
Represents the source code of an object
18 sort()
Sorts the elements of an array.
19 splice()
Adds and/or removes elements from an array.
20 toString()
Returns a string representing the array and its elements.
21 unshift()
Adds one or more elements to the front of an array and returns the new length of the array.
Date Methods
Here is a list of each method and its description.
Sr.No. Method & Description
1 Date()
Returns today's date and time
2 getDate()
Returns the day of the month for the specified date according to local time.
3 getDay()
Returns the day of the week for the specified date according to local time.
4 getFullYear()
Returns the year of the specified date according to local time.
5 getHours()
Returns the hour in the specified date according to local time.
6 getMilliseconds()
Returns the milliseconds in the specified date according to local time.
7 getMinutes()
Returns the minutes in the specified date according to local time.
8 getMonth()
Returns the month in the specified date according to local time.
9 getSeconds()
Returns the seconds in the specified date according to local time.
10 getTime()
Returns the numeric value of the specified date as the number of milliseconds since
January 1, 1970, 00:00:00 UTC.
11 getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
12 getUTCDate()
Returns the day (date) of the month in the specified date according to universal time.
13 getUTCDay()
Returns the day of the week in the specified date according to universal time.
14 getUTCFullYear()
Returns the year in the specified date according to universal time.
15 getUTCHours()
Returns the hours in the specified date according to universal time.
16 getUTCMilliseconds()
Returns the milliseconds in the specified date according to universal time.
17 getUTCMinutes()
Returns the minutes in the specified date according to universal time.
18 getUTCMonth()
Returns the month in the specified date according to universal time.
19 getUTCSeconds()
Returns the seconds in the specified date according to universal time.
20 getYear()
Deprecated - Returns the year in the specified date according to local time. Use
getFullYear instead.
21 setDate()
Sets the day of the month for a specified date according to local time.
22 setFullYear()
Sets the full year for a specified date according to local time.
23 setHours()
Sets the hours for a specified date according to local time.
24 setMilliseconds()
Sets the milliseconds for a specified date according to local time.
25 setMinutes()
Sets the minutes for a specified date according to local time.
26 setMonth()
Sets the month for a specified date according to local time.
27 setSeconds()
Sets the seconds for a specified date according to local time.
28 setTime()
Sets the Date object to the time represented by a number of milliseconds since January 1,
1970, 00:00:00 UTC.
29 setUTCDate()
Sets the day of the month for a specified date according to universal time.
30 setUTCFullYear()
Sets the full year for a specified date according to universal time.
31 setUTCHours()
Sets the hour for a specified date according to universal time.
32 setUTCMilliseconds()
Sets the milliseconds for a specified date according to universal time.
33 setUTCMinutes()
Sets the minutes for a specified date according to universal time.
34 setUTCMonth()
Sets the month for a specified date according to universal time.
35 setUTCSeconds()
Sets the seconds for a specified date according to universal time.
36 setYear()
Deprecated - Sets the year for a specified date according to local time. Use setFullYear
instead.
37 toDateString()
Returns the "date" portion of the Date as a human-readable string.
38 toGMTString()
Deprecated - Converts a date to a string, using the Internet GMT conventions. Use
toUTCString instead.
39 toLocaleDateString()
Returns the "date" portion of the Date as a string, using the current locale's conventions.
40 toLocaleFormat()
Converts a date to a string, using a format string.
41 toLocaleString()
Converts a date to a string, using the current locale's conventions.
42 toLocaleTimeString()
Returns the "time" portion of the Date as a string, using the current locale's conventions.
43 toSource()
Returns a string representing the source for an equivalent Date object; you can use this
value to create a new object.
44 toString()
Returns a string representing the specified Date object.
45 toTimeString()
Returns the "time" portion of the Date as a human-readable string.
46 toUTCString()
Converts a date to a string, using the universal time convention.
47 valueOf()
Returns the primitive value of a Date object.
Date Static Methods
In addition to the many instance methods listed previously, the Date object also defines two
static methods. These methods are invoked through the Date( ) constructor itself −
Sr.No. Method & Description
1 Date.parse( )
Parses a string representation of a date and time and returns the internal millisecond
representation of that date.
2 Date.UTC( )
Returns the millisecond representation of the specified UTC date and time.
Math Methods
Here is a list of each method and its description.
Sr.No. Method & Description
1 abs()
Returns the absolute value of a number.
2 acos()
Returns the arccosine (in radians) of a number.
3 asin()
Returns the arcsine (in radians) of a number.
4 atan()
Returns the arctangent (in radians) of a number.
5 atan2()
Returns the arctangent of the quotient of its arguments.
6 ceil()
Returns the smallest integer greater than or equal to a number.
7 cos()
Returns the cosine of a number.
8 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base of the natural
logarithm.
9 floor()
Returns the largest integer less than or equal to a number.
10 log()
Returns the natural logarithm (base E) of a number.
11 max()
Returns the largest of zero or more numbers.
12 min()
Returns the smallest of zero or more numbers.
13 pow()
Returns base to the exponent power, that is, base exponent.
14 random()
Returns a pseudo-random number between 0 and 1.
15 round()
Returns the value of a number rounded to the nearest integer.
16 sin()
Returns the sine of a number.
17 sqrt()
Returns the square root of a number.
18 tan()
Returns the tangent of a number.
19 toSource()
Returns the string "Math".
RegExp Methods
Here is a list of each method and its description.
1 exec()
Executes a search for a match in its string parameter.
2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this value to create
a new object.
4 toString()
Returns a string representing the specified object.
Window Size
Two properties can be used to determine the size of the browser window.
Both properties return the sizes in pixels:
• window.innerHeight - the inner height of the browser window (in pixels)
• window.innerWidth - the inner width of the browser window (in pixels)
For Internet Explorer 8, 7, 6, 5:
• document.documentElement.clientHeight
• document.documentElement.clientWidth
• or
• document.body.clientHeight
• document.body.clientWidth
A practical JavaScript solution (covering all browsers):
Example
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
The example displays the browser window's height and width: (NOT including
toolbars/scrollbars)
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the client
and request that the form be resubmitted with correct information. This was really a lengthy
process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it
to the web server. Form validation generally performs two functions.
• Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in the
form and check for data.
• Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test correctness
of data.
Example
We will take an example to understand the process of validation. Here is a simple form in
html format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
HTML5:
Easy Learning with HTML "Try it Yourself"
With our "Try it Yourself" editor, you can edit the HTML code and view the result:
Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Click on the "Try it Yourself" button to see how it works.
HTML Examples
In this HTML tutorial, you will find more than 200 examples. With our online "Try it
Yourself" editor, you can edit and test each example yourself!
CSS3:
What is CSS?
• CSS stands for Cascading Style Sheets
• CSS describes how HTML elements are to be displayed on screen, paper, or in
other media
• CSS saves a lot of work. It can control the layout of multiple web pages all at once
• External stylesheets are stored in CSS files
p{
font-family: verdana;
font-size: 20px;
}
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it
started a nightmare for web developers. Development of large websites, where fonts and
color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!
CSS Saves a Lot of Work!
The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by changing
just one file!
HTML 5 Canvas:
HTML Canvas Graphics
Browser Support
The numbers in the table specify the first browser version that fully supports
the <canvas> element.
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no
content.
The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
Note: Always specify an id attribute (to be referred to in a script), and
a width and height attribute to define the size of the canvas. To add a border, use
the style attribute.
Here is an example of a basic, empty canvas:
Example
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
Add a JavaScript
After creating the rectangular canvas area, you must add a JavaScript to do the drawing.
Here are some examples:
Draw a Line
Example
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
Draw a Circle
Example
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
Draw a Text
Example
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
</script>
Stroke Text
Example
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);
</script>
Draw Linear Gradient
Example
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
// Create gradient
var grd = ctx.createRadialGradient(75, 50, 5, 90, 60, 100);
grd.addColorStop(0, "red");
grd.addColorStop(1, "white");
Draw Image
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
</script>
Website creation using Tools:
Features of Java:
Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as java buzzwords.
A list of most important features of Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
A variable provides us with named storage that our programs can manipulate. Each variable
in Java has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable.
You must declare all variables before they can be used. Following is the basic form of a
variable declaration −
data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
This chapter will explain various variable types available in Java Language. There are three
kinds of variables in Java −
• Local variables
• Instance variables
• Class/Static variables
Local Variables
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to only this method.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators
Checks if the values of two operands are equal or not, if yes (A == B) is not
== (equal to)
then condition becomes true. true.
Checks if the value of left operand is greater than the value of (A > B) is not
> (greater than)
right operand, if yes then condition becomes true. true.
& (bitwise Binary AND Operator copies a bit to the result (A & B) will give 12 which is
and) if it exists in both operands. 0000 1100
^ (bitwise Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is
XOR) in one operand but not both. 0011 0001
Simple assignment operator. Assigns values from right side operands to C=A+
left side operand. B will
assign
=
value of
A+B
into C
Add AND assignment operator. It adds right operand to the left operand C += A is
and assign the result to left operand. equivalent
+=
to C = C
+A
Subtract AND assignment operator. It subtracts right operand from the left C -= A is
operand and assign the result to left operand. equivalent
-=
to C = C
–A
/= Divide AND assignment operator. It divides left operand with the right C /= A is
operand and assign the result to left operand. equivalent
to C = C /
A
C >>= 2
is same as
>>= Right shift AND assignment operator.
C = C >>
2
C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2
Output
true
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity
Control statements:
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate If statement
class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15
• nested-if: A nested if is an if statement that is the target of another if or else. Nested if
statements means an if statement inside an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
• if (condition1)
• {
• // Executes when condition1 is true
• if (condition2)
• {
• // Executes when condition2 is true
• }
• }
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12 too
• if-else-if ladder:
Here, a user can decide among multiple options.The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
• if (condition)
• statement;
• else if (condition)
• statement;
• .
• .
• else
• statement;
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output:
i is 20
switch-case
• The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:
• switch (expression)
• {
• case value1:
• statement1;
• break;
• case value2:
• statement2;
• break;
• .
• .
• case valueN:
• statementN;
• break;
• default:
• statementDefault;
}
• Expression can be of type byte, short, int char or an enumeration. Beginning with
JDK7, expression can also be of type String.
• Dulplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a statement sequence.
• The break statement is optional. If omitted, execution will continue on into the
next case.
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate switch-case
class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Output:
i is greater than 2.
•
• jump: Java supports three jump statement: break, continue and return. These three
statements transfer control to other part of the program.
• Break: In Java, break is majorly used for:
• Terminate a sequence in a switch statement (discussed above).
• To exit a loop.
• Used as a “civilized” form of goto.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the
innermost loop.
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate using
// break to exit a loop
class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
// label first
first:
{
// Illegal statement here as label second is not
// introduced yet break second;
second:
{
third:
{
// Before break
System.out.println("Before the break statement");
// First block
System.out.println("This is after second block.");
}
}
}
Output:
Before the break.
This is after second block.
• Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the
code in its body for this particular iteration. This is, in effect, a goto just past the
body of the loop, to the loop’s end. The continue statement performs such an
action.
Example:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate using
// continue in an if statement
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
myMethod() prints a text (the action), when it is called. To call a method, write the method's
name followed by two parentheses () and a semicolon;
Example
Inside main, call myMethod():
public class MyClass {
static void myMethod() {
System.out.println("Hello World!");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent
class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe
two classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.
Copy and paste the following program in a file with name My_Calculation.java
Example
class Calculation {
int z;
In the given program, when an object to My_Calculation class is created, a copy of the
contents of the superclass is made within it. That is why, using the object of the subclass you
can access the members of a superclass.
The Superclass reference variable can hold the subclass object, but using that variable you
can access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But using
the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.
• It is used to differentiate the members of superclass from the members of subclass,
if they have same names.
• It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super keyword
as shown below.
super.variable
super.method();
Sample Code
This section provides you a program that demonstrates the usage of the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both have a
method named display() with different implementations, and a variable named num with
different values. We are invoking display() method of both classes and printing the value of
the variable num of both classes. Here you can observe that we have used super keyword to
differentiate the members of superclass from subclass.
Copy and paste the program in a file with name Sub_class.java.
Example
class Super_class {
int num = 20;
Superclass(int age) {
this.age = age;
}
Output
true
true
true
HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain
class HAS-A certain thing. This relationship helps to reduce duplication of code as well as
bugs.
Lets look into an example −
Example
public class Vehicle{}
public class Speed{}
Types of Inheritance
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance. This
means that a class cannot extend more than one class. Therefore following is illegal −
Example
public class extends Animal, Mammal{}
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations
and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −
• java.lang − bundles the fundamental classes
• java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as shown
below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
Example
Let us look at an example that creates a package called animals. It is a good practice to use
names of packages with lower case letters to avoid any conflicts with the names of classes
and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal {
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
The import Keyword
If a class wants to use another class in the same package, the package name need not be
used. Classes in the same package find each other without any special syntax.
Example
Here, a class named Boss is added to the payroll package that already contains Employee.
The Boss can then refer to the Employee class without using the payroll prefix, as
demonstrated by the following Boss class.
package payroll;
public class Boss {
public void payEmployee(Employee e) {
e.mailCheck();
}
}
What happens if the Employee class is not in the payroll package? The Boss class must then
use one of the following techniques for referring to a class in a different package.
• The fully qualified name of the class can be used. For example −
payroll.Employee
• The package can be imported using the import keyword and the wild card (*). For
example −
import payroll.*;
• The class itself can be imported using the import keyword. For example −
import payroll.Employee;
Note − A class file can contain any number of import statements. The import statements
must appear after the package statement and before the class declaration.
The Directory Structure of Packages
Two major results occur when a class is placed in a package −
• The name of the package becomes a part of the name of the class, as we just
discussed in the previous section.
• The name of the package must match the directory structure where the corresponding
bytecode resides.
Here is simple way of managing your files in Java −
Put the source code for a class, interface, enumeration, or annotation type in a text file
whose name is the simple name of the type and whose extension is .java.
For example −
// File Name : Car.java
package vehicle;
class Ups {
}
Now, compile this file as follows using -d option −
$javac -d . Dell.java
The files will be compiled as follows −
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that
reflect the package name. However, the path to the .class files does not have to be the same
as the path to the .java source files. You can arrange your source and class directories
separately, as −
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class
By doing this, it is possible to give access to the classes directory to other programmers
without revealing your sources. You also need to manage source and class files in this
manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your
program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set
with the CLASSPATH system variable. Both the compiler and the JVM construct the path
to your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers,
then the compiler and JVM will look for .class files in <path-
two>\classes\com\apple\computers.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current
directory and the JAR file containing the Java platform classes so that these directories are
automatically in the class path.
Set CLASSPATH System Variable
To display the current CLASSPATH variable, use the following commands in Windows and
UNIX (Bourne shell) −
• In Windows → C:\> set CLASSPATH
• In UNIX → % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use −
• In Windows → C:\> set CLASSPATH =
• In UNIX → % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable −
• In Windows → set CLASSPATH = C:\users\jack\java\classes
• In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH
Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare
an interface −
Example
Following is an example of an interface −
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
Exception Handling:
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to
know how exception handling works in Java.
• Checked exceptions − A checked exception is an exception that is checked (notified)
by the compiler at compilation-time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored, the programmer should take
care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
import java.io.File;
import java.io.FileReader;
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled
by the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from
errors.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
Following is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods
Following is the list of important methods available in the Throwable class.
Sr.No. Method & Description
Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks like
the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.
Example
The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple Catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example
Here is code segment showing how to use multiple try/catch statements.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
Catching Multiple Type of Exceptions
Since Java 7, you can handle more than one exception using a single catch block, this feature
simplifies the code. Here is how you would do it −
catch (IOException|FileNotFoundException ex) {
logger.log(ex);
throw ex;
The Throws/Throw Keywords
If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException −
Example
import java.io.*;
public class className {
You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes −
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the Handle
or Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException
class.
We can define our own Exception class as below −
class MyException extends Exception {
}
You just need to extend the predefined Exception class to create your own Exception. These
are considered to be checked exceptions. The following InsufficientFundsException class
is a user-defined exception that extends the Exception class, making it a checked exception.
An exception class is like any other class, containing useful fields and methods.
Example
// File Name InsufficientFundsException.java
import java.io.*;
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo. This will produce the following result
−
Output
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Common Exceptions
Multithreaded Programming:
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the same time making optimal
use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread
A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.
Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and are very much platform dependent.
Create a Thread by Implementing a Runnable Interface
If your class is intended to be executed as a thread then you can achieve this by
implementing a Runnable interface. You will need to follow three basic steps −
Step 1
As a first step, you need to implement a run() method provided by a Runnable interface.
This method provides an entry point for the thread and you will put your complete business
logic inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
Step 3
Once a Thread object is created, you can start it by calling start() method, which executes a
call to run( ) method. Following is a simple syntax of start() method −
void start();
Example
Here is an example that creates a new thread and starts running it −
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread Methods
Following is the list of important methods available in the Thread class.
Sr.No. Method & Description
Following is the main program, which makes use of the above-defined classes −
// File Name : ThreadClassDemo.java
public class ThreadClassDemo {
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
This will produce the following result. You can try this example again and again and you
will get a different result every time.
Output
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
Input/output Files:
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, object, localized
characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
• InPutStream − The InputStream is used to read data from a source.
• OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this
tutorial covers very basic functionality related to streams and I/O. We will see the most
commonly used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. If you
are aware of C or C++ programming languages, then you must be aware of three standard
devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three
standard streams −
• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's program
and usually a computer screen is used for standard output stream and represented
as System.out.
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.
Following is a simple program, which creates InputStreamReader to read standard input
stream until the user types a "q" −
Example
import java.io.*;
public class ReadConsole {
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as
shown in the following program. This program continues to read and output the same
character until we press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read
the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file.
First we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can
be used to read to stream or to do other operations on the stream.
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a
file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write
the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file.
First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which
can be used to write to stream or to do other operations on the stream.
Example
Following is the example to demonstrate InputStream and OutputStream −
import java.io.*;
public class fileStreamTest {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
Example
import java.io.File;
public class CreateDir {
try {
// create new file object
file = new File("/tmp");
Output
test1.txt
test2.txt
ReadDir.java
ReadDir.class
Utility Classes:
Introduction
The Collections utility class consists exclusively of static methods that operate on or return
collections. It contains polymorphic algorithms that operate on collections, "wrappers", which
return a new collection backed by a specified collection,
Some useful method in Collections class:
Let's take the example of List sorting using Collection class. We can sort any Collection
using “Collections” utility class. i.e.; ArrayList of Strings can be sorted alphabetically using
this utility class. ArrayList class itself is not providing any methods to sort. We use
Collections class static methods to do this. Below program shows use of reverse(), shuffle(),
frequency() methods as well.
Java Code:
package utility;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
Collections.sort(studentList);
System.out.println("Sorted alphabetically List " + studentList);
Collections.reverse(studentList);
System.out.println("Reverse List " + studentList);
Collections.shuffle(studentList);
System.out.println("Shuffled List " + studentList);
System.out.println("Checking occurance of Neeraj: "
+ Collections.frequency(studentList, "Neeraj"));
}
}
Output:
String Handling:
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
We will discuss immutable string later. Let's first understand what is String in Java and how
to create the String object.
Java Utility Classes continue:
Collections.copy(List dest, List src) Copy the source List into dest List.
JDBC Overview:
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.
Why to Learn JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your
data sources.
The new features in these packages include changes in the following areas −
• Automatic database driver loading.
• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.
Audience
This tutorial is designed for Java programmers who would like to understand the JDBC
framework in detail along with its architecture and actual usage.
JDBC Implementation:
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
Pre-Requisite
Before moving further, you need to have a good understanding of the following two subjects
−
• Core JAVA Programming
• SQL or MySQL Database
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
• JDBC API: This provides the application-to-JDBC Manager connection.
• JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
Common JDBC Components
The JDBC API provides the following interfaces and classes −
• DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
• Driver: This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.
• Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
• Statement: You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.
• ResultSet: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
• SQLException: This class handles any errors that occur in a database application.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your
data sources.
The new features in these packages include changes in the following areas −
• Automatic database driver loading.
• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.
Connection class:
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences between Java and SQL data
types used in a database.
The following table provides a summary of each interface's purpose to decide on the
interface to use.
Interfaces Recommended Use
Statement Use this for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot
accept parameters.
PreparedStatement Use this when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use this when you want to access the database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
The Statement Objects
Creating Statement Object
Before you can use a Statement object to execute a SQL statement, you need to create one
using the Connection object's createStatement( ) method, as in the following example −
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
...
}
Once you've created a Statement object, you can then use it to execute an SQL statement
with one of its three execute methods.
• boolean execute (String SQL): Returns a boolean value of true if a ResultSet object
can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL
statements or when you need to use truly dynamic SQL.
• int executeUpdate (String SQL): Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for
which you expect to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.
• ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method
when you expect to get a result set, as you would with a SELECT statement.
Closing Statement Object
Just as you close a Connection object to save database resources, for the same reason you
should also close the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first,
it will close the Statement object as well. However, you should always explicitly close the
Statement object to ensure proper cleanup.
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
stmt.close();
}
For a better understanding, we suggest you to study the Statement - Example tutorial.
The PreparedStatement Objects
The PreparedStatement interface extends the Statement interface, which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.
The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values,
you will receive an SQLException.
Each parameter marker is referred by its ordinal position. The first marker represents
position 1, the next position 2, and so forth. This method differs from that of Java array
indices, which starts at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.
However, the methods are modified to use SQL statements that can input the parameters.
Closing PreparedStatement Object
Just as you close a Statement object, for the same reason you should also close the
PreparedStatement object.
A simple call to the close() method will do the job. If you close the Connection object first,
it will close the PreparedStatement object as well. However, you should always explicitly
close the PreparedStatement object to ensure proper cleanup.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}
For a better understanding, let us study Prepare - Example Code.
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all the three.
Here are the definitions of each −
Parameter Description
IN A parameter whose value is unknown when the SQL statement is created. You
bind values to IN parameters with the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it returns. You
retrieve values from theOUT parameters with the getXXX() methods.
INOUT A parameter that provides both input and output values. You bind variables with
the setXXX() methods and retrieve values with the getXXX() methods.
The following code snippet shows how to employ the Connection.prepareCall() method to
instantiate a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
The String variable SQL, represents the stored procedure, with parameter placeholders.
Using the CallableStatement objects is much like using the PreparedStatement objects. You
must bind values to all the parameters before executing the statement, or you will receive an
SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type
you are binding.
When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The registerOutParameter() method
binds the JDBC data type, to the data type that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with
the appropriate getXXX() method. This method casts the retrieved value of SQL type to a
Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the
CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first,
it will close the CallableStatement object as well. However, you should always explicitly
close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}
This chapter provides an example of how to create a simple JDBC application. This will
show you how to open a database connection, execute a SQL query, and display the results.
All the steps mentioned in this template example, would be explained in subsequent chapters
of this tutorial.
Creating JDBC Application
There are following six steps involved in building a JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the
database.
• Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
• Extract data from result set: Requires that you use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set.
• Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Sample Code
This sample example can serve as a template when you need to create your own JDBC
application in the future.
This sample code has been written based on the environment and database setup done in the
previous chapter.
Copy and paste the following example in FirstExample.java, compile and run as follows −
//STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile the above example as follows −
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
The statement interface provides methods that are used to execute static SQL statements.
The SQL statements are queries, insertions, updates and deletions, etc.
Some of the methods of the Statement interface are as follows.
• void close(): This method closes database connections associated with Statement’s object
and releases JDBC resources.
• boolean execute (String sql): This method is used to execute an SQL statement that might
produce multiple result sets or multiple counts. It returns true if multiple result sets are
produced and returns false if multiple counts are generated.
• int executeUpdate(String sql): This method is used to execute an SQL statement that
gives information about number of affected rows. For example, if we execute the statements
like INSERT, DELETE, the result will only be a number of rows affected.
• ResultSet executeQuery(String sql): This method executes a query and returns a Resu1ts
et object. A result set isjust like a table containing the resultant data.
• ResultSet getResultSet () : This method returns the first result set or multiple count
generated on the execution of execute (String sql) method. If there is no result set, it returns
null value.
• int getUpdateCount():After the execution of the execute (String sql) method updates
counts may be generated. This method returns the first update count and clears it. More
update counts can be retrieved by getMoreResults ().Note that this method returns value -1 if
there is no update count or when only result sets are generated on execution of execute
(String sql) method.
• boolean getMoreResults () : This method is used to retrieve the next result set in multiple
result set or to the next count in multiple update count generated on execution of execute
(String sql) method. It returns a true value if multiple sets are available and returns a false
value if multiple update counts are available.
Networking:
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your
data sources.
The new features in these packages include changes in the following areas −
• Automatic database driver loading.
• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.
InetAddress Class:
URL Class:
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator.
It points to a resource on the World Wide Web. For example:
1. https://www.javatpoint.com/java-tutorial
TCP Sockets:
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection between serve
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10.
11. String str="",str2="";
12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}
File: MyClient.java
1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9.
10. String str="",str2="";
11. while(!str.equals("stop")){
12. str=br.readLine();
13. dout.writeUTF(str);
14. dout.flush();
15. str2=din.readUTF();
16. System.out.println("Server says: "+str2);
17. }
18.
19. dout.close();
20. s.close();
21. }}
UDP Sockets:
Arguments :
sockfd – File descriptor of socket to be binded
addr – Structure in which address to be binded to is specified
addrlen – Size of addr structure
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen)
Send a message on the socket
Arguments :
sockfd – File descriptor of socket
buf – Application buffer containing the data to be sent
len – Size of buf application buffer
flags – Bitwise OR of flags to modify socket behaviour
dest_addr – Structure containing address of destination
addrlen – Size of dest_addr structure
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen)
Receive a message from the socket.
Arguments :
sockfd – File descriptor of socket
buf – Application buffer in which to receive data
len – Size of buf application buffer
flags – Bitwise OR of flags to modify socket behaviour
src_addr – Structure containing source address is returned
addrlen – Variable in which size of src_addr structure is returned
int close(int fd)
Close a file descriptor
Arguments :
fd – File descriptor
In the below code, exchange of one hello message between server and client is shown to
demonstrate the model.
• UDPClient.c
filter_none
edit
play_arrow
brightness_4
// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
int n, len;
close(sockfd);
return 0;
}
Output :
$ ./server
Client : Hello from client
Hello message sent.
$ ./client
Hello message sent.
Server : Hello from server
Java Beans:
A JavaBean is a specially constructed Java class written in the Java and coded according to
the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes
−
• It provides a default, no-argument constructor.
• It should be serializable and that which can implement the Serializable interface.
• It may have a number of properties which can be read or written.
• It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −
S.No. Method & Description
getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.
setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only
attribute will have only a setPropertyName() method.
JavaBeans Example
Consider a student class with few properties −
package com.tutorialspoint;
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes
a scripting variable that can be accessed by both scripting elements and other custom tags
used in the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on
your requirement. The value of the id attribute may be any value as a long as it is a unique
name among other useBean declarations in the same JSP.
Following example shows how to use the useBean action −
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010
Accessing JavaBeans Properties
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access
the get methods and the <jsp:setProperty/> action to access the set methods. Here is the
full syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should
be invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −
Student First Name: Zara
Student Age: 10
RMI:
In the previous chapter, we created a sample RMI application where a client invokes a
method which displays a GUI window (JavaFX).
In this chapter, we will take an example to see how a client program can retrieve the records
of a table in MySQL database residing on the server.
Assume we have a table named student_data in the database details as shown below.
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
Assume the name of the user is myuser and its password is password.
Creating a Student Class
Create a Student class with setter and getter methods as shown below.
public class Student implements java.io.Serializable {
private int id, percent;
private String name, branch, email;
// Database credentials
String USER = "myuser";
String PASS = "password";
//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client Program
Following is the client program of this application. Here, we are fetching the remote object
and invoking the method named getStudents(). It retrieves the records of the table from the
list object and displays them.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
// System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}
// System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Steps to Run the Example
Following are the steps to run our RMI Example.
Step 1 − Open the folder where you have stored all the programs and compile all the Java
files as shown below.
Javac *.java
Step 2 − Start the rmi registry using the following command.
start rmiregistry
Java Applets:
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not define
main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Life Cycle of an Applet
Four methods in the Applet class gives you the framework on which you build any serious
applet −
• init − This method is intended for whatever initialization is needed for your applet. It
is called after the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It
is also called whenever the user returns to the page containing the applet after having
gone off to other pages.
• stop − This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally leave
resources behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from
the java.awt.
A "Hello, World" Applet
Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;
setBackground (Color.black);
setForeground (fg);
}
In this article we will learn about applet life cycle and various life cycle methods of an applet
along with example program.
init(): The init() method is the first method to execute when the applet is executed. Variable
declaration and initialization operations are performed in this method.
start(): The start() method contains the actual code of the applet that should run. The start()
method executes immediately after the init() method. It also executes whenever the applet is
restored, maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The stop() method executes when
the applet is minimized or when moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed. stop() method executes just before when destroy() method
is invoked. The destroy() method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet display area. The
paint() method executes after the execution of start() method and whenever the applet or
browser is resized.
• import java.awt.*;
• import java.applet.*;
• public class MyApplet extends Applet
• {
• public void init()
• {
• System.out.println("Applet initialized");
• }
• public void start()
• {
• System.out.println("Applet execution started");
• }
• public void stop()
• {
• System.out.println("Applet execution stopped");
• }
• public void paint(Graphics g)
• {
• System.out.println("Painting...");
• }
• public void destroy()
• {
• System.out.println("Applet destroyed");
• }
• }
• Output of the above applet program when run using appletviewer tool is:
• Applet initialized
Applet execution started
Painting…
Painting…
Applet execution stopped
Applet destroyed
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Problem Description
How to play sound using Applet?
Solution
Following example demonstrates how to play a sound using an applet image using
getAudioClip(), play() & stop() methods of AudioClip() class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
Event handling:
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple
in applet that prints a message by click on the button.
Example of EventHandling in applet:
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because
it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Introducing AWT:
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Introduction
The Graphics class is the abstract super class for all graphics contexts which allow an
application to draw onto components that can be realized on various devices, or onto off-
screen images as well.
A Graphics object encapsulates all state information required for the basic rendering
operations that Java supports. State information includes the following properties.
• The Component object on which to draw.
• A translation origin for rendering and clipping coordinates.
• The current clip.
• The current color.
• The current font.
• The current logical pixel operation function.
• The current XOR alternation color
Class declaration
Following is the declaration for java.awt.Graphics class:
public abstract class Graphics
extends Object
Class constructors
S.N. Constructor & Description
1 Graphics() ()
Constructs a new Graphics object.
Class methods
S.N. Method & Description
3 abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy.
8 abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
13 abstract boolean drawImage(Image img, int x, int y, int width, int height, Color
bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.
14 abstract boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.
15 abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling
it on the fly to fit inside the specified area of the destination drawable surface.
16 abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling
it on the fly to fit inside the specified area of the destination drawable surface.
17 abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this
graphics context's coordinate system.
20 void drawPolygon(Polygon p)
Draws the outline of a polygon defined by the specified Polygon object.
23 abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.
27 abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
28 abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
30 void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the graphics context's current
color.
32 abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Fills the specified rounded corner rectangle with the current color.
33 void finalize()
Disposes of this graphics context once it is no longer referenced.
36 Rectangle getClipBounds(Rectangle r)
Returns the bounding rectangle of the current clipping area.
37 Rectangle getClipRect()
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
40 FontMetrics getFontMetrics()
Gets the font metrics of the current font.
49 String toString()
Returns a String object representing this Graphics object's value.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
@Override
public void paint(Graphics g) {
g.setColor(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to TutorialsPoint", 50, 150);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following
command.
D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java
If no error comes that means compilation is successful. Run the program using following
command.
D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo
Verify the following output
1 Component
A Component is an abstract super class for GUI controls and it represents an object with
graphical representation.
AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.
Sr. Control & Description
No.
1 Label
A Label object is a component for placing text in a container.
2 Button
This class creates a labeled button.
3 Check Box
A check box is a graphical component that can be in either an on (true) or off (false) state.
5 List
The List component presents the user with a scrolling list of text items.
6 Text Field
A TextField object is a text component that allows for the editing of a single line of text.
7 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.
8 Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on the
top of the menu.
9 Canvas
A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
10 Image
An Image control is superclass for all image classes representing graphical images.
11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
12 Dialog
A Dialog control represents a top-level window with a title and a border used to take some
form of input from the user.
13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.
1 LayoutManager
The LayoutManager interface declares those methods which need to be implemented by the
class whose object will act as a layout manager.
2 LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those
classes that know how to layout containers based on layout constraint object.
AWT Layout Manager Classes:
Following is the list of commonly used controls while designed GUI using AWT.
Sr. LayoutManager & Description
No.
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4 GridLayout
The GridLayout manages the components in form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components
of same size.
Servlet:
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web
page.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api. The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Handling HTTP Request and Response:
An HTTP client sends an HTTP request to a server in the form of a request message which
includes following format:
• A Request-line
• Optionally a message-body
The following sections explain each of the entities used in an HTTP request message.
Request-Line
The Request-Line begins with a method token, followed by the Request-URI and the
protocol version, and ending with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Let's discuss each of the parts mentioned in the Request-Line.
Request Method
The request method indicates the method to be performed on the resource identified by the
given Request-URI. The method is case-sensitive and should always be mentioned in
uppercase. The following table lists all the supported methods in HTTP/1.1.
S.N. Method and Description
1 GET
The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.
2 HEAD
Same as GET, but it transfers the status line and the header section only.
3 POST
A POST request is used to send data to the server, for example, customer information, file
upload, etc. using HTML forms.
4 PUT
Replaces all the current representations of the target resource with the uploaded content.
5 DELETE
Removes all the current representations of the target resource given by URI.
6 CONNECT
Establishes a tunnel to the server identified by a given URI.
7 OPTIONS
Describe the communication options for the target resource.
8 TRACE
Performs a message loop back test along with the path to the target resource.
Request-URI
The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to
apply the request. Following are the most commonly used forms to specify an URI:
Request-URI = "*" | absoluteURI | abs_path | authority
1 The asterisk * is used when an HTTP request does not apply to a particular resource, but to
the server itself, and is only allowed when the method used does not necessarily apply to a
resource. For example:
OPTIONS * HTTP/1.1
2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is
requested to forward the request or service from a valid cache, and return the response. For
example:
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1
3 The most common form of Request-URI is that used to identify a resource on an origin server
or gateway. For example, a client wishing to retrieve a resource directly from the origin
server would create a TCP connection to port 80 of the host "www.w3.org" and send the
following lines:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
Note that the absolute path cannot be empty; if none is present in the original URI, it MUST
be given as "/" (the server root).
Request Header Fields
We will study General-header and Entity-header in a separate chapter when we will learn
HTTP header fields. For now, let's check what Request header fields are.
The request-header fields allow the client to pass additional information about the request,
and about the client itself, to the server. These fields act as request modifiers.Here is a list of
some important Request-header fields that can be used based on the requirement:
• Accept-Charset
• Accept-Encoding
• Accept-Language
• Authorization
• Expect
• From
• Host
• If-Match
• If-Modified-Since
• If-None-Match
• If-Range
• If-Unmodified-Since
• Max-Forwards
• Proxy-Authorization
• Range
• Referer
• TE
• User-Agent
You can introduce your custom fields in case you are going to write your own custom Client
and Web Server.
Examples of Request Message
Now let's put it all together to form an HTTP request to fetch hello.htm page from the web
server running on tutorialspoint.com
GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Here we are not sending any request data to the server because we are fetching a plain
HTML page from the server. Connection is a general-header, and the rest of the headers are
request headers. The following example shows how to send form data to the server using
request message body:
POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
licenseID=string&content=string&/paramsXML=string
Here the given URL /cgi-bin/process.cgi will be used to process the passed data and
accordingly, a response will be returned. Here content-type tells the server that the passed
data is a simple web form data and length will be the actual length of the data put in the
message body. The following example shows how you can pass plain XML to your web
server:
POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Using Cookies:
In the last guide, I have covered Sessions in Servlet. Here we will discuss Cookies which is
also used for session management. Let’s recall few things here from last tutorial so that we
can relate sessions and cookies. When a user visits web application first time, the servlet
container crates new HttpSession object by calling request.getSession(). A unique Id is
assigned to the session. The Servlet container also sets a Cookie in the header of the
HTTP response with cookie name and the unique session ID as its value.
The cookie is stored in the user browser, the client (user’s browser) sends this cookie back to
the server for all the subsequent requests until the cookie is valid. The Servlet container
checks the request header for cookies and get the session information from the cookie
and use the associated session from the server memory.
The session remains active for the time specified in tag in web.xml. If tag in not set in
web.xml then the session remains active for 30 minutes. Cookie remains active as long as
the user’s browser is running, as soon as the browser is closed, the cookie and associated
session info is destroyed. So when the user opens the browser again and sends request to web
server, the new session is being created.
Types of Cookies
We can classify the cookie based on their expiry time:
1. Session
2. Persistent
1) SessionCookies:
Session cookies do not have expiration time. It lives in the browser memory. As soon as the
web browser is closed this cookie gets destroyed.
2) Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the user hard drive and
gets destroyed based on the expiry time.
How to send Cookies to the Client
Here are steps for sending cookie to the client:
1. Create a Cookie object.
2. Set the maximum Age.
3. Place the Cookie in HTTP response header.
1) Create a Cookie object:
Cookie c = new Cookie("userName","Chaitanya");
2) Set the maximum Age:
By using setMaxAge () method we can set the maximum age for the particular cookie in
seconds.
c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.
response.addCookie(c);
How to read cookies
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++){
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}
Example of Cookies in java servlet
index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue());
//Displaying user password value from cookie
pwriter.print("Password: "+c[2].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Welcome Screen:
XML:
XML stands for Extensible Markup Language. It is a text-based markup language derived
from Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data. XML is not
going to replace HTML in the near future, but it introduces new possibilities by adopting
many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems
and solutions −
• XML is extensible − XML allows you to create your own self-descriptive tags, or
language, that suits your application.
• XML carries the data, does not present it − XML allows you to store the data
irrespective of how it will be presented.
• XML is a public standard − XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available as an open standard.
XML Usage
A short list of XML usage says it all −
• XML can work behind the scene to simplify the creation of HTML documents for
large web sites.
• XML can be used to exchange the information between organizations and systems.
• XML can be used for offloading and reloading of databases.
• XML can be used to store and arrange the data, which can customize your data
handling needs.
• XML can easily be merged with style sheets to create almost any desired output.
• Virtually, any type of data can be expressed as an XML document.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that
is both human-readable and machine-readable. So what exactly is a markup
language? Markup is information added to a document that enhances its meaning in certain
ways, in that it identifies the parts and how they relate to each other. More specifically, a
markup language is a set of symbols that can be placed in the text of a document to
demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>
This snippet includes the markup symbols, or the tags such as <message>...</message> and
<text>... </text>. The tags <message> and </message> mark the start and the end of the
XML code fragment. The tags <text> and </text> surround the text Hello, world!.
Is XML a Programming Language?
A programming language consists of grammar rules and its own vocabulary which is used to
create computer programs. These programs instruct the computer to perform specific tasks.
XML does not qualify to be a programming language as it does not perform any
computation or algorithms. It is usually stored in a simple text file and is processed by
special software that is capable of interpreting XML.
Form Navigation:
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = get_firstChild(xmlDoc.getElementsByTagName("book")[0]);
document.getElementById("demo").innerHTML = x.nodeName;
}
An XML document is a basic unit of XML information composed of elements and other
markup in an orderly package. An XML document can contains wide variety of data. For
example, database of numbers, numbers representing molecular structure or a mathematical
equation.
XML Document Example
A simple document is shown in the following example −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
The following image depicts the parts of XML document.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
What You Should Already Know
Before you continue you should have a basic understanding of the following:
• HTML
• XML
If you want to study these subjects first, find the tutorials on our Home page.
XSLT References
XSLT Elements
Description of all the XSLT elements from the W3C Recommendation, and information
about browser support.
XSLT, XPath, and XQuery Functions
XSLT 2.0, XPath 2.0, and XQuery 1.0, share the same functions library. There are over 100
built-in functions. There are functions for string values, numeric values, date and time
comparison, node and QName manipulation, sequence manipulation, and more.
Web Services:
Web services are web application components.
Web services can be published, found, and used on the Web.
This tutorial introduces WSDL, SOAP, RDF, and RSS.
WSDL
• WSDL stands for Web Services Description Language
• WSDL is an XML-based language for describing Web services.
• WSDL is a W3C recommendation
SOAP
• SOAP stands for Simple Object Access Protocol
• SOAP is an XML based protocol for accessing Web Services.
• SOAP is based on XML
• SOAP is a W3C recommendation
RDF
• RDF stands for Resource Description Framework
• RDF is a framework for describing resources on the web
• RDF is written in XML
• RDF is a W3C Recommendation
RSS
• RSS stands for Really Simple Syndication
• RSS allows you to syndicate your site content
• RSS defines an easy way to share and view headlines and content
• RSS files can be automatically updated
• RSS allows personalized views for different sites
• RSS is written in XML
Imports System
Imports System.Web.Services
end class
This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web
Services.
Example Explained
Note: To run this example, you will need a .NET server.
The first line in the example states that this is a Web Service, written in VBScript, and has the
class name "TempConvert":
<%@ WebService Language="VBScript" Class="TempConvert" %>
The next lines import the namespace "System.Web.Services" from the .NET framework:
Imports System
Imports System.Web.Services
The next line defines that the "TempConvert" class is a WebService class type:
Public Class TempConvert :Inherits WebService
The next steps are basic VB programming. This application has two functions. One to convert
from Fahrenheit to Celsius, and one to convert from Celsius to Fahrenheit.
The only difference from a normal application is that this function is defined as a
"WebMethod()".
Use "WebMethod()" to convert the functions in your application into web services:
<WebMethod()> Public Function FahrenheitToCelsius(ByVal Fahrenheit As String) As
String
dim fahr
fahr=trim(replace(Fahrenheit,",","."))
if fahr="" or IsNumeric(fahr)=false then return "Error"
return ((((fahr) - 32) / 9) * 5)
end function
How To Do It
Here is the code to add the Web Service to a web page:
<form action='tempconvert.asmx/FahrenheitToCelsius'
method="post" target="_blank">
<table>
<tr>
<td>Fahrenheit to Celsius:</td>
<td>
<input class="frmInput" type="text" size="30" name="Fahrenheit">
</td>
</tr>
<tr>
<td></td>
<td align="right">
<input type="submit" value="Submit" class="button">
</td>
</tr>
</table>
</form>
<form action='tempconvert.asmx/CelsiusToFahrenheit'
method="post" target="_blank">
<table>
<tr>
<td>Celsius to Fahrenheit:</td>
<td>
<input class="frmInput" type="text" size="30" name="Celsius">
</td>
</tr>
<tr>
<td></td>
<td align="right">
<input type="submit" value="Submit" class="button">
</td>
</tr>
</table>
</form>
UDDI:
UDDI is an XML-based standard for describing, publishing, and finding web services.
• UDDI stands for Universal Description, Discovery, and Integration.
• UDDI is a specification for a distributed registry of web services.
• UDDI is a platform-independent, open framework.
• UDDI can communicate via SOAP, CORBA, Java RMI Protocol.
• UDDI uses Web Service Definition Language(WSDL) to describe interfaces to web
services.
• UDDI is seen with SOAP and WSDL as one of the three foundation standards of web
services.
• UDDI is an open industry initiative, enabling businesses to discover each other and
define how they interact over the Internet.
UDDI has two sections −
• A registry of all web service's metadata, including a pointer to the WSDL description
of a service.
• A set of WSDL port type definitions for manipulating and searching that registry.
History of UDDI
• UDDI 1.0 was originally announced by Microsoft, IBM, and Ariba in September
2000.
• Since the initial announcement, the UDDI initiative has grown to include more than
300 companies including Dell, Fujitsu, HP, Hitachi, IBM, Intel, Microsoft, Oracle,
SAP, and Sun.
• In May 2001, Microsoft and IBM launched the first UDDI operator sites and turned
the UDDI registry live.
• In June 2001, UDDI announced Version 2.0.
• As the time of writing this tutorial, Microsoft and IBM sites had implemented the 1.0
specification and were planning 2.0 support in the near future.
• Currently UDDI is sponsored by OASIS.
Partner Interface Processes
Partner Interface Processes (PIPs) are XML based interfaces that enable two trading partners
to exchange data. Dozens of PIPs already exist. Some of them are listed here −
• PIP2A2 − Enables a partner to query another for product information.
• PIP3A2 − Enables a partner to query the price and availability of specific products.
• PIP3A4 − Enables a partner to submit an electronic purchase order and receive
acknowledgment of the order.
• PIP3A3 − Enables a partner to transfer the contents of an electronic shopping cart.
• PIP3B4 − Enables a partner to query the status of a specific shipment.
Private UDDI Registries
As an alternative to using the public federated network of UDDI registries available on the
Internet, companies or industry groups may choose to implement their own private UDDI
registries.
These exclusive services are designed for the sole purpose of allowing members of the
company or of the industry group to share and advertise services amongst themselves.
Regardless of whether the UDDI registry is a part of the global federated network or a
privately owned and operated registry, the one thing that ties them all together is a common
web services API for publishing and locating businesses and services advertised within the
UDDI registry.
WSDL:
WSDL stands for Web Services Description Language. It is the standard format for
describing a web service. WSDL was developed jointly by Microsoft and IBM.
Features of WSDL
• WSDL is an XML-based protocol for information exchange in decentralized and
distributed environments.
• WSDL definitions describe how to access a web service and what operations it will
perform.
• WSDL is a language for describing how to interface with XML-based services.
• WSDL is an integral part of Universal Description, Discovery, and Integration
(UDDI), an XML-based worldwide business registry.
• WSDL is the language that UDDI uses.
• WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.
WSDL Usage
WSDL is often used in combination with SOAP and XML Schema to provide web services
over the Internet. A client program connecting to a web service can read the WSDL to
determine what functions are available on the server. Any special datatypes used are
embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to
actually call one of the functions listed in the WSDL.
History of WSDL
WSDL 1.1 was submitted as a W3C Note by Ariba, IBM, and Microsoft for describing
services for the W3C XML Activity on XML Protocols in March 2001.
WSDL 1.1 has not been endorsed by the World Wide Web Consortium (W3C), however it
has just released a draft for version 2.0 that will be a recommendation (an official standard),
and thus endorsed by the W3C.
Different books and different organizations provide different definitions to Web Services.
Some of them are listed here.
• A web service is any piece of software that makes itself available over the internet
and uses a standardized XML messaging system. XML is used to encode all
communications to a web service. For example, a client invokes a web service by
sending an XML message, then waits for a corresponding XML response. As all
communication is in XML, web services are not tied to any one operating system or
programming language—Java can talk with Perl; Windows applications can talk
with Unix applications.
• Web services are self-contained, modular, distributed, dynamic applications that can
be described, published, located, or invoked over the network to create products,
processes, and supply chains. These applications can be local, distributed, or web-
based. Web services are built on top of open standards such as TCP/IP, HTTP, Java,
HTML, and XML.
• Web services are XML-based information exchange systems that use the Internet for
direct application-to-application interaction. These systems can include programs,
objects, messages, or documents.
• A web service is a collection of open protocols and standards used for exchanging
data between applications or systems. Software applications written in various
programming languages and running on various platforms can use web services to
exchange data over computer networks like the Internet in a manner similar to inter-
process communication on a single computer. This interoperability (e.g., between
Java and Python, or Windows and Linux applications) is due to the use of open
standards.
To summarize, a complete web service is, therefore, any service that −
• Is available over the Internet or private (intranet) networks
• Uses a standardized XML messaging system
• Is not tied to any one operating system or programming language
• Is self-describing via a common XML grammar
• Is discoverable via a simple find mechanism
Components of Web Services
The basic web services platform is XML + HTTP. All the standard web services work using
the following components −
• SOAP (Simple Object Access Protocol)
• UDDI (Universal Description, Discovery and Integration)
• WSDL (Web Services Description Language)
All these components have been discussed in the Web Services Architecture chapter.
How Does a Web Service Work?
A web service enables communication among various applications by using open standards
such as HTML, XML, WSDL, and SOAP. A web service takes the help of −
• XML to tag the data
• SOAP to transfer a message
• WSDL to describe the availability of service.
You can build a Java-based web service on Solaris that is accessible from your Visual Basic
program that runs on Windows.
You can also use C# to build new web services on Windows that can be invoked from your
web application that is based on JavaServer Pages (JSP) and runs on Linux.
Example
Consider a simple account-management and order processing system. The accounting
personnel use a client application built with Visual Basic or JSP to create new accounts and
enter new customer orders.
The processing logic for this system is written in Java and resides on a Solaris machine,
which also interacts with a database to store information.
The steps to perform this operation are as follows −
• The client program bundles the account registration information into a SOAP
message.
• This SOAP message is sent to the web service as the body of an HTTP POST request.
• The web service unpacks the SOAP request and converts it into a command that the
application can understand.
• The application processes the information as required and responds with a new
unique account number for that customer.
• Next, the web service packages the response into another SOAP message, which it
sends back to the client program in response to its HTTP request.
• The client program unpacks the SOAP message to obtain the results of the account
registration process.