Beruflich Dokumente
Kultur Dokumente
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63
Learning Objectives
Obtaining the Java SDK Java Version History Importance and features of Java JVM How to write and run Java Application programs Java Interface to achieve multiple inheritance Putting classes together by using package
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
The Java Software Development Kit The java SDK comes in three versions -J2ME micro Edition (for handheld and portable devices e.g. smartcard, PDA, cell phone and pager.) -J2SE standard edition (PC development e.g. desktop and small network) -J2EE Enterprise edition (Distributed and enterprise computing, web services)
Note: The SDK is a set of command line tools for developing java applications.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Introduction to Java
Java is an object-oriented programming language with a built-in application programming interface (API) that can handle graphics and user interfaces and that can be used to create applications or applets. Because of its rich set of API's, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform in itself. Java also has standard libraries for doing mathematics.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Features of Java
simple object- oriented distributed interpreted robust secure architect neutral Portable high-performance
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
integration with TCP/IP Java have extensive library of routines for copying TCP/IP Protocols like HTTP,FTP. - Java application can open and access objects across the Net via URLS as the same case as when accessing a local file.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Portable( different kind of O/S) The java compiler does this by generating byte code instructions which have no dependency on computer architecture rather they are designed to be easy to interpret on any machine and easily translated to native machine code
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Java VM Responsibility
JVM does more than interpret to bytecode -The class loader loads appropriate java classes, possibly from the network. - All classes are verified to contain only legal bytecodes and not permitted any illegal stack or register user. - A security manager can limit access to resources such as the local files or the network. -Any unreferenced memory are returned to the system by Garbage collector thread.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
JVM
Java source files (.java) are compiled to Java byte code (.class) Bytecode is interpreted on the target plateform within a Java Virtual Machine
i386VM
Source .java
Java Compiler
SPARC VM
PPC VM
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
JVM Cont.
Traditionally, source code had to be compiled for the target hardware and OS plateform. Windows Compiler -i386 binary Solaries Compiler -SPARC binary Mac Compiler -PPC binary
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Robust( fault-tolerance) -Memory management is done automatically. -Java checks the code at compile and runtime and eliminate the situation that are error prone. -It eliminate the overwriting memory and corrupting data ( mishandled exception code like divide by zero)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
10
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
11
Applications
helo.java
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Applications Cont.
helo.java javac Java compiler
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Applications Cont.
Program bytecode
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
12
Applet
helo.java javac
helo.class
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Applet Cont.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } } Java is case-sensitive
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
13
A Program
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
Java program consists of a named class.
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
Java program consists of a named class. The body of the class is surrounded by braces
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
(Almost) every Java program must have one and only one main() function.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
14
main() in Java
main() must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main() to be called without having to instantiate a particular instance of the class. This is necessary since main() is called by java interpreter before any objects are made.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
The body of the function is surrounded by braces
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
15
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
A semicolon is a statement terminator (not a statement separator).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
Statements can be combined within braces to form a compound statement. White space is (almost always) ignored.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
The identifier System.out is an object. The identifier println is one of the methods for that object.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
16
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
"Hello World" is called a string. There is an explicit string type in Java (unlike C++) Strings are different than characters
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
public indicates that this function can be called by objects outside of the class
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
void indicates that this function does not return a value to the object that calls it
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
17
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
args can be used in the main function to pass parameters from the operating system command line.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
A Program Cont.
/* Display a message */ class hello { public static void main(String args[]) { System.out.println("Hello World!"); } }
Comments are the most important part of your program Criteria for good comments
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Another Program
class ab {public static void main(String args[]) { for (int i=0; i<args.length; i++) System.out.println("args["+i+"]: " +args[i]); System.out.print("the length is::"); System.out.print(args.length); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
18
Javas Goals
Ability to function within current Web environment Portability Device independent user interface Strong implementation of OOP techniques Security
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Important Syntax
Javac- Java complier (Converts java source code into bytecode) Syntax: javac filename.java Java- java interpreter (JAVA VM) (Executes java application byte code directly from class file) Syntax: java filename
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
19
directory tree
After installing the java you will get the following directory tree: docs library documentation in html bin The compiler and tools are here. demo example programs include file for native method lib library files src library source files.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
20
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Data Types
Although complex data values are represented using objects, Java defines a set of primitive types to represent simple data. char 16bits Unicode character data boolean boolean Variable (true/false) byte 8 bits signed integer (with a stream of data from a network or file) short 16 bits signed integer (least-used) java type
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
21
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
22
42
(contains an int)
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
23
Variable Declarations
The value changes whenever you assign a new value to the variable. In Java, you must declare a variable before you can use it. The declaration establishes the name and type of the variable and, in most cases, specifies the initial value as well. The most common form of a variable declaration is type name = value; where type is the name of a Java primitive
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
24
Kinds of Operator
Arithmetic Op. : + * / % Relational Op. : > >= < <= == != Logical Op. : && || ! Inc/Dec Op. : ++ -Operators of Java Bit Op. : & | ^ ~ << >> >>> Conditional Op. : ?: Assign Op. : = += -= *= /= %= &= ^= |= >>= <<= >>>= Casting Op. : (Data Type) Array Op. : [] Method Op. : () . instanceof Op. : instanceof
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Arithmetic Operator
Operator for arithmetic operation Single term operator : +, Binary term operator : +, -, *, /, %
x = -5 ; x = -(-5) ; x = -(3-5) ;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
25
Arithmetic Operator
Real type operation Floating point description and operation: IEEE754 Standard underflow, overflow Infinitive arithmetic java.lang.Float, java.lang.Double,
POSITIVE_INFINITY, NEGATIVE_INFINITY constant
Relational Operator
Compare two value Result : true or false Expression include relational operator for, while, ... Operator
<, <=, >, >=, ==, !=
a > b + c ===> a > (b + c) b == x < y ===> b == (x < y)
- precedence
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Conditional Operator
Conditional Logical operands Operator ! , && , || Relationship of two
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
26
max = x > y ? x : y ;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Postfix operator
n = 1; x = n++; // x=1, n=2
Bitwise Operator
&, |, <<, >>, >>>, ^, ~
Operand should be integer type Precedence
Operator ~ << >> >>> & ^ | Precedence
(H)
(L)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
27
Bitwise Operator
Bitwise AND 10012 & 00112 = 00012 To extract the special area in variable by masking that area Bit OR 10012 | 00112 = 10112 Exclusive AND 10012 ^ 00112 = 10102 1s Complement ~ 000010102 = 111101012
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Shift right(>>)
x >> y = x / 2y
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Assignment Operators
Expr 1 = Expr 1 op Expr2 Expr1 op= Expr 2
Operator
Arithmetic operator : + - * / % Bitwise operator : & | ^ << >> >>>
sum = sum + i ; x = x * y + 1; sum += i ; x *= y + 1;
x = x * (y+1)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
28
Cast Operator
Data Type Casting Operator
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Precedence Rules
Evaluate all subexpressions in parentheses Evaluate nested parentheses from the inside out In the absence of parentheses or within parentheses a. Evaluate *, /, or % before + or b. Evaluate sequences of *, /, and % operators from left to right c. Evaluate sequences of + and operators from left to right
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Operator Precedence
Operator
() [] . ! ~ ++ -- + - (Data Type) * / % + << >> >>> < <= > >= instance == != & ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= >>>=
Association Precedence
Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. (High)
(Low)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
29
Operator Precedence
a = x + y - z ; // Left Association b = -x ; // Right Association c = -x++ ; d = -++x ; e = -x + z ;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Precedence Examples
Example 1 6 + 37 % 8 / 5 is the same as 6 + ((37 % 8) / 5) = 6 + ( 5 / 5) = 7 Example 2 6 + 37 % (8 / 5) =6 + 37 % 1 =6 + 0 = 6
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Type Conversion
Size Direction of Data Type
Widening Type Conversion (Casting down) Smaller Data Type Larger Data Type Narrowing Type Conversion (Casting up) Larger Data Type Smaller Data Type
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
30
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Narrowing Type Conversion (Casting incompatible type) Programmer should describe the conversion explicitly e.g. (target-type) value; byte b; //conversion of int to byte. int i=67; b=(byte) i; byte b=50; b=b*2;// Error (Solution: b=(byte) (b*2);)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
31
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
32
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Mixed Mode Operations and Strings It is important to remember that 13 and 13 are not the same Examples out.println(4 + 5) // prints 45 out.println(4 + 5) // prints 45 out.println(4 + 5) // prints 9
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Characters as Integers
It is legal to assign a char to an int variable int i = a; // assigns 97 to i It is legal to assign an int to an char variable char c = 97; // assigns a to c It is possible to perform arithmetic on char variables char ch = a; ch = ch + 1; // assigns b to ch
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
33
String s = Lincoln said: + \ Four score and seven years ago\ ; Result :
Lincoln said: Four score and seven years ago
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Comments
Single Line Comment int i = 10 ; // i is counter Multiple Line Comment /* Some comments */ Documentation Comment Using javadoc Tool, /** make document Documentation Comment */
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Java Keywords
abstract boolean break byte case catch char class const* continue default do double else extends final finally float for goto* if implements import instanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient* try void volatile while strictfp
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
34
assert (New in 1.5) enum (New in 1.5) The assert is recognized as keyword in JDK1.4 compiler, but we could not use it. It can be used it from 1.5.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
The if statement
Syntax if (expression) statement The expression must evaluate to a boolean TRUE or FALSE value. The statement can be either a single statement or a compound statement.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
35
Nested if statements
if (x) if (y) a = 1; else a = 2;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
36
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
if (condition1) statement1;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Syntax
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
37
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
38
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
39
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Difference between do-while and while The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. int i=0; do { System.out.println(X); i++; } while (i < 3);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
40
Example of do-while
class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
41
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
42
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
43
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
44
return statement
The return statement is used to return the value within the body of method. The method declared void does not return any value. Java method Return Value return to the code when it -When it completes all the statements in the method
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
45
Introduction to class
The class is the fundamental concept in JAVA (and other OOPs). A class describes some data object(s), and the operations (or methods) that can be applied to those objects Every object and method in Java belongs to a class Classes have data (fields) and code (methods) and classes (member classes or inner classes)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
46
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Declare a class
[Access-specifier][modifier] class class_name { // data type instance variable1; // data type instance variable n } Data type method_name(parameter_list) { //body of method } Note: Access-specifier and modifier is optional.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Creating an Object
class-name object-name; class circle { circle c;//declare c=new circle();//create an object } To access a variable dot(.) operator is used. c.radius=10;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
47
Declaring method
Access-specifier modifier return-type method-name(parameter-list) { //body of method } e.g. void display(){} int sum(int a, int b) { }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Example of a class
class tri { double base; double height; double area; void findarea() { area=(0.5)*(base)*(height); System.out.println(+area); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
48
new operator
The new operator allocate memory for an object during runtime and return reference to it. In java we cannot manipulate reference (as in C/C++ by using pointers). Java runtime allocate memory to an object dynamically. Since a class is a logical construct and an object has physical construct. Declaring an object of a class is two step process.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
It contains default value null. It means it does not yet point to an actual object. So we must assign actual object. t=new triangle();
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
49
Garbage Collector
When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as garbage collection. Java performs garbage collection for you and eliminates the need to free objects explicitly. This eliminates a common cause of errors in C/C++ and other languages (memory leaks). Never have to worry about dangling references. When an object is no longer reachable the space it occupies can be reclaimed. Space is reclaimed at the garbage collector's discretion.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
50
Finalization
protected void finalize() throws Throwable {} every class inherits the finalize() method from java.lang.Object the method is called by the garbage collector when it determines no more references to the object exist the Object finalize method performs no actions but it may be overridden by any class normally it should be overridden to clean-up nonJava resources ie closing a file finalize() is never run more than once on any object
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Argument passing
Two ways of argument passing in java Call by value Call by reference 1. Call by value: In java when we pass a simple type to a method, it is passed by value. So, the parameter that receives the argument has no effect outside the method.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Call by Value
Characteristics Original value cannot be changed Called method gets only a copy of the variable. In java, all argument of the primitive data types are passed by value. The copy of the argument value is maintained at a separate memory location.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
51
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
52
Call by reference
2. Call by reference : If we want to change the value of the original variable in the calling program; which is not possible if the call by value method is used. Here argument that are objects are passed by a reference to the called method.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
53
Output: C:\d>javac reference.java C:\d>java reference Before call:20 inside method :400 After call:400
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Static modifier
static: static int i; //declare the variable as static, it makes only one value of the variable exists for all instance of the class. These variables are called class variable. It is used even if the class is never actually instantiated. e.g. public static int abs(int a); public static int min(int a,int b);
Note: The above are declared in java Math class library.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
54
Constructor
A constructor creates an Object of the class that it is in by initializing all the instance variables and creating a place in memory to hold the Object. It is always used with the keyword new and then the Class name. For instance, new String(); constructs a new String object. Sometimes in a few classes you may have to initialize a few of the variables to values apart from their predefined data type specific values.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Constructor Cont.
If java initializes variables it would default them to their variable type specific values. For example you may want to initialize an integer variable to 10 or 20 based on a certain condition, when your class is created. In such a case you cannot hard code the value during variable declaration. such kind of code can be placed inside the constructor so that the initialization would happen when the class is instantiated.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
55
Constructor Example
public class Circle { public static final double PI = 3.14159; // A constant public double r; // instance field holds circles radius // The constructor method: initialize the radius field public Circle(double r) { this.r = r; }
this.r refers to the r field of the class
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Constructor Example
// Constructor to use if no arguments
// The instance methods: compute values based on radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Copy constructor
class copy { int a,b; public copy(int a1,int b1) { a=a1; b=b1; }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
56
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
57
Inheritance
Inheritance- Creating a new class by taking help of some existing class is known as Inheritance. The new class is known as: Child class or derived class or subclass, and the existing class is known as : base class or parent class or superclass. Benefit: 1.Code reusability 2. Save Effort
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Inheritance in Java
Inheritance is declared using the "extends" keyword If inheritance is not defined, the class extends a class called Object.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
58
Types of Inheritance
Single Inheritance-One base class and one Derived class
Person
Employee
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
59
Person
Person
Neuro-Surgon
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Employee Vehicle
Griffin
Person
Employee
Customer
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
60
Employee
Customer
Full-Time
Part-Time
Regular
Casual
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Inheritance Example
class A { int I,j; void showij() { System.out.println(I and j:: +i+ +j); } } { Sytem.out.println(i+j+k:+(i+j+k)); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Inheritance Example
class B extends A { Int k; void showk() { System.out.println(k:+k); } void sum()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
61
Inheritance Example
class inheritance { public static void main(String s[]) { A a1=new A(); B b1=new B(); //The superclass may be used by itself a1.i=10; a1.j=20; System.out.println(Contents of Superclass); a1.showij(); System.out.println(); // The subclass has access to all public members of its superclass */
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Inheritance Example
b1.i=7; b1.j=8; b1.k=9; System.out.println(Contents of Subclass); b1.showij(); b1.showk(); System.out.println(); System.out.println(Sum of I , j and k in subclass); b1.sum(); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Inheritance Example
Contents of superclass I and j: 10 20 Contents of Subclass I and j:7 8 K:9 Sum of I , j and k in Sub class i+j+k:24
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
62
Array(s) in Java
An array is a collection of elements where each element is the same type. Element type can be primitive or Object. Each element is a single value. The length of the array is set when it is created. It cannot change.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Array(s) in Java
Individual array elements are accessed via an index. Array index numbering starts at 0. Note: Some references claim that arrays in Java are Objects. THIS IS NOT TRUE. Arrays do exhibit some behaviour which is similar to objects, but they are not themselves, objects.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Creating Array
Creating an array is a 2 step process It must be declared (declaration does not specify size) declaration syntax: type[] arrayName;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
63
grades = new int[5]; // Create array. // specify size // assign new array to // array variable
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
grades
1 2
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
64
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
type[] arrayName = {initializer_list}; int[] grades = {100, 96, 78, 86, 93};
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
65
Whenever and array is accessed, the index is checked to ensure that it within the bounds of the array. Attempts to access an array element outside the bounds of the array will cause an ArrayIndexOutOfBounds exception to be thrown.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
66
0 1 2 3 4
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Multi-dimensional Array
type[][] arrayName;
They are created and initialized in the same way as single dimensioned arrays.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
String[][] colours =
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
67
String Array
An array is the collection of same data type. Suppose if we have a declare an array of type String, then it will store only the String value not any other data type. When we have a closely related data of the same type and scope, it is better to declare it in an array.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
68
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
69
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
70
Strings can also be created using the + operator. The + operator, when applied to Strings means concatenation.
int age = 21; String message = "Craig wishes he was " + age + " years old";
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
71
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
String Examples
String name = "Craig"; String name2 = "Craig"; if (name.equals(name2)) System.out.println("The names are the same");
String name = "Craig Schock"; int lastNameIndex = name.indexOf("Schock");
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
72
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
73
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
StringBuffer Example
StringBuffer sql = new StringBuffer(); sql.setLength(0); sql.append("Select * from Employee"); sql.append(" where Employee_ID = " + employeeId); sql.append(" and Employee_name = '" + employeeName + "'");
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
String Tokenizer
String Tokenizer:- This class provides a method to break a string into token parsing. A string involves breaking the string into different words. These words are called token. The StringTokenizer uses white spaces as separators. This is known as delimiters. countToken() // count the no. of tokens in the string
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
74
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
StringTokenizer Example
import java.util.*; public class Test { public static void main(String args[]) { int idx = 0; int tokenCount; String words[] = new String [500]; String message="The text of the message to be broken up for analysis"; StringTokenizer st = new StringTokenizer(message);
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
75
Wrapper Classes
Wrapper Classes: Primitive data types may be converted into object type by using the wrapper classes. These wrapper classes are available in the java.lang package. So we can use it without an import statement. There are eight wrapper classes: Byte Boolean Character Short
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
76
Integer Class
Integer Class: The Integer class is a wrapper class for primitive data type int. It wraps a value of the primitive type int in an object. This class provides methods for converting an int to String object and String to an int. parseInt(String s) //convert string to integer n return value int toBinaryString(int n) // returns a String that contain binary equivalent of n
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Double class
e.g. Double class: isNAN() // find the given no. is not a number isInfinite() Double d=new Double(1.0/0.0); //infinity d.isNAN(); Double.POSITIVE_INFINITY; Double.NEGATIVE_INFINITY; etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
77
java.lang package
The java.lang is one of the most important packages in java. It provides the fundamental for java programming, its most important classes are: Object Class Math String StringBuffer System andThread, etc
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
78
79
super Cont.
//Boxweight now uses super to intialize its box attribute class boxweight extendsBox { double weight; //initialize width,height,depth using super() Boxweight(double w,double h ,double d,double ){ super(w,h,d); //call superclass constructor weight m; } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
super Cont.
When a subclass calls super(), it is calling the constructor of its immediate superclass. Thus super(), always refers to the superclass immediately above the calling class. This is true even in multileveled hierarchy.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Super Cont.
Second use for super Similar to this, excepts it always refer to the superclass of the subclass in which it is used. Syntax super.member Method can be method or variable This form is applicable to situations in which member names of a subclass hides members by the name in the superclass.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
80
Super Example
//using super to overcome name hiding class A { int i; } //create a subclass by extending class A class B extends A { int i; //this I hides the i in A
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Super Example
B(int a,int b) { super.i=a; //i in A i=b; //i in B } void show(){ System.out.println(i in superclass: +super.i); //Result 1 System.out.println( i in subclass: + i); //Result 2 } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Super Example
class usersuper{ public static void mai(String args[]) { B b=new B(1,2); b.show(); } } Output: i in superclass 1 i in subclass 2
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
81
Method Overriding
Method Overriding Subclasses inherit all methods from their superclass Sometimes, the implementation of the method in the superclass does not provide the functionality required by the subclass. In these cases, the method must be overridden. To override a method, provide an implementation in the subclass.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Method Overriding
The method in the subclass MUST have the exact name and same signature (name & type) as the method it is overriding. else overloaded
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
82
Introduction Abstract
First of all, we should understand what is the meaning of 'abstract' in terms of software. It's the same meaning as in English, that is, the entities (objects) which do not exist in the real world are abstract entities. For example, Dog, Cat, Bear, Deer are all animals that exist but animal is also an entity which is just a concept and there is no existence's we can define an abstract class for 'Animal'.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Introduction Abstract
We can derive any number of real world animal classes from the abstract class 'Animal' like Tiger, Lion, etc. Obviously, we can understand now why we cannot create objects for abstract classes. Because the Animal class has no existence in real world. So we cannot create a real world entity (nothing but an object).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
83
Introduction Abstract
That is the very reason this concept is followed. The derived classes that we've seen above are concrete classes since they are real world objects and have definite properties and operations on them. Abstract: It allows the implementation of a behavior in different ways. The class and methods declared using abstract modifier are not complete. The implementation is done in subclass. It is opposite to final modifier.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Abstract Class
It can have abstract method. If we are giving abstract specifier, then the class cannot be instantiated, because it is incomplete. If it is declared as in method, it has no body and belong to an abstract class. So subclass must override the abstract methods of the superclass. We cannot use the final and abstract modifier for the same class, method or data member. An abstract class can have concrete methods also.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Abstract Class
A class for which object is not created, i.e. An abstract class cannot be directly instantiated with the new operator, Such objects would be useless, because an abstract class is not fully defined. Also we cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass , or be itself declared abstract.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
84
Abstract function
Abstract function-A function for which body({.}) is not defined. Syntax: abstract type name(parameterlist)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
85
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Concrete class: It specifies the full set of methods for an object. It implements all of its methods. Can have instance. Can have subclass Can have constructor.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
86
Abstract Class: Declare the method. Implementation none, some or all of its method Cannot have instance Must have subclass Cannot declare abstract constructor (or) abstract static method
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
final Class
A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final. Example: public final class MyFinalClass {...}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
final methods
A final method cannot be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class. Example: public class MyClass { public final void myFinalMethod() {...}}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
87
final variable
A final variable can only be assigned once. This assignment does not grant the variable immutable status. If the variable is a field of a class, it must be assigned in the constructor of its class. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.) Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
88
Object class
The Object class: All the classes are subclass of the object class and inherit its methods. Object, which is the root of the java class hierarchy. The toString() method creates a string representation of the value of an object of the object class. wait() and notify() are methods of the object class and used for controlling threads, etc.
clone(), equals() & hashcode(), getClass(), finalize() these methods also belongs to the object class.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Interface
Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Once it is defined, any no. of classes can implement an interface. Also, one class can implement any no. of interfaces. To implement an interface, class must create the complete set of methods defined by the interface. However each class is free to determine the details of its own implementation.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
89
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Interface Syntax
Syntax:
access interface name { return-type method-name1(parameter-list); return-type method-name1(parameter-list); type final-variable1=value; type final-variable2=value; // return-type method-nameN(parameter-list); type final-variableN=value; }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Interface Syntax
Where, access is either public or not used. When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. name is the name of interface, and can be any valid identifiers. The method which are declared have no bodies. They end with a semicolon after the parameter list.(// like abstract methods)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
90
Interface Example
Variables can be declared inside of interface declarations. They are implicitly final and static, they cannot be changed by the implementing class. They must also initialized with a constant value. The methods that implement an interface must be declared public.
e.g interface call { void callme(parameter); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Implementing Interface
Implementing interfaces Once an interface has been defined, one or more classes can implement that interface. Syntax:
access-class classname [extends superclass] [implements interface[,interface]]
{ // }
class-body
e.g. public class Test1 extends Test2 implements NewInterface { // class body }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
91
Conclusion
Interfaces are essential to the Java language. Interfaces have advantages over classes because of improved information hiding and code re-use. They provide multiple inheritance. Interfaces also solve the nasty virtual class problem in C++. Virtual classes are a counterintuitive solution to the problem of a class inheriting from the same class more than once. This is equivalent in Java to the situation where a base class and derived class implement the same interface. Interfaces that extend other interfaces may also produce duplicate references. Java merges the duplicate references into one without any fuss
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
static
Static (keyword):- Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
static Cont.
We can declare both methods and variables to be static. e.g. the most common example of a static member is main(). main() is declared as static because it must be called before any object exist. Variables-Instance variable declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
92
Static Cont.
Methods: methods declared as static have several restrictions: They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. If we need to do computation in order to initialize static variables, we can declare a static block which gets executed exactly once, when the class is first loaded.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Abstract classes: are used only when there is a isa type of relationship between the classes. Interfaces: can be implemented by classes that are not related to one another. Abstract classes :You cannot extend more than one abstract class. Interfaces: You can implement more than one interface. Abstract classes: An abstract class implements, some,all or none of its methods. Interfaces: It implements none of its methods.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
interface contains methods that must be abstract; abstract class may contain concrete methods interface contains variables that must be static and final; abstract class may contain non-final and final variables. members in an interface are public by default, abstract class may contain non-public members
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
93
interface is used to "implements"; whereas abstract class is used to "extends". interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces. interface is absolutely abstract; abstract class can be invoked if a main() exists.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, use interface instead of abstract class. Similarities: Neither Abstract classes or Interface can be instantiated.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Extending Interface
Interface is also extended by other interface. One interface can inherit another by use of the keyword extends. This is much like a way for inheriting class. When you inheriting two interfaces, you must provide implementations for all methods defined within the interface inheritance path.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
94
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic form limited to reusing the classes within a program. What if we need to use classes from other programs without physically copying them into the program under development ?
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Introduction Package(s)
In Java, this is achieved by using what is known as packages, a concept similar to class libraries in other languages. Packages are Javas way of grouping a number of related classes and/or interfaces together into a single unit. That means, packages act as containers for classes.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
95
Benefits of Package(s)
The benefits of organising classes into packages are: The classes contained in the packages of other programs/applications can be reused. In packages classes can be unique compared with classes in other packages. That two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
96
Predefined package
Java provides a large number of classes groped into different packages based on their functionality. The six foundation Java packages are: java.lang Contains classes for primitive types, strings, math functions, threads, and exception
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
97
Accessing Classes from Packages Cont. Selected or all classes in packages can be imported: Implicit in all programs: import java.lang.*; package statement(s) must appear first .
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Creating Packages
Java supports a keyword called package for creating user-defined packages. The package statement must be the first statement in a Java source file (except comments and white spaces) followed by one or more classes.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
98
Package name is myPackage and classes are considered as part of this package; The code is saved in a file called ClassA.java and located in a directory called myPackage.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
99
Accessing a Package
As indicated earlier, classes in packages can be accessed using a fully qualified name or using a short-cut as long as we import a corresponding package. The general form of importing package is: import package1[.package2][].classname Example: import myPackage.ClassA; import myPackage.secondPackage
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
100
Visibility - Revisited
Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. Protected members of a class are visible within the class, subclasses and also within
all classes that are in the same package as that class.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Visibility Modifiers
Accessible to: public protected Packag e (default) private
Same Class
Yes Yes No No
Yes No No No
Class in package
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
This class is stored in Teacher.java file within a directory called pack1. How do we a new public class called Student to this package.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
101
class Teacher
class Student
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
102
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
103
Conclusion
Packages allow grouping of related classes into a single united. Packages are organised in hierarchical structure. Packages handle name classing issues. Packages can be accessed or inherited without actual copy of code to each program.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Conclusion
Java offers the real possibility that most programs can be written in a type-safe language. However, for Java to be broadly useful, it needs to have more expressive power than it does at present. It allows students to learn object-oriented programming without exposing them to the complexity of C++. It provides the kind of rigorous compile-time error checking typically associated with Pascal. It allows instructors to introduce students to GUI programming, networking, threads, and other important concepts used in modern-day software.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Summary
Java is a popular, mature language that is highly portable, features a large standard library and automatic memory handling. On the downside, its an interpreted language with no support for unsigned types and the automatic memory management prevents fine control over memory use and makes porting of algorithms harder. Whether Java is a good choice for your scientific programming will depend upon which of these pros or cons is of most benefit or cost.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
104
Review Questions
Objective Questions Q1) Which one does not extend java.lang.Number 1)Integer 2)Boolean 3)Character 4)Long 5)Short Q2) Which one does not have a valueOf(String) method 1)Integer 2)Boolean 3)Character 4)Long 5)Short
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
105
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
106
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
107
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
108
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
109
Suggested Reading/References
References
[1]. Bergin, J., ``Java as a better C++,'' ACM SIGPLAN Notices 31, 11 (November 1996), pp. 21-27. [2]. Bowen, B. D., ``Educators embrace Java,'' JavaWorld (January 1997), 3. Brilliant, S. S., and T. R. Wiseman, ``The first programming paradigm and language dilemma,'' Proceedings of the 27th SIGCSE Technical Symposium on Computer Science Education, Philadelphia, February, 1996, pp. 338-342. [3]. Jon Byous, Java technology: The early years. Sun Developer Network, no date [ca. 1998]. Retrieved April 22, 2005. [4]James Gosling, A brief history of the Green project. Java.net, no date [ca. Q1/1998]. Retrieved April 29, 2007. [5]James Gosling, Bill Joy, Guy Steele, and Gilad Bracha, The Java language specification, third edition. Addison-Wesley, 2005. ISBN 0321-24678-0 (see also online edition of the specification).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
UNIT-2
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63
Learning Objectives
Exception Handling Multithreaded Programming Input/Output Programming Networking
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
110
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Runtime exceptions Runtime Exception What are runtime exceptions Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
111
Exception
An exception is an abnormal condition that arises in a code sequence at run time. An exception is a run time error. A java exception is an object that describe an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, and object representing that exception is created and thrown in the method that cause the error, that method may choose to handle the exception itself or pass it on.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Exception Cont.
Java exception handling is managed via five keywords: try, catch, throw, throws and finally.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
try
try Programs statements that we want to monitor for exceptions are contained within try block. try require at least one catch or one finally. try{ //block of code to monitor for errors } If an exception occurs within the try block, it is thrown.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
112
catch
catch- your code can catch this exception (using catch) and handle it. try{ //block of code to monitor for errors } catch(ExceptionType1 exob) { //exception handler for ExceptionType1 }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Catch Cont.
catch(ExceptionType2 exob) { //exception handler for ExceptionType2 }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Exception Type
Exception type is the type of exception that has occurred. Uncaught Exception Any exception that is not caught by the program, will ultimately be processed by the default handler. Default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program, default handler provided by the Java run-time system.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
113
Exception Example
class ecep { int d=0; int a=42/d; } Output: Java.lang.ArithmeticEception: / by zero at ecep.main(ecep.java:4)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
114
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
try Example
class excep { public static void main(String s[]) { int d,a; try { d=0; a=42/d; }catch(Exception f) {System.out.println("Divide by zero");}}}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Multiple Catch
try- to handle a run time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. Multiple catch clause- In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, use two or more catch clause, each catching a different type of exception. When
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
115
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
116
Nested try
The try statement can be nested. That is , a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If a inner try statement does not have a catch statements catch handlers are inspected for a match.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
117
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
118
throw
So far, you have only been catching exceptions that are thrown by Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
throw Cont.
There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
throw Example
class ThrowDemo{ static void demopro(){ try{ throw new NullPointerException(demo); }catch(NullPointerException e){ System.out.println(Caught inside dempproc.); throw e; //rethrow the exception } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
119
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
throws Example
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. We do this by including a throws clause in the methods declaration. A throws clause exceptions, except those of the type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
120
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
catch (IllegalAccessException e) { System.out.println(Caught +e); } } } Output is: Inside throwOne Caught java.lang.IllegalAccessException: demo
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
121
finally
finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
finally Cont.
This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
122
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
123
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
124
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Checked Exception
Checked Exception- Java compiler checks that you have indeed stated what is to be done when they arise, and it is because of this checking that they are called checked exception. The checked exceptions describe problems that can arise in a correct program, typically difficulties with the environment such as user mistake or I/O programs. In any method that contains some statements that might throw checked exception you must either throws the exception using a throws constraint in the declaration of the method.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
125
Checked Exception
Checked Exception
ClassNotFoundException Class not found IlligalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread NoSuchFieldException A requested field does not exist NoSuchMethodException A requested method does not exist
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Thread
Thread- A thread is similar to a sequential program. A sequential program has a beginning, a sequence of steps to be execute, and an end. A thread also has a beginning, a sequence and an end. However, a thread is not a program on its own but runs within a program. A thread can be defined as the sequential flow of control within a program.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Thread Cont.
Every program has at least one thread that is called the primary thread. We can create more threads when necessary.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
126
Application of Thread
Use-Threads are very useful when we have large computation that take several seconds to complete, and user should not perceive the delay. Animation is another area where threads are used. Most computer games use graphics and the score and the audio effects go on simultaneously.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Single Thread
A process that is made only one thread is said to be single threaded. A single threaded application can perform only one task at a time. In such a situation you wait for one task to complete so that another can start. A process having more than one thread is said to be multithreaded.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
127
Multithread
Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Multithreaded Cont.
Multiple threads in a process run at the same time, perform different tasks and interact with each other. e.g. Microsoft internet explorer, is a web browser within browser, we can print a page in the background , while you are scrolling a page. You can play audio and watch animated images at the same time. This behavior is close to real life where you perform several tasks concurrently.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Thread Class
The java.lang.thread class is used to construct and access individual threads in a multithreaded application. Syntax:two general form Access_specifier <class_name> extends Thread { //body }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
128
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
129
Blocked
New
Ready
Running
Done
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
130
131
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
132
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
133
Multiple threads in a process run at the same time, perform different tasks and interact with each other. e.g. Microsoft internet explorer, is a web browser within browser, we can print a page in the background , while you are scrolling a page .You can play audio and watch animated images at the same time. This behavior is close to real life where you perform several tasks concurrently.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
The thread class The java.lang.thread class is used to construct and access individual threads in a multithreaded application. Syntax: Access_specifier <class_name> extends Thread { //body }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
134
A thread group is a data structure that controls the state of a collection of threads as a whole. The sleep() method causes the thread from which it is called to suspend execution for the specified period of milliseconds. static void sleep(long milliseconds) throws InterruptedException The no of milliseconds to suspend is specified in milliseconds.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
static void sleep(long millisecond,int nanoseconds)throws InterruptedException This is useful only in environments that allow timing period as short as nanoseconds.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
setName()- set the name of a thread getName()-obtain the name of a thread final void setName(String ThreadName) final String getName() Where, ThreadName is the name of thread.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
135
Creating a Thread
Creating a Thread In the most general sense, you can create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished: You can extend the Thread class, itself You can implement the Runnable interface
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Creating a Thread
Extending Thread To create a thread, is to create a new class that extends Thread, an then to create an instance of that class. The extending class must override the run() method, which is the entry point for the new thread.It must also call start() method to begin execution of the new Thread.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Extending Thread
class NewThread extends Thread { NewThread() { //create a new second ,Thread super("Demo Thread"); System.out.println("Child Thread"+this); start(); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
136
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
137
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Implementing Runnable
Implementing Runnable: To create a thread is to create a class that implements Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class needs only implement a single method called run(), which is declared like this: public void run();
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
138
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
139
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
140
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
141
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Thread Methods
As you can see, once started, all three child threads share the CPU. Notice the call to sleep()in main().This cause the main thread to sleep for ten seconds and ensures that it will finish last. Using isAlive() and join()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
142
This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Synchronization
Synchronization When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
143
Monitor
Monitor: The monitor is mechanism, can hold only one thread. Once a thread enters a monitor, all other threads must wait until that threads exits the monitor.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Inter-Thread Communication
Sometimes one thread may be interested in the activities of another. Or, one could have a functional dependency on another. Reading from a file or over a network? Waiting for a given thread to return a result. Polling (Busy Waiting) vs. Notification BadConsumer Example
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Inter-Thread Communication
final void wait()-tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify(). final void notify()- wakes up the first thread that called wait() on the same object. final void notifyAll()-wakes up all the threads that called wait() on the same object.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
144
Deadlock
Deadlock A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Input/Output Programming
java.io (package) A collection of things wrapped or boxed together. A package is a namespace that organizes a set of related classes and interfaces Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
145
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
146
Input/Output Exception
IOException: Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
147
Types Of Streams
Java defines two types of streams: 1. Byte 2. Character Byte stream provides a convenient means for handling input and output of bytes. It is used , when reading and writing binary data.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Character Streams
Character streams provides a convenient means for handling input and output of character. They use Unicode therefore , can be internationalized. Also in some cases character streams are more efficient than byte stream
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
148
Character Stream
Used to read and write text. They are very nice because they handle unicode character conversion for you. Methods provided: int read() int read(char[] buf) int read(char[] buf, int offset, int len)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
149
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Byte Stream
Used to read and write everything else Methods provided: int read() int read(byte[] buff) int read(byte[] buff, int offset, int len) In general, for every read method, there is a write method.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
150
File handling
A file is a collection of related records placed in a specific area on the disk. Java.io package provides a class known as the File class that provide support for creating files. A file object is used to obtain or manipulate the information associated with a disk file. It will give the permission , directory path and so on.there are some constructors can be used to create a file Objects. 1. File(String pathname) 2. File(String pathname,String filename) 3. File(File obj, String filename)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
In general use the readers and writers for text files, and streams for when you dont know what may be in the files. e.g. File f1=new File(/) //create a file using directory path
File f2=new File(/,a.java);// it uses directory path
and file name.
java.io.File
The File class is very useful for information about files and the directory structure. Constructer takes a String for the name Useful methods:
.exists() .isDirectory() .listFiles() - Lists the files if its a directory .canRead() / .canWrite() - check permissions File.listRoots() - returns an array of the roots of a file system. .length() .delete()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
151
java.io.RandomAccessFile
Not a stream file. There is a file pointer which you can use to read and write to random place in the file. You can read and write only primitive data types - writeByte(), writeInt(), writeBoolean() Its faster to jump between points in the file, than search an entire stream file.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
transient modifier
transient modifier: It is used when you do not want to store certain data member to file. class a { transient boolean b;// not to be stored int i; //to be store }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
152
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63
Agenda
Introduction Elements of Client Server Computing Networking Basics Understanding Ports and Sockets Java Sockets Implementing a Server Implementing a Client Sample Examples Conclusions
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
153
Socket
Socket: It is used for transmission control protocol/Internet protocol (TCP/IP). The advantage of TCP/IP is the client can be any kind of computer. So all the computers in a network implementing TCP/IP can communicate with each other through sockets. A socket is one end point of a two_way communication link between two programs running on the network. The socket classes is used to represent the connection between a client program and a server program.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Socket Cont.
The URL, URLConnection, Socket, ServerSocket classes are used TCP to communicate over the network. The DatagramPacket, DatagramSocket and MulticastSockets classes are used in UDP. Note: Socket is not a physical device but an abstraction for the network software, that enables communication between a server and a client.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
IP Address
IP Address: The internet protocol (IP) provides every network device with a logical address called an IP address. It is represented as a series of four 8 bit numbers. So, An IP address consists of 32 bit patterns each range is in the value from 0 to 255. In java InetAddress is a class under net pakage used for finding IP addresses. It has the following methods getLocalHost, getByName or getAllByName.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
154
Port Cont.
Ports are identified by a 16 bit number, which TCP and UDP use the port to deliver the data to the right application. The TCP/UDP protocols use ports to map incoming data to a particular process running on a computer. Port numbers ranges from 0 to 65535, because ports are represented by 16 bit numbers. The port numbers ranges from 01023 are reserved for use by well known services. These ports are called well known ports.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Port Cont.
Every protocol has a default port number, which is used if the port number is not specified. Port is not a physical device but an abstraction to make communication between a server and a client. e.g.
FTP 23 SMTP 25 DOMAIN 53 HTTP 80 etc.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
155
Internet
Java is a programming language for the internet. It provides the package java.net for networking programs. Internet: It is a networks of network.It is a mechanism for information dissemination, and a medium for collaboration and interaction between individuals and their computers without regards for geographic locations. Java supports two types of protocols basically: TCP/IP and UDP/IP.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Internet Cont.
Internet and WWW have emerged as global ubiquitous media for communication and changing the way we conduct science, engineering, and commerce. They also changing the way we learn, live, enjoy, communicate, interact, engage, etc. It appears like the modern life activities are getting completely centered around the Internet.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
PC client
Internet Server
Local Area Network
PD A
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
156
Increased demand for Internet applications To take advantage of opportunities presented by the Internet, businesses are continuously seeking new and innovative ways and means for offering their services via the Internet. This created a huge demand for software designers with skills to create new Internet-enabled applications or migrate existing/legacy applications on the Internet platform. Object-oriented Java technologiesSockets, threads, RMI, clustering, Web services-- have emerged as leading solutions for creating portable, efficient, and maintainable large and complex Internet applications.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Networking Basics
Applications Layer Standard apps HTTP FTP Telnet User apps Transport Layer TCP UDP Programming Interface: Sockets Network Layer IP Link Layer Device drivers
TCP/IP Stack
Application (http,ftp,telnet, ) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
157
TCP/IP Stack
Application (http,ftp,telnet, ) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
TCP/IP Stack
Application (http,ftp,telnet, ) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Understanding Ports
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
P o r t TCP Client
server
app
app
app
app
port
port
port
port
158
Sockets
Sockets provide an interface for programming networks at the transport layer. Network communication using Sockets is very much similar to performing file I/O In fact, socket handle is treated like file handle. The streams used in file I/O operation are also applicable to socket-based I/O Socket-based communication is programming language independent. That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Socket Communication
A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request.
server
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
port
159
server port
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Sockets and Java Socket Classes A socket is an endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent. Javas .net package provides two classes: Socket for implementing a client ServerSocket for implementing a server
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Java Sockets
Server
ServerSocket(1234)
Output/write stream
Client
Socket(128.250.25.158, 1234)
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
160
Implementing a Server
1. Open the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); 2. Wait for the Client Request: Socket client = server.accept(); 3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() );
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Implementing a Client
1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server: Receive data from the server: String line = is.readLine(); Send data to the server: os.writeBytes("Hello\n"); 4. Close the socket when done: client.close();
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
161
162
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Run
Run Server on mundroo.cs.mu.oz.au [raj@mundroo] java SimpleServer & Run Client on any machine (including mundroo): [raj@mundroo] java SimpleClient Hi there If you run client when server is not up: [raj@mundroo] sockets [1:147] java SimpleClient Exception in thread "main" java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120) at java.net.Socket.<init>(Socket.java:273) at java.net.Socket.<init>(Socket.java:100) at SimpleClient.main(SimpleClient.java:6)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Socket Exceptions
try { Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println("Unknown host: " + host); uhe.printStackTrace(); } catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
163
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); } } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
164
Client 1 Process
Server Process
Server Threads
n
Internet
Client 2 Process
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Conclusion
Programming client/server applications in Java is fun and challenging. Programming socket programming in Java is much easier than doing it in other languages such as C.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
165
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
166
Event Handling
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63
Learning Objective
Event Handling Different Mechanism (AWT Introduction) Delegation Event Model Event Classes Event Listener Interfaces Adapter and Inner Classes Working with windows Graphics and Text Using AWT Controls Layout Managers and Menus Handling Image Animation Sound and Video Java Applet Beans Swings Servlets
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
AWT Introduction
All the various types of AWT events, are placed in a separate package called java.awt.event for the sake of convenience. The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit. The AWT is now part of the Java Foundation Classes (JFC) The standard API for providing a graphical user interface (GUI) for a Java program.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
167
AWT Introduction
The AWT provides, among other things: 1. A basic set of GUI widgets such as buttons, text boxes, and menus, etc. 2. The core of the GUI event subsystem . 3. The interface between the native windowing system and the Java application. 4. Several layout managers. 5. A java.awt.datatransfer package for use with the Clipboard and Drag and Drop
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
AWT Introduction
6.The interface to input devices such as mouse and keyboards. 7.The AWT Native Interface, which enables rendering libraries compiled to native code to draw directly to an AWT Canvas object drawing surface. 8. Access to the system tray on supporting systems 9.The ability to launch some desktop applications such as web browsers and email clients from a Java application
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
AWT Definition
AWT- It is a package that contains classes, which are used to create interfaces and in event handling. Java.awt (package) Component
Label
Button Window
Container Panel
Text Component
TextField Frame
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
TextArea
168
Component Cont.
A component is an object that can be displayed on the screen and can interact with the user. It is like a button or scroll bar that has visual representation in a screen window. It has special property like background color and font color.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Component
Component is an abstract class that encapsulate all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. A component object is responsible for remembering the current foreground and background colors and the currently selected text font.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Container
Container:- It is a subclass of Component class. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instance of Component). It uses various Layout Managers.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
169
Panel
Panel:- It is a concrete subclass of a Container. It doesnt add any new methods; it simply implements Container. Panel is a superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. Panel is a window that does not contain a title bar, Menu bar, or border.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Panel Cont.
When you run an applet using an applet viewer, the applet viewer provides the title and border. Other components can be added to a panel object by its add() method. (inherited from container). Once these components have been added, you can position and resize them manually using the setLocation(), setSize(), or setBounds() methods defined by Component.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Windows
Window:- The window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally we wont create window objects directly, instead will use a subclass of Window called Frame.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
170
Frame
Frame:- sub class of a Window .
It has a title bar, menu bar, borders, and resizing corners. When a Frame window is created by a program a normal window is created (rather than an applet).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Canvas
Canvas:- Although it is not part of the hierarchy for applet or frame window, there is one another type of window called Canvas. Canvas encapsulates a blank window upon which you can draw.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
GUI components
Buttons Common buttons Radio buttons Check buttons
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
171
GUI components
GUI components
Combo boxes Lists Menus
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
GUI components
Spinners Sliders Textfields
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
172
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
173
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
174
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
175
Events
Events: In the delegation model, an event is an object that describes a state change in a source. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse, etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Events Cont.
Events may also occur that are not directly caused by interactions with a user interface. e.g. an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed, etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Event Delegation Model is based on four concepts: 1. The Event Classes 2. The Event Listeners 3. Explicit Event Enabling 4. Adapters
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
176
At the root of the java event class hierarchy is EventObject, which is an java.util. It is the superclass for all events. EventObject contains two methods: getSource() and toString(). getSource()- method returns the source of the event. toString()- returns the string equivalent of the event.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
1. Event Class
ActionEvent generated by component activation AdjustmentEvent generated by adjustment of adjustable components such as scroll bars ContainerEvent generated when components are added to or removed from a container FocusEvent generated when a component receives input focus ItemEvent generated when an item is selected from a list, choice or check box KeyEvent generated by keyboard activity MouseEvent generated by mouse activity PaintEvent generated when a component is painted TextEvent generated when a text component is modified WindowEvent generated by window activity like minimizing or maximizing
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
2. Event Listener
Listeners for Different Events For each event type that can occur, the application can add event listeners, that have methods invoked when the event occurs. The listeners are defined as interfaces, so that an actual listener has to implement these methods.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
177
2. Event Listener
The names of the listener classes are simply derived from the names of the events they handle, MouseEvent's have two different types of listener for efficiency reasons. (MouseListener and MouseMotionListener)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
178
Listeners
Any number of event listener objects can listen for all kinds of events from any number of event source objects. e.g. a program might create one listener per event source or a program might have a single listener for all events from all sources.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Listeners
Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Listeners
Each type of listeners can be notified only for its corresponding types of events which can be generated by specific types of sources.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
179
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
MouseMotion Listener
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Listeners as interfaces
You implement an interface to create a listener. In the case of a single source that generates multiple types of events you can create a single listener that implements all interfaces (remember: a class may extend only one superclass but implement more than one interfaces).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
180
MouseWheelEvent
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
the
You can find the source of an event by using the getSource method:
event_object.getSource();
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
181
Listener
ActionListener AdjustmentListener ComponentListener
Method
actionPerformed() adjustmentValueChangd() componentResized() componentMoved() componentShown() componentHidden() focusGained() focusLost() itemStateChanged() keyTyped() keyPressed() keyReleased()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
MouseMotionListener
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Dialog
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
182
Note that every GUI object that inherits from Component can have Component, Focus, Key, Mouse and MouseMotion listeners added.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Action Events
Action events are generated for the following objects: GUI Object Action Button Click on Button List Double-click on an item MenuItem Click on MenuItem TextField Press <Enter> key
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Item Events
Item events are generated for the following objects: GUI Object Action Choice Click on item Checkbox Select an item Deselect an item List Select an item Deselect an item Extend a selection Reduce a selection
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
183
3. Listeners vs. Explicit Enabling Event A subclass can handle its own events by adding itself as a listener. In Explicit Event Handling, you control the order.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
4. Adapter class
Java provides adapter classes that implements the corresponding listener interface containing more than one method. The methods in the classes are empty. The listener class that you define can extend the Adapter class and override the methods that you need.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
184
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
185
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
186
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Anonymous Class
Notes:: Inner classes also called nested classes and these are declared within other classes. The program that are not named within a program are called anonymous class. An anonymous class cannot have a constructor as the class has no name.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Inner classes
You may create all different classes independently and put them in separate files. you can implement your listeners inside the class that extends your Frame, making it an inner class. This enables you to put everything in one class (and hence in one file).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
187
Inner Classes
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="MouseInnerDemo" width=100 height=100> </applet> */ public class MouseInnerDemo extends Applet {
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
188
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
189
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
190
Frame: Frame() Frame(String) Frame f=new Frame(calculator); setTitle(String), f.setTitle(Calculator) getTitle(String) setLayout(null)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Label -is a control that is used for displaying messages or output. 1.Label() 2.Label(String) Label l= new Label() l.setText() l.getText()
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
191
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
192
Drawing Lines
drawLine public 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. Parameters:
x1 - the first point's x coordinate. y1 - the first point's y coordinate. x2 - the second point's x coordinate. y2 - the second point's y coordinate.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Drawing Rectangles
drawRect public void drawRect(int x, int y, int width, int height)
Draws the outline of the specified rectangle. The left and right edges of the rectangle are at x and x + width. The top and bottom edges are at y and y + height. The rectangle is drawn using the graphics context's current color. Parameters:
x - the x coordinate of the rectangle to be drawn. y - the y coordinate of the rectangle to be drawn. width - the width of the rectangle to be drawn. height - the height of the rectangle to be drawn
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
193
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
194
195
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
196
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
197
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
198
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
199
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
200
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
201
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
202
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Layout Managers
You use layout managers to design your GUIs. There are several managers like: FlowLayout BorderLayout GridLayout CardLayout GridBagLayout
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
203
FlowLayout
Default layout Components laid out from the top-left corner, from left to right and top to bottom like a text.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
BorderLayout
Places components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
GridLayout
Simply makes a bunch of components equal in size and displays them in the requested number of rows and columns
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
204
CardLayout
lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
GridBagLayout
is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
205
Handling Image
The java.awt.Image class is actually abstract. However, methods such as getImage(URL) in the Applet class return an instance of a concrete subclass provided by the particular JVM implementation. The details of that subclass are not important since you invoke only methods listed in the Image class, many of which are overridden by the subclass.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
206
Animation
Threads and Animation The only functions we have seen in applets so far are init(), paint(), and functions called in response to input events. All of these functions are supposed to do a small amount of work and return quickly. There has been no opportunity, so far, for a function to loop and do some continuous work.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Animation Cont.
This applet creates a thread, a separate stream of execution, to perform a background task. The body of the thread's code is in the run() function. In this case, the purpose of the thread is to increment the variable i once every 1000 milliseconds, and cause the applet to redraw itself. The result is a simple animation.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Animation Cont.
import java.applet.*; import java.awt.*; public class Threads1 extends Applet implements Runnable { int width, height; int i = 0; Thread t = null; boolean threadSuspended;
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
207
Animation Cont.
// Executed when the applet is first created. public void init() { System.out.println("init(): begin"); width = getSize().width; height = getSize().height; setBackground( Color.black ); System.out.println("init(): end"); } // Executed when the applet is destroyed. public void destroy() { System.out.println("destroy()"); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Animation Cont.
// Executed after the applet is created; and also whenever // the browser returns to the page containing the applet. public void start() { System.out.println("start(): begin"); if ( t == null ) { System.out.println("start(): creating thread"); t = new Thread( this ); System.out.println("start(): starting thread"); threadSuspended = false; t.start(); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Animation Cont.
else { if ( threadSuspended ) { threadSuspended = false; System.out.println("start(): notifying thread"); synchronized( this ) { notify(); } } } System.out.println("start(): end"); }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
208
Animation Cont.
// Executed whenever the browser leaves the page containing the applet. public void stop() { System.out.println("stop(): begin"); threadSuspended = true; } // Executed within the thread that this applet created. public void run() { System.out.println("run(): begin"); try { while (true) { System.out.println("run(): awake"); // Here's where the thread does some work ++i; // this is shorthand for "i = i+1;" if ( i == 10 ) { i = 0; }showStatus( "i is " + i );
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Animation Cont.
// Now the thread checks to see if it should suspend itself if ( threadSuspended ) { synchronized( this ) { while ( threadSuspended ) { System.out.println("run(): waiting"); wait(); } } } System.out.println("run(): requesting repaint"); repaint(); System.out.println("run(): sleeping"); t.sleep( 1000 ); // interval given in milliseconds } } catch (InterruptedException e) { } System.out.println("run(): end");}
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Animation Cont.
// Executed whenever the applet is asked to redraw itself. public void paint( Graphics g ) { System.out.println("paint()"); g.setColor( Color.green ); g.drawLine( width, height, i * width / 10, 0 ); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
209
APPLET
An Applet is Loaded into a java-enabled program (Netscape, Applet Viewer) Applet is not a stand-alone program (no main method), structured to run inside another program (browser) JVM runs applications, but not applets. An applet can run as an application if it defines a main(). Applets are usually event-driven.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
APPLET Cont.
Does I/O through a GUI, only displays error messages with stdout. Applets subclass java.applet Security - applets barred from reading/writing files on the client,cant load libraries, cant make network connections (except to its host), cant execute programs, etc...
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
210
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bean
Java Bean is a developed by Sun Microsystems that defines how Java objects interact. An object that conforms to this specification is called a JavaBean, and is similar to an ActiveX control. It can be used by any application that understands the JavaBeans format.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
211
Bean Cont.
The principal difference between ActiveX controls and JavaBeans are that ActiveX controls can be developed in any programming language but executed only on a Windows platform, whereas JavaBeans can be developed only in Java, but can run on any platform.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bean Cont.
A java bean is a software component that has been designed to be reusable in a variety of different environment. It may perform a simple function , such as checking the spelling of a document, or a complex function, . A bean may be visible and invisible to end user. e.g. Button on a GUI.. Software to generate a pie chart from a set of data points is an example of a Bean that can execute locally.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Advantage
A software component architecture provides standard mechanism to deal with software building blocks: A bean obtain all the benefits of javas writeonce, run-anywhere paradigm. The properties, events, and method of a Bean that are exposed to an application builder tool can be controlled.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
212
Java Beans
Java beans are a framework for creating components in Java. AWT and Swing packages are built within this framework Made to fit in with graphic development environments such as Jbuilder and Forte. An extension is Java Enterprise Beans
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bean Rules
Code must be written correctly Access methods must begin with get Mutation methods must begin with set Code must support event handling Objects must be persistent, i.e. implement serializable
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Java Beans: Development Environments Introspection used to asses what a bean can do (which methods it has) There is also an interface BeanInfo to give development tools more information Tools can change a beans properties, e.g. background color in a window if the window is regarded as a bean.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
213
Summary
We learned that JavaBeans are Java classes which adhere to an extremely simple coding convention. All you have to do is to implement java.io.Serializable interface, use a public empty argument constructor and provide public getter and setter methods to get and set the values of private variables ( properties ).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Swing
Swing is a widget toolkit for Java. It is part of Sun Microsystems' Java Foundation Classes (JFC) an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Swing Cont.
The Java Swing provides the multiple platform independent APIs interfaces for interacting between the users and GUIs components. All Java Swing classes imports form the import javax.swing.*; package. Java provides an interactive features for design the GUIs toolkit or components like: labels, buttons, text boxes, checkboxes, combo boxes, panels and sliders etc. All AWT flexible components can be handled by the Java Swing.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
214
Swing Cont.
The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
Above code sets the operation of close operation to Exit the application using the System exit method.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
} }
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
215
Servlet
Why Java Servlets Instead of CGI?
Efficient, Convenient, Powerful, Portable, Secure, Inexpensive Lightweight threads instead of OS threads created Single copy of code brought into memory for all threads versus per thread Data (session state) can be stored across threads within servlet container Java is portable and secure Requires little expense once servlet container integrated with web server
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Advantages
The advantages of using servlets is their fast performance and ease of use combined with more power over traditional CGI. Traditional CGI scripts written in Java have a number of disadvantages when it comes to performance. When a HTTP request is made a new process is created for each call of the CGI script. This overhead of process creation can be very system intensive especially when the script does relatively fast
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Advantages Cont.
operations (process creation will take more time than CGI script execution). Java servlets solve this problem by allowing each request to be handled by a separate Java thread within the Web server process, omitting separate process forking by the HTTP daemon. In addition, simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests. However with servlets there are same amount of threads as request but there will only be one copy of the servlet class created in memory.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
216
Servlet Structure
Java Servlet Objects on Server Side Managed by Servlet Container Loads/unloads servlets Directs requests to servlets Request doGet() Each request is run as its own thread
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Servlet Cont.
Web App with Servlets
GET
Servlet doGet()
HEADERS BODY
Servlet Container
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Servlet Cont.
5 Simple Steps for Java Servlets
1. Subclass off HttpServlet
2. Override doGet(....) method 3. HttpServletRequest getParameter("paramName") 4. HttpServletResponse set Content Type get PrintWriter send text to client via PrintWriter 5. Don't use instance variables
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
217
Servlet Lifecycle
Servlet Creation Single instance created init() method called You can override init() in your subclass of HttpServlet to do some initial code.... init() is NOT called again on further requests
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Summary
In this chapter, you learnt about Java events and the delegation event model necessary to support them. More specifically, you learned about Java events, including the event listener capable of generating them and how they are handled by the Java AWT library. You saw examples of using the swings that are more useful in event handling and a Java Servlet is an efficient, convenient, powerful, portable, secure, inexpensive thats why it is more useful.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
218
Conclusion
Event-driven programming provides the means to develop flexible applications where the user determines program flow. Implementing event handlers in Java is generally straightforward, but it's important to know which approach is best for which situation. In this article, we looked at three of the most common ways to implement event handling: dispatching events to an object, using an anonymous class to dispatch an event directly to the method that handles it, and using reflection to write a generic class that dispatches events to the event handler method.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Review Questions
Objective type Questions Q1) The CheckboxGroup class is a subclass of the Component class. (a)True (b)False Q2) You want to construct a text area that is 80 characterwidths wide and 10 characters height tall.what code do you use? (a) New TextArea(80,10) (b) New TextArea(10,80)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
219
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
220
Unit-IV
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63
Learning Objectives
Overview of Internet and Intranet Services HTML Tags Tables Frames Graphical and animation techniques Static & Dynamic Web Pages DHTML ASP Javascript
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
The Internet, sometimes called the "Information Superhighway", is a worldwide, publicly accessible series of interconnected computer networks that transmit data (by packet switching) using the standard Internet Protocol (IP). It is a "network of networks" that consists of millions of smaller domestic, academic, business, and government networks, which together carry various information and services, such as electronic mail, online chat, file transfer, and the interlinked web pages).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
221
and other resources of the World Wide Web (WWW The Internet is a collection of interconnected computer networks, linked by copper wires, fiber-optic cables, wireless connections, etc. In contrast, the Web is a collection of interconnected documents and other resources, linked by hyperlinks and URLs. The World Wide Web is one of the services accessible via the Internet, along with various others including e-mail, file sharing, online gaming,etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Overview of Internet and Intranet Services Cont. An intranet is a private computer network that uses Internet protocols and network connectivity to securely share part of an organization's information or operations with its employees. Sometimes the term refers only to the most visible service, the internal website. The same concepts and technologies of the Internet such as clients and servers running on the Internet protocol suite are used to build an intranet. HTTP and other Internet protocols are commonly used as well, such as FTP.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
An intranet is an information portal designed specifically for the internal communications of small, medium or large businesses, enterprises, governments, industries or financial institutions of any size or complexity. Intranets can be custom-designed to fit the exact needs of businesses no matter where they are situated. Users of intranets consists mainly of:
1. Members of the executive team. 2. Accounting and order billing. 3. Managers and directors. 4. Sales people and support staff. 5. Customer service, help desk, etc..
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
222
Extranet
An extranet is somewhat very similar to an intranet. Extranets are designed specifically to give external, limited access to certain files of your computer systems to: 1. Certain large or privileged customers. 2. Selected industry partners. 3. Suppliers and subcontractors... etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Disadvantage
Disadvantages Theft of Personal information Spamming Email spamming is when people send out large batches of emails (mail shots) to unknown recipients. This is similar to 'junk mail' you get through the post. Search engine spamming is used by people trying to improve their rankings by repetitive use of keywords and submissions. Virus threat, etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
223
Static page
Static Pages Most of these advantages and disadvantages apply to normal HTML pages in particular. Advantages Quick and easy to put together, even by someone who doesn't have much experience. Ideal for demonstrating how a site will look. Cache friendly, one copy can be shown to many people.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Dynamic page
Dynamic Pages Typically written in various scripting languages or technologies such as ASP, PHP, Perl or JSP. Advantages Offers highly personalized and customised visitor options. Database access improves the personalized experience (as opposed to using just client side cookies)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
224
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
HTML Tag
What is an HTML File? HTML stands for Hyper Text Markup Language An HTML file is a text file containing small markup tags The markup tags tell the Web browser how to display the page An HTML file must have an htm or html file extension An HTML file can be created using a simple text editor.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
225
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
226
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
227
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Formatted Text
<html> <body> <b>This text is bold</b><br> <strong> This text is strong </strong><br> <big> This text is big </big><br> <small>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
228
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Preformatted Text
<html> <body> <!--pre> !--comment-This is preformatted text. It preserves both spaces and line breaks. </pre-->
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
229
Preformatted Text
<p>The pre tag is good for displaying computer code:</p> <pre> for i = 1 to 20 print i next i </pre> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Preformatted Text
<html> <body> <address> Donald Duck<br> BOX 555<br> Disneyland<br> USA </address></body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Create hyperlink
The Anchor Tag and the href Attribute HTML uses the <a> (anchor) tag to create a link to another document. An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a movie, etc. The syntax of creating an anchor:
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
230
Create hyperlink
<a href="url">Text to be displayed</a> The <a> tag is used to create an anchor to link from, the href attribute is used to address the document to link to, and the words between the open and close of the anchor tag will be displayed as a hyperlink.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Create Hyperlink
<html> <body><p> <a href="lastpage.htm"> This text</a> is a link to a page on this Web site. </p> <p> <a href="http://www.microsoft.com/"> This text</a> is a link to a page on the World Wide Web. </p></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
An image as a link
<html> <body> <p> You can also use an image as a link: <a href="lastpage.htm"> <img border="0" src="buttonnext.gif" width="65" height="38"> </a> </p></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
231
Attribute
Attributes Example 1: <h1> defines the start of a heading. <h1 align="center"> has additional information about the alignment. Attributes Example 2: <body> defines the body of an HTML document. <body bgcolor="yellow"> has additional information about the background color. Or, <body bgcolor=#000000> <body bgcolor=#C0C0C0>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Font Color
Font color- is used to color the texts used in html documents. <html> <head> <title>Example of Formatting Text</title> </head> <body> <p><font COLOR="#00FF00">This text is Green</font></p> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
232
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
233
Table
Tables Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). The letters td stands for "table data," which is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Table Example
<html> <caption>hello</caption> <body> <table> <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
234
Table Attributes
Syntax<TABLE>...</TABLE>
Attribute SUMMARY=Text(purpose/structure of table) Specifications WIDTH=Length (table width) BORDER=Pixels (border width) CELLSPACING=Length (spacing between cells) CELLPADDING=Length (spacing within cells)
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
235
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Frames
Frames With frames, you can display more than one HTML document in the same browser window. Each HTML document is called a frame, and each frame is independent of the others. The disadvantages of using frames are: The web developer must keep track of more HTML documents.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Frames Cont.
The Frameset Tag The <frameset> tag defines how to divide window into frames. Each frameset defines a set of rows columns. The values of the rows/columns indicate amount of screen area each row/column occupy. the or the will
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
236
Frames Cont.
The Frameset Tag The <frameset> tag defines how to divide the window into frames Each frameset defines a set of rows or columns The values of the rows/columns indicate the amount of screen area each row/column will occupy <frameset cols="25%,75%">
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Frames Cont.
<frame src="frame_a.htm"> <frame src="frame_b.htm"> </frameset> Note: The frameset column size value can also be set in pixels (cols="200,500"), and one of the columns can be set to use the remaining space (cols="25%,*").
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Vertical frameset
<html> <frameset cols="25%,50%,25%"> <frame name=f1 src="frame_a.htm"> <frame name=f2 src="frame_b.htm"> <frame name=f3 src="frame_c.htm"> </frameset> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
237
Horizontal frameset
<html> <frameset rows="25%,50%,25%"> <frame src="frame_a.htm"> <frame src="frame_b.htm"> <frame src="frame_c.htm"> </frameset> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
iframe
iframes are widely used to display web content in a separate inline floating frame and they are supported by all modern HTML browsers. <IFRAME SRC="b.html" WIDTH=275 HEIGHT=200 ALIGN=RIGHT>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
iframe Cont.
<TABLE ALIGN=RIGHT BORDER=1 CELLPADDING=5> <TR><TD>See the article on <A HREF=b.html">Stuff about the Beaver</A></TD></TR> </TABLE> </IFRAME>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
238
iframe Cont.
The IFRAME element allows you to insert a frame within a block of text. Inserting an inline frame within a section of text is much like inserting an object via the OBJECT element: they both allow you to insert an HTML document in the middle of another, they may both be aligned with surrounding text, etc. The information to be inserted inline is designated by the src attribute of this element. The contents of the IFRAME element, on the other hand, should only be displayed by user agents that do not support
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
iframe Cont.
frames or are configured not to display frames. For user agents that support frames, the following example will place an inline frame surrounded by a border in the middle of the text. <IFRAME src="al.html" width="400" height="500" scrolling="auto" frameborder="1"> [Your user agent does not support frames or is currently configured not to display frames. However, you may visit <A href="a.html">the related document.</A>] </IFRAME>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
iframe Cont.
<HTML> <HEAD> <TITLE>A simple frameset document</TITLE> </HEAD> <FRAMESET cols="20%, 80%"> <FRAMESET rows="100, 200"> <FRAME src="contents_of_frame1.html"> <FRAME src="contents_of_frame2.gif"> </FRAMESET> <FRAME src="contents_of_frame3.html"> <NOFRAMES>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
239
iframe Cont.
<P>This frameset document contains: <UL> <LI><A href="contents_of_frame1.html">Some neat contents</A> <LI><IMG src="contents_of_frame2.gif" alt="A neat image"> <LI><A href="contents_of_frame3.html">Some other neat contents</A> </UL> </NOFRAMES> </FRAMESET> </HTML>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
HTML Comment
A comment declaration starts with <!, followed by zero or more comments, followed by >. A comment starts and ends with "--", and does not contain any occurrence of "--". This means that the following are all legal comments: 1. <!-- Hello --> 2. <!-- Hello -- -- Hello--> 3. <!----> 4. <!------ Hello --> 5. <!>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Lists
Lists: Lists are of two types 1. Unordered list, and 2. Ordered list Unordered Lists An unordered list is a list of items. The list items are marked with bullets (typically small black circles). An unordered list starts with the <ul> and end with </ul> tag. Each list item starts with the <li> and end with </li> tag.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
240
Unordered Lists
<ul> <li>Coffee</li> <li>Milk</li> </ul> Coffee Milk
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Ordered Lists
Ordered Lists An ordered list is also a list of items. The list items are marked with numbers. An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. <ol> <li>Coffee</li> <li>Milk</li> </ol> 1.Coffee 2.Milk
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Definition Lists
Definition Lists A definition list is not a list of items. This is a list of terms and explanation of the terms. A definition list starts with the <dl> tag. Each definition-list term starts with the <dt> tag. Each definition-list definition starts with the <dd> tag. <dl> <dt>Coffee</dt> <dd>Black hot drink</dd> <dt>Milk</dt>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
241
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Forms
Forms A form is an area that can contain form elements. Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form. TextFields example given below:
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
242
Forms Example
<html> <body> <form action=""> First name: <input type="text" name="firstname"> <br> Last name: <input type="text" name="lastname"> <input type=Submit" value=Submit></form> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
243
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
244
Insert images from different locations <html> <body> <p> An image from another folder: <img src="/images/netscape.gif" width="33" height="32"> </p> <p> An image from yahoo
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Insert images from different locations <img src="http://www.yahoo.com/images/ie.gif"> </p> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Background color
Backgrounds The <body> tag has two attributes where you can specify backgrounds. The background can be a color or an image. Bgcolor The bgcolor attribute specifies a backgroundcolor for an HTML page. The value of this attribute can be a hexadecimal number, an RGB value, or a color name:<body bgcolor="#000000"> <body bgcolor="rgb(0,0,0)"> <body bgcolor="black">
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
245
Radio Button
Radio Buttons Radio Buttons are used when you want the user to select one of a limited number of choices. <html> <form> <input type="radio" name="sex" value="male"> Male <br>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
246
Checkbox Example
Checkboxes Checkboxes are used when you want the user to select one or more options of a limited number of choices. <html> <form> bike:       <input type="checkbox" name="vehicle" value="Bike">
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
The Form's Action Attribute and the Submit Button When the user clicks on the "Submit" button, the content of the form is sent to another file. The form's action attribute defines the name of the file to send the content to. The file defined in the action attribute usually does something with the received input. <html> <form name="input" action=filename.htm" method="get/post">
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
247
Username: <input type="text" name="user"> <br><br><br><br> <input type="Button" value="OK">      <input type="submit" value="Submit"> </form> </html> Where, <input type="text> tag is used for single line text.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Dropdown List
dropdown box <html> <body> <form action=""> <select name="country"> <option value="india">india</option> <option value="pakistan">pakistan</option> <option value="america">america</option> <option value="africa">africa</option> </select> </form></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
248
Textarea Example
Textarea -Multi line input in a form
<HTML> <body> <textarea name= address rows=10 cols=30> bvicam , new delhi </textarea> </body> </html>
Where name=name rows= number of visible text lines cols= number of visible width of text, in average character widths
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Link Example
<html> <body> <form action="a.htm"> <input type="button" value="Hello world!"> </form> </body> </html> This page will not go to next page.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Fieldset
Fieldset around data This example demonstrates how to draw a border with a caption around your data. <html> <body> <fieldset> <legend> Health information: </legend> <form action="">
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
249
Fieldset Example
Height <input type="text" size="3"> Weight <input type="text" size="3"> </form> </fieldset> <p>If there is no border around the input form, your browser is too old</p></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
marquee
<marquee behavior="alternate">This text will bounce from left to right</marquee> Bgcolor: Sets the background color of the marquee. <marquee bgcolor="blue">This marquee's background color will be blue.</marquee> Direction: Sets the direction of the marquee box to either left-to-right or right-to-left. Later browsers added support for a movie credit style bottom-up and top-down values.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Marquee Cont.
<marquee direction="right">This text will scroll from left to right.</marquee> Height: This sets how tall the marquee should be. <marquee height="20px">The height of this marquee is twenty pixels.</marquee>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
250
Marquee Cont.
Width: This sets how wide the marquee should be. <marquee width="100px">This marquee is only a hundred pixels wide!</marquee> Loop: This sets how many times the marquee should 'Loop' its text. <marquee loop="2">You will only see this text twice before it stops playing.</marquee>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Marquee Cont.
Scrollamount: This is how many pixels the text moves between 'frames', in pixels. <marquee scrollamount="10">This text will move ten pixels per 'frame'</marquee> Scrolldelay: This sets the amount of time, in milliseconds, between 'frames'. <marquee scrolldelay="1000">This would be so slow, you'd get no sense of animation.</marquee> <marquee scrolldelay="1">This would be so fast, you couldn't see it!</marquee>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Marquee Cont.
<html> <marquee behavior="alternate">This text will bounce from left to right</marquee> <marquee bgcolor="yellow">This marquee's background color will be blue.</marquee> <marquee direction="right">This text will scroll from left to right.</marquee> <marquee height="20px">The height of this marquee is twenty pixels.</marquee> <marquee width="100px">This marquee is only a hundred pixels wide!</marquee>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
251
Marquee Cont.
<marquee loop="2">You will only see this text twice before it stops playing.</marquee> <marquee scrollamount="10">This text will move ten pixels per 'frame'</marquee> <marquee scrolldelay="1000">This would be so slow, you'd get no sense of animation.</marquee> <marquee scrolldelay="1">This would be so fast, you couldn't see it!</marquee> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
252
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
DHTML
DHTML is the art of making HTML pages dynamic! DHTML is a combination of technologies used to create dynamic and interactive Web sites. To most people DHTML means a combination of HTML, Style Sheets and JavaScript. DHTML is NOT a W3C Standard DHTML stands for Dynamic HTML.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
253
DHTML Cont.
DHTML is not a standard defined by the World Wide Web Consortium (W3C). DHTML is a "marketing term" - used by Netscape and Microsoft to describe the new technologies the 4.x generation browsers would support. DHTML is a combination of technologies used to create dynamic Web sites. To most people DHTML means a combination of HTML 4.0, Style Sheets and JavaScript.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
DHTML Cont.
DHTML Technologies With DHTML a Web developer can control how to display and position HTML elements in a browser window. HTML 4.0 With HTML 4.0 all formatting can be moved out of the HTML document and into a separate style sheet. Because HTML 4.0 separates the presentation of the document from its structure, we have total control of presentation layout without messing up the document content.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
DHTML Cont.
Cascading Style Sheets (CSS) With CSS we have a style and layout model for HTML documents. CSS was a breakthrough in Web design because it allowed developers to control the style and layout of multiple Web pages all at once. As a Web developer you can define a style for each HTML element and apply it to as many Web pages as you want. To make a global change, simply change the style, and all elements in the Web are updated automatically.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
254
ASP
What is ASP? ASP stands for Active Server Pages. ASP is a program that runs inside IIS IIS stands for Internet Information Services IIS comes as a free component with Windows 2000 IIS is also a part of the Windows NT 4.0 Option Pack The Option Pack can be downloaded from Microsoft
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
ASP Cont.
PWS is a smaller - but fully functional - version of IIS PWS can be found on your Windows 95/98 CD ASP Compatibility ASP is a Microsoft Technology To run IIS you must have Windows NT 4.0 or later To run PWS you must have Windows 95 or later ChiliASP is a technology that runs ASP without Windows OS InstantASP is another technology that runs ASP without Windows
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
ASP Cont.
What is an ASP File? An ASP file is just the same as an HTML file ASP is a powerful tool for making dynamic and interactive Web pages. An ASP file can contain text, HTML, XML, and scripts . Scripts in an ASP file are executed on the server An ASP file has the file extension ".asp"
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
255
ASP Cont.
How Does ASP Differ from HTML? When a browser requests an HTML file, the server returns the file When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
ASP Cont.
What can ASP do for you? Dynamically edit, change or add any content of a Web page Respond to user queries or data submitted from HTML forms Access any data or databases and return the results to a browser Customize a Web page to make it more useful for individual users
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
ASP Cont.
The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed. Accessible by a larger population , Cheaper Faster, Interactive,. Provide security since your ASP code can not be viewed from the browser Clever ASP programming can minimize the network traffic. Database handling.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
256
ASP Cont.
How to Run ASP on your own PC You can run ASP on your own PC without an external server. To do that, you must install Microsoft's Personal Web Server (PWS) or Internet Information Services (IIS) on your PC.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Conclusion
ASP is used to add server-side scripts to your web site, to make your web site more dynamic and interactive. You have learned how to dynamically edit, change or add any content of a web page, respond to data submitted from HTML forms, access any data or databases and return the results to a browser, customize a web page to make it more useful for individual users.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
257
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
ASP Example
Write Output to a Browser The response.write command is used to write output to a browser. The following example sends the text "Hello World" to the browser:
<HTML> <body> <% response.write("Hello World!") %> </body> </html> OUTPUT: Hello World!
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
258
Requset.QueryString
Request.QueryString The Request.QueryString command is used to collect values in a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. If a user typed Divya" and "Goel" in the form example above, the URL sent to the server would look like this:
http://localhost/firstform.asp?fname=Divya&lname=Goel
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
259
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
260
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
261
Request.Form
Request.Form The Request.Form command is used to collect values in a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Request.Form Example
<html> <body> <form action="demo_simpleform.asp" method="post"> Your name: <input type="text" name="fname" size="20" /> <input type="submit" value="Submit" /> </form> <% dim fname fname=Request.Form("fname") If fname<>"" Then Response.Write("Hello " & fname & "!<br />") Response.Write("How are you today?") End If %> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
262
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
radio button
<html> <% dim cars cars=Request.Form("cars") %> <body> <form action="demo_radiob.asp" method="post"> <p>Please select your favorite car:</p> <input type="radio" name="cars"
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
263
An Application
Assume that the ASP file "simpleform.asp" contains the following script: <body> Welcome <% response.write(request.form("fname")) response.write(" " & request.form("lname")) %> </body>
The browser will display the following in the body of the document: Welcome Divya Goel
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
An Application Cont.
<html> <body> <% fruits=Request.Form("fruits") %> <form action="checkboxes.asp" method="post"> <p>Which of these fruits do you prefer:</p> <input type="checkbox" name="fruits" value="Apples" <%if instr(fruits,"Apple") then Response.Write("checked")%>> Apple<br />
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
264
An Application Cont.
<input type="checkbox" name="fruits" value="Oranges" <%if instr(fruits,"Oranges") then Response.Write("checked")%>> Orange <br /> <input type="checkbox" name="fruits" value="Bananas" <%if instr(fruits,"Banana") then Response.Write("checked")%>>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
An Application Cont.
Banana <br /> <input type="submit" value="Submit"> </form> <% if fruits<>"" then%> <p>You like: <%Response.Write(fruits)%></p> <%end if %></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
265
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
266
Server Object
The ASP Server object is used to access the Servers properties and methods.. One of the most important ASP Server object methods is the Server.CreateObject. The Server.CreateObject method is used to create an instance of server component. Here is how to create an ADO database connection object instance, by using Server.CreateObject method:
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Connection String
Connection String What is ADOdb? An object oriented library written in PHP that abstracts database operations for portability. It is modelled on Microsoft's ADO, but has many improvements that make it unique (eg. pivot tables, generating HTML for paging recordsets with next and previous links, cached recordsets, HTML menu generation, etc).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
267
268
Another Connection String Example <% set conn=server.createobject("ADODB.connectio n") conn.open "DSN=man" set rec=conn.execute("select * from shop") rec.movefirst while not rec.eof %>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Another Connection String Example <tr><td><%=rec.fields("dat")%> </td><td > <%=rec.fields("cre")%> </td><td><%=re c.fields("name")%> </td><td><%=rec.fi elds("amount")%> </td></tr> <%rec.movenext wend%> </table> </center></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
JavaScript
JavaScript is a scripting language that enables web developers/designers to build more functional and interactive websites. Allows you to write code to control all HTML elements. CSS is used to style HTML elements. Common uses of JavaScript include: Alert messages Popup windows Dynamic dropdown menus Form validation Displaying date/time
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
269
JavaScript Cont.
JavaScript usually runs on the client-side (the browser's side), as opposed to server-side (on the web server). One benefit of doing this is performance. On the client side, JavaScript is loaded into the browser and can run as soon as it is called. Without running on the client side, the page would need to refresh each time you needed a script to run.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
JavaScript Example
<html> <body> <script type="text/javascript"> document.write("This is my first JavaScript!"); </script> </body> </html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
JavaScript Event
Event Handler onBlur Event that it handles User has left the focus of the object. For example, they clicked away from a text field that was previously selected. User has changed the object, then attempts to leave that field (i.e. clicks elsewhere). User clicked on the object. User clicked twice on the object. User brought the focus to the object (i.e. clicked on it/tabbed to it) A key was pressed over an element. A key was released over an element. A key was pressed over an element then released.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
270
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
onMousedo The cursor moved over the object and n mouse/pointing device was pressed down. onMouseup The mouse/pointing device was released after being pressed down. onMouseov The cursor moved over the object (i.e. user er hovers the mouse over the object).
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
onSubmit onUnload
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
271
Conclusion
Basic knowledge of HTML and graphic design work will go a long way in your designing a website. Database templates also facilitate you to make changes to your site much more easily, and help you change certain elements without recreating the entire page from scratch the dividends of simplicity can not be ignored and put at stake While designing a website it is important that the site is attractive, fast-loading, user friendly, focuses on your content and has a high stickiness factor to it.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #
Summary
A Web page is really just a text document in disguise and HTML tags, CSS, ASP, JavaScript, etc are used. You can cleanly organize content using headings and paragraphs. Lists can help break up content into more web-friendly chunks .Tables are grids with headings, rows and cells. Hypelinks and Animation are used to make a website more interactive.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Review Questions
Objective type questions Q1)We send and receive HTML file using which protocol? a. SMTP b. POP3 c. HTTPd. d. FTP Q2)Which sequence of HTML tags are correct? a. <html><head><title></<title></head><body></body></html> b. <html><head></head><body><title></<title></body></html> c. <html><head><title></<title><body></body></head></html> d. <html><title></<title><head></head><body></body></html>
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
272
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
273
References
1. Rick Dranell, HTML 4 unleashed, Techmedia Publication, 2000. 2. John P. Flynt,Java Programming, Second Edition, by Akash press 3. Shelley Powers, Dynamic Web Publishing, 2nd Edition, Techmedia, 1998.
Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63.
274